07f7b2617c84b0d574e6e3e0467863c64deb0a77
[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     Instruction *FoldICmpAddOpCst(ICmpInst &ICI, Value *X, ConstantInt *CI,
261                                   ICmpInst::Predicate Pred);
262     Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
263                              ICmpInst::Predicate Cond, Instruction &I);
264     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
265                                      BinaryOperator &I);
266     Instruction *commonCastTransforms(CastInst &CI);
267     Instruction *commonIntCastTransforms(CastInst &CI);
268     Instruction *commonPointerCastTransforms(CastInst &CI);
269     Instruction *visitTrunc(TruncInst &CI);
270     Instruction *visitZExt(ZExtInst &CI);
271     Instruction *visitSExt(SExtInst &CI);
272     Instruction *visitFPTrunc(FPTruncInst &CI);
273     Instruction *visitFPExt(CastInst &CI);
274     Instruction *visitFPToUI(FPToUIInst &FI);
275     Instruction *visitFPToSI(FPToSIInst &FI);
276     Instruction *visitUIToFP(CastInst &CI);
277     Instruction *visitSIToFP(CastInst &CI);
278     Instruction *visitPtrToInt(PtrToIntInst &CI);
279     Instruction *visitIntToPtr(IntToPtrInst &CI);
280     Instruction *visitBitCast(BitCastInst &CI);
281     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
282                                 Instruction *FI);
283     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
284     Instruction *visitSelectInst(SelectInst &SI);
285     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
286     Instruction *visitCallInst(CallInst &CI);
287     Instruction *visitInvokeInst(InvokeInst &II);
288
289     Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
290     Instruction *visitPHINode(PHINode &PN);
291     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
292     Instruction *visitAllocaInst(AllocaInst &AI);
293     Instruction *visitFree(Instruction &FI);
294     Instruction *visitLoadInst(LoadInst &LI);
295     Instruction *visitStoreInst(StoreInst &SI);
296     Instruction *visitBranchInst(BranchInst &BI);
297     Instruction *visitSwitchInst(SwitchInst &SI);
298     Instruction *visitInsertElementInst(InsertElementInst &IE);
299     Instruction *visitExtractElementInst(ExtractElementInst &EI);
300     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
301     Instruction *visitExtractValueInst(ExtractValueInst &EV);
302
303     // visitInstruction - Specify what to return for unhandled instructions...
304     Instruction *visitInstruction(Instruction &I) { return 0; }
305
306   private:
307     Instruction *visitCallSite(CallSite CS);
308     bool transformConstExprCastCall(CallSite CS);
309     Instruction *transformCallThroughTrampoline(CallSite CS);
310     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
311                                    bool DoXform = true);
312     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
313     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
314
315
316   public:
317     // InsertNewInstBefore - insert an instruction New before instruction Old
318     // in the program.  Add the new instruction to the worklist.
319     //
320     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
321       assert(New && New->getParent() == 0 &&
322              "New instruction already inserted into a basic block!");
323       BasicBlock *BB = Old.getParent();
324       BB->getInstList().insert(&Old, New);  // Insert inst
325       Worklist.Add(New);
326       return New;
327     }
328         
329     // ReplaceInstUsesWith - This method is to be used when an instruction is
330     // found to be dead, replacable with another preexisting expression.  Here
331     // we add all uses of I to the worklist, replace all uses of I with the new
332     // value, then return I, so that the inst combiner will know that I was
333     // modified.
334     //
335     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
336       Worklist.AddUsersToWorkList(I);   // Add all modified instrs to worklist.
337       
338       // If we are replacing the instruction with itself, this must be in a
339       // segment of unreachable code, so just clobber the instruction.
340       if (&I == V) 
341         V = UndefValue::get(I.getType());
342         
343       I.replaceAllUsesWith(V);
344       return &I;
345     }
346
347     // EraseInstFromFunction - When dealing with an instruction that has side
348     // effects or produces a void value, we can't rely on DCE to delete the
349     // instruction.  Instead, visit methods should return the value returned by
350     // this function.
351     Instruction *EraseInstFromFunction(Instruction &I) {
352       DEBUG(errs() << "IC: ERASE " << I << '\n');
353
354       assert(I.use_empty() && "Cannot erase instruction that is used!");
355       // Make sure that we reprocess all operands now that we reduced their
356       // use counts.
357       if (I.getNumOperands() < 8) {
358         for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
359           if (Instruction *Op = dyn_cast<Instruction>(*i))
360             Worklist.Add(Op);
361       }
362       Worklist.Remove(&I);
363       I.eraseFromParent();
364       MadeIRChange = true;
365       return 0;  // Don't do anything with FI
366     }
367         
368     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
369                            APInt &KnownOne, unsigned Depth = 0) const {
370       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
371     }
372     
373     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
374                            unsigned Depth = 0) const {
375       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
376     }
377     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
378       return llvm::ComputeNumSignBits(Op, TD, Depth);
379     }
380
381   private:
382
383     /// SimplifyCommutative - This performs a few simplifications for 
384     /// commutative operators.
385     bool SimplifyCommutative(BinaryOperator &I);
386
387     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
388     /// based on the demanded bits.
389     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
390                                    APInt& KnownZero, APInt& KnownOne,
391                                    unsigned Depth);
392     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
393                               APInt& KnownZero, APInt& KnownOne,
394                               unsigned Depth=0);
395         
396     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
397     /// SimplifyDemandedBits knows about.  See if the instruction has any
398     /// properties that allow us to simplify its operands.
399     bool SimplifyDemandedInstructionBits(Instruction &Inst);
400         
401     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
402                                       APInt& UndefElts, unsigned Depth = 0);
403       
404     // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
405     // which has a PHI node as operand #0, see if we can fold the instruction
406     // into the PHI (which is only possible if all operands to the PHI are
407     // constants).
408     //
409     // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
410     // that would normally be unprofitable because they strongly encourage jump
411     // threading.
412     Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
413
414     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
415     // operator and they all are only used by the PHI, PHI together their
416     // inputs, and do the operation once, to the result of the PHI.
417     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
418     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
419     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
420     Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
421
422     
423     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
424                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
425     
426     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
427                               bool isSub, Instruction &I);
428     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
429                                  bool isSigned, bool Inside, Instruction &IB);
430     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
431     Instruction *MatchBSwap(BinaryOperator &I);
432     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
433     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
434     Instruction *SimplifyMemSet(MemSetInst *MI);
435
436
437     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
438
439     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
440                                     unsigned CastOpc, int &NumCastsRemoved);
441     unsigned GetOrEnforceKnownAlignment(Value *V,
442                                         unsigned PrefAlign = 0);
443
444   };
445 } // end anonymous namespace
446
447 char InstCombiner::ID = 0;
448 static RegisterPass<InstCombiner>
449 X("instcombine", "Combine redundant instructions");
450
451 // getComplexity:  Assign a complexity or rank value to LLVM Values...
452 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
453 static unsigned getComplexity(Value *V) {
454   if (isa<Instruction>(V)) {
455     if (BinaryOperator::isNeg(V) ||
456         BinaryOperator::isFNeg(V) ||
457         BinaryOperator::isNot(V))
458       return 3;
459     return 4;
460   }
461   if (isa<Argument>(V)) return 3;
462   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
463 }
464
465 // isOnlyUse - Return true if this instruction will be deleted if we stop using
466 // it.
467 static bool isOnlyUse(Value *V) {
468   return V->hasOneUse() || isa<Constant>(V);
469 }
470
471 // getPromotedType - Return the specified type promoted as it would be to pass
472 // though a va_arg area...
473 static const Type *getPromotedType(const Type *Ty) {
474   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
475     if (ITy->getBitWidth() < 32)
476       return Type::getInt32Ty(Ty->getContext());
477   }
478   return Ty;
479 }
480
481 /// ShouldChangeType - Return true if it is desirable to convert a computation
482 /// from 'From' to 'To'.  We don't want to convert from a legal to an illegal
483 /// type for example, or from a smaller to a larger illegal type.
484 static bool ShouldChangeType(const Type *From, const Type *To,
485                              const TargetData *TD) {
486   assert(isa<IntegerType>(From) && isa<IntegerType>(To));
487   
488   // If we don't have TD, we don't know if the source/dest are legal.
489   if (!TD) return false;
490   
491   unsigned FromWidth = From->getPrimitiveSizeInBits();
492   unsigned ToWidth = To->getPrimitiveSizeInBits();
493   bool FromLegal = TD->isLegalInteger(FromWidth);
494   bool ToLegal = TD->isLegalInteger(ToWidth);
495   
496   // If this is a legal integer from type, and the result would be an illegal
497   // type, don't do the transformation.
498   if (FromLegal && !ToLegal)
499     return false;
500   
501   // Otherwise, if both are illegal, do not increase the size of the result. We
502   // do allow things like i160 -> i64, but not i64 -> i160.
503   if (!FromLegal && !ToLegal && ToWidth > FromWidth)
504     return false;
505   
506   return true;
507 }
508
509 /// getBitCastOperand - If the specified operand is a CastInst, a constant
510 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
511 /// operand value, otherwise return null.
512 static Value *getBitCastOperand(Value *V) {
513   if (Operator *O = dyn_cast<Operator>(V)) {
514     if (O->getOpcode() == Instruction::BitCast)
515       return O->getOperand(0);
516     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
517       if (GEP->hasAllZeroIndices())
518         return GEP->getPointerOperand();
519   }
520   return 0;
521 }
522
523 /// This function is a wrapper around CastInst::isEliminableCastPair. It
524 /// simply extracts arguments and returns what that function returns.
525 static Instruction::CastOps 
526 isEliminableCastPair(
527   const CastInst *CI, ///< The first cast instruction
528   unsigned opcode,       ///< The opcode of the second cast instruction
529   const Type *DstTy,     ///< The target type for the second cast instruction
530   TargetData *TD         ///< The target data for pointer size
531 ) {
532
533   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
534   const Type *MidTy = CI->getType();                  // B from above
535
536   // Get the opcodes of the two Cast instructions
537   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
538   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
539
540   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
541                                                 DstTy,
542                                   TD ? TD->getIntPtrType(CI->getContext()) : 0);
543   
544   // We don't want to form an inttoptr or ptrtoint that converts to an integer
545   // type that differs from the pointer size.
546   if ((Res == Instruction::IntToPtr &&
547           (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
548       (Res == Instruction::PtrToInt &&
549           (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
550     Res = 0;
551   
552   return Instruction::CastOps(Res);
553 }
554
555 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
556 /// in any code being generated.  It does not require codegen if V is simple
557 /// enough or if the cast can be folded into other casts.
558 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
559                               const Type *Ty, TargetData *TD) {
560   if (V->getType() == Ty || isa<Constant>(V)) return false;
561   
562   // If this is another cast that can be eliminated, it isn't codegen either.
563   if (const CastInst *CI = dyn_cast<CastInst>(V))
564     if (isEliminableCastPair(CI, opcode, Ty, TD))
565       return false;
566   return true;
567 }
568
569 // SimplifyCommutative - This performs a few simplifications for commutative
570 // operators:
571 //
572 //  1. Order operands such that they are listed from right (least complex) to
573 //     left (most complex).  This puts constants before unary operators before
574 //     binary operators.
575 //
576 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
577 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
578 //
579 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
580   bool Changed = false;
581   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
582     Changed = !I.swapOperands();
583
584   if (!I.isAssociative()) return Changed;
585   Instruction::BinaryOps Opcode = I.getOpcode();
586   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
587     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
588       if (isa<Constant>(I.getOperand(1))) {
589         Constant *Folded = ConstantExpr::get(I.getOpcode(),
590                                              cast<Constant>(I.getOperand(1)),
591                                              cast<Constant>(Op->getOperand(1)));
592         I.setOperand(0, Op->getOperand(0));
593         I.setOperand(1, Folded);
594         return true;
595       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
596         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
597             isOnlyUse(Op) && isOnlyUse(Op1)) {
598           Constant *C1 = cast<Constant>(Op->getOperand(1));
599           Constant *C2 = cast<Constant>(Op1->getOperand(1));
600
601           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
602           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
603           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
604                                                     Op1->getOperand(0),
605                                                     Op1->getName(), &I);
606           Worklist.Add(New);
607           I.setOperand(0, New);
608           I.setOperand(1, Folded);
609           return true;
610         }
611     }
612   return Changed;
613 }
614
615 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
616 // if the LHS is a constant zero (which is the 'negate' form).
617 //
618 static inline Value *dyn_castNegVal(Value *V) {
619   if (BinaryOperator::isNeg(V))
620     return BinaryOperator::getNegArgument(V);
621
622   // Constants can be considered to be negated values if they can be folded.
623   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
624     return ConstantExpr::getNeg(C);
625
626   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
627     if (C->getType()->getElementType()->isInteger())
628       return ConstantExpr::getNeg(C);
629
630   return 0;
631 }
632
633 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
634 // instruction if the LHS is a constant negative zero (which is the 'negate'
635 // form).
636 //
637 static inline Value *dyn_castFNegVal(Value *V) {
638   if (BinaryOperator::isFNeg(V))
639     return BinaryOperator::getFNegArgument(V);
640
641   // Constants can be considered to be negated values if they can be folded.
642   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
643     return ConstantExpr::getFNeg(C);
644
645   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
646     if (C->getType()->getElementType()->isFloatingPoint())
647       return ConstantExpr::getFNeg(C);
648
649   return 0;
650 }
651
652 /// isFreeToInvert - Return true if the specified value is free to invert (apply
653 /// ~ to).  This happens in cases where the ~ can be eliminated.
654 static inline bool isFreeToInvert(Value *V) {
655   // ~(~(X)) -> X.
656   if (BinaryOperator::isNot(V))
657     return true;
658   
659   // Constants can be considered to be not'ed values.
660   if (isa<ConstantInt>(V))
661     return true;
662   
663   // Compares can be inverted if they have a single use.
664   if (CmpInst *CI = dyn_cast<CmpInst>(V))
665     return CI->hasOneUse();
666   
667   return false;
668 }
669
670 static inline Value *dyn_castNotVal(Value *V) {
671   // If this is not(not(x)) don't return that this is a not: we want the two
672   // not's to be folded first.
673   if (BinaryOperator::isNot(V)) {
674     Value *Operand = BinaryOperator::getNotArgument(V);
675     if (!isFreeToInvert(Operand))
676       return Operand;
677   }
678
679   // Constants can be considered to be not'ed values...
680   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
681     return ConstantInt::get(C->getType(), ~C->getValue());
682   return 0;
683 }
684
685
686
687 // dyn_castFoldableMul - If this value is a multiply that can be folded into
688 // other computations (because it has a constant operand), return the
689 // non-constant operand of the multiply, and set CST to point to the multiplier.
690 // Otherwise, return null.
691 //
692 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
693   if (V->hasOneUse() && V->getType()->isInteger())
694     if (Instruction *I = dyn_cast<Instruction>(V)) {
695       if (I->getOpcode() == Instruction::Mul)
696         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
697           return I->getOperand(0);
698       if (I->getOpcode() == Instruction::Shl)
699         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
700           // The multiplier is really 1 << CST.
701           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
702           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
703           CST = ConstantInt::get(V->getType()->getContext(),
704                                  APInt(BitWidth, 1).shl(CSTVal));
705           return I->getOperand(0);
706         }
707     }
708   return 0;
709 }
710
711 /// AddOne - Add one to a ConstantInt
712 static Constant *AddOne(Constant *C) {
713   return ConstantExpr::getAdd(C, 
714     ConstantInt::get(C->getType(), 1));
715 }
716 /// SubOne - Subtract one from a ConstantInt
717 static Constant *SubOne(ConstantInt *C) {
718   return ConstantExpr::getSub(C, 
719     ConstantInt::get(C->getType(), 1));
720 }
721 /// MultiplyOverflows - True if the multiply can not be expressed in an int
722 /// this size.
723 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
724   uint32_t W = C1->getBitWidth();
725   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
726   if (sign) {
727     LHSExt.sext(W * 2);
728     RHSExt.sext(W * 2);
729   } else {
730     LHSExt.zext(W * 2);
731     RHSExt.zext(W * 2);
732   }
733
734   APInt MulExt = LHSExt * RHSExt;
735
736   if (sign) {
737     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
738     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
739     return MulExt.slt(Min) || MulExt.sgt(Max);
740   } else 
741     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
742 }
743
744
745 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
746 /// specified instruction is a constant integer.  If so, check to see if there
747 /// are any bits set in the constant that are not demanded.  If so, shrink the
748 /// constant and return true.
749 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
750                                    APInt Demanded) {
751   assert(I && "No instruction?");
752   assert(OpNo < I->getNumOperands() && "Operand index too large");
753
754   // If the operand is not a constant integer, nothing to do.
755   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
756   if (!OpC) return false;
757
758   // If there are no bits set that aren't demanded, nothing to do.
759   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
760   if ((~Demanded & OpC->getValue()) == 0)
761     return false;
762
763   // This instruction is producing bits that are not demanded. Shrink the RHS.
764   Demanded &= OpC->getValue();
765   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
766   return true;
767 }
768
769 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
770 // set of known zero and one bits, compute the maximum and minimum values that
771 // could have the specified known zero and known one bits, returning them in
772 // min/max.
773 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
774                                                    const APInt& KnownOne,
775                                                    APInt& Min, APInt& Max) {
776   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
777          KnownZero.getBitWidth() == Min.getBitWidth() &&
778          KnownZero.getBitWidth() == Max.getBitWidth() &&
779          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
780   APInt UnknownBits = ~(KnownZero|KnownOne);
781
782   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
783   // bit if it is unknown.
784   Min = KnownOne;
785   Max = KnownOne|UnknownBits;
786   
787   if (UnknownBits.isNegative()) { // Sign bit is unknown
788     Min.set(Min.getBitWidth()-1);
789     Max.clear(Max.getBitWidth()-1);
790   }
791 }
792
793 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
794 // a set of known zero and one bits, compute the maximum and minimum values that
795 // could have the specified known zero and known one bits, returning them in
796 // min/max.
797 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
798                                                      const APInt &KnownOne,
799                                                      APInt &Min, APInt &Max) {
800   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
801          KnownZero.getBitWidth() == Min.getBitWidth() &&
802          KnownZero.getBitWidth() == Max.getBitWidth() &&
803          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
804   APInt UnknownBits = ~(KnownZero|KnownOne);
805   
806   // The minimum value is when the unknown bits are all zeros.
807   Min = KnownOne;
808   // The maximum value is when the unknown bits are all ones.
809   Max = KnownOne|UnknownBits;
810 }
811
812 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
813 /// SimplifyDemandedBits knows about.  See if the instruction has any
814 /// properties that allow us to simplify its operands.
815 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
816   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
817   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
818   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
819   
820   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
821                                      KnownZero, KnownOne, 0);
822   if (V == 0) return false;
823   if (V == &Inst) return true;
824   ReplaceInstUsesWith(Inst, V);
825   return true;
826 }
827
828 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
829 /// specified instruction operand if possible, updating it in place.  It returns
830 /// true if it made any change and false otherwise.
831 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
832                                         APInt &KnownZero, APInt &KnownOne,
833                                         unsigned Depth) {
834   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
835                                           KnownZero, KnownOne, Depth);
836   if (NewVal == 0) return false;
837   U = NewVal;
838   return true;
839 }
840
841
842 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
843 /// value based on the demanded bits.  When this function is called, it is known
844 /// that only the bits set in DemandedMask of the result of V are ever used
845 /// downstream. Consequently, depending on the mask and V, it may be possible
846 /// to replace V with a constant or one of its operands. In such cases, this
847 /// function does the replacement and returns true. In all other cases, it
848 /// returns false after analyzing the expression and setting KnownOne and known
849 /// to be one in the expression.  KnownZero contains all the bits that are known
850 /// to be zero in the expression. These are provided to potentially allow the
851 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
852 /// the expression. KnownOne and KnownZero always follow the invariant that 
853 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
854 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
855 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
856 /// and KnownOne must all be the same.
857 ///
858 /// This returns null if it did not change anything and it permits no
859 /// simplification.  This returns V itself if it did some simplification of V's
860 /// operands based on the information about what bits are demanded. This returns
861 /// some other non-null value if it found out that V is equal to another value
862 /// in the context where the specified bits are demanded, but not for all users.
863 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
864                                              APInt &KnownZero, APInt &KnownOne,
865                                              unsigned Depth) {
866   assert(V != 0 && "Null pointer of Value???");
867   assert(Depth <= 6 && "Limit Search Depth");
868   uint32_t BitWidth = DemandedMask.getBitWidth();
869   const Type *VTy = V->getType();
870   assert((TD || !isa<PointerType>(VTy)) &&
871          "SimplifyDemandedBits needs to know bit widths!");
872   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
873          (!VTy->isIntOrIntVector() ||
874           VTy->getScalarSizeInBits() == BitWidth) &&
875          KnownZero.getBitWidth() == BitWidth &&
876          KnownOne.getBitWidth() == BitWidth &&
877          "Value *V, DemandedMask, KnownZero and KnownOne "
878          "must have same BitWidth");
879   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
880     // We know all of the bits for a constant!
881     KnownOne = CI->getValue() & DemandedMask;
882     KnownZero = ~KnownOne & DemandedMask;
883     return 0;
884   }
885   if (isa<ConstantPointerNull>(V)) {
886     // We know all of the bits for a constant!
887     KnownOne.clear();
888     KnownZero = DemandedMask;
889     return 0;
890   }
891
892   KnownZero.clear();
893   KnownOne.clear();
894   if (DemandedMask == 0) {   // Not demanding any bits from V.
895     if (isa<UndefValue>(V))
896       return 0;
897     return UndefValue::get(VTy);
898   }
899   
900   if (Depth == 6)        // Limit search depth.
901     return 0;
902   
903   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
904   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
905
906   Instruction *I = dyn_cast<Instruction>(V);
907   if (!I) {
908     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
909     return 0;        // Only analyze instructions.
910   }
911
912   // If there are multiple uses of this value and we aren't at the root, then
913   // we can't do any simplifications of the operands, because DemandedMask
914   // only reflects the bits demanded by *one* of the users.
915   if (Depth != 0 && !I->hasOneUse()) {
916     // Despite the fact that we can't simplify this instruction in all User's
917     // context, we can at least compute the knownzero/knownone bits, and we can
918     // do simplifications that apply to *just* the one user if we know that
919     // this instruction has a simpler value in that context.
920     if (I->getOpcode() == Instruction::And) {
921       // If either the LHS or the RHS are Zero, the result is zero.
922       ComputeMaskedBits(I->getOperand(1), DemandedMask,
923                         RHSKnownZero, RHSKnownOne, Depth+1);
924       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
925                         LHSKnownZero, LHSKnownOne, Depth+1);
926       
927       // If all of the demanded bits are known 1 on one side, return the other.
928       // These bits cannot contribute to the result of the 'and' in this
929       // context.
930       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
931           (DemandedMask & ~LHSKnownZero))
932         return I->getOperand(0);
933       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
934           (DemandedMask & ~RHSKnownZero))
935         return I->getOperand(1);
936       
937       // If all of the demanded bits in the inputs are known zeros, return zero.
938       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
939         return Constant::getNullValue(VTy);
940       
941     } else if (I->getOpcode() == Instruction::Or) {
942       // We can simplify (X|Y) -> X or Y in the user's context if we know that
943       // only bits from X or Y are demanded.
944       
945       // If either the LHS or the RHS are One, the result is One.
946       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
947                         RHSKnownZero, RHSKnownOne, Depth+1);
948       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
949                         LHSKnownZero, LHSKnownOne, Depth+1);
950       
951       // If all of the demanded bits are known zero on one side, return the
952       // other.  These bits cannot contribute to the result of the 'or' in this
953       // context.
954       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
955           (DemandedMask & ~LHSKnownOne))
956         return I->getOperand(0);
957       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
958           (DemandedMask & ~RHSKnownOne))
959         return I->getOperand(1);
960       
961       // If all of the potentially set bits on one side are known to be set on
962       // the other side, just use the 'other' side.
963       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
964           (DemandedMask & (~RHSKnownZero)))
965         return I->getOperand(0);
966       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
967           (DemandedMask & (~LHSKnownZero)))
968         return I->getOperand(1);
969     }
970     
971     // Compute the KnownZero/KnownOne bits to simplify things downstream.
972     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
973     return 0;
974   }
975   
976   // If this is the root being simplified, allow it to have multiple uses,
977   // just set the DemandedMask to all bits so that we can try to simplify the
978   // operands.  This allows visitTruncInst (for example) to simplify the
979   // operand of a trunc without duplicating all the logic below.
980   if (Depth == 0 && !V->hasOneUse())
981     DemandedMask = APInt::getAllOnesValue(BitWidth);
982   
983   switch (I->getOpcode()) {
984   default:
985     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
986     break;
987   case Instruction::And:
988     // If either the LHS or the RHS are Zero, the result is zero.
989     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
990                              RHSKnownZero, RHSKnownOne, Depth+1) ||
991         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
992                              LHSKnownZero, LHSKnownOne, Depth+1))
993       return I;
994     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
995     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
996
997     // If all of the demanded bits are known 1 on one side, return the other.
998     // These bits cannot contribute to the result of the 'and'.
999     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
1000         (DemandedMask & ~LHSKnownZero))
1001       return I->getOperand(0);
1002     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
1003         (DemandedMask & ~RHSKnownZero))
1004       return I->getOperand(1);
1005     
1006     // If all of the demanded bits in the inputs are known zeros, return zero.
1007     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1008       return Constant::getNullValue(VTy);
1009       
1010     // If the RHS is a constant, see if we can simplify it.
1011     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1012       return I;
1013       
1014     // Output known-1 bits are only known if set in both the LHS & RHS.
1015     RHSKnownOne &= LHSKnownOne;
1016     // Output known-0 are known to be clear if zero in either the LHS | RHS.
1017     RHSKnownZero |= LHSKnownZero;
1018     break;
1019   case Instruction::Or:
1020     // If either the LHS or the RHS are One, the result is One.
1021     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1022                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1023         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
1024                              LHSKnownZero, LHSKnownOne, Depth+1))
1025       return I;
1026     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1027     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1028     
1029     // If all of the demanded bits are known zero on one side, return the other.
1030     // These bits cannot contribute to the result of the 'or'.
1031     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
1032         (DemandedMask & ~LHSKnownOne))
1033       return I->getOperand(0);
1034     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
1035         (DemandedMask & ~RHSKnownOne))
1036       return I->getOperand(1);
1037
1038     // If all of the potentially set bits on one side are known to be set on
1039     // the other side, just use the 'other' side.
1040     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
1041         (DemandedMask & (~RHSKnownZero)))
1042       return I->getOperand(0);
1043     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1044         (DemandedMask & (~LHSKnownZero)))
1045       return I->getOperand(1);
1046         
1047     // If the RHS is a constant, see if we can simplify it.
1048     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1049       return I;
1050           
1051     // Output known-0 bits are only known if clear in both the LHS & RHS.
1052     RHSKnownZero &= LHSKnownZero;
1053     // Output known-1 are known to be set if set in either the LHS | RHS.
1054     RHSKnownOne |= LHSKnownOne;
1055     break;
1056   case Instruction::Xor: {
1057     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1058                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1059         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1060                              LHSKnownZero, LHSKnownOne, Depth+1))
1061       return I;
1062     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1063     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1064     
1065     // If all of the demanded bits are known zero on one side, return the other.
1066     // These bits cannot contribute to the result of the 'xor'.
1067     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1068       return I->getOperand(0);
1069     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1070       return I->getOperand(1);
1071     
1072     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1073     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1074                          (RHSKnownOne & LHSKnownOne);
1075     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1076     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1077                         (RHSKnownOne & LHSKnownZero);
1078     
1079     // If all of the demanded bits are known to be zero on one side or the
1080     // other, turn this into an *inclusive* or.
1081     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1082     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1083       Instruction *Or = 
1084         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1085                                  I->getName());
1086       return InsertNewInstBefore(Or, *I);
1087     }
1088     
1089     // If all of the demanded bits on one side are known, and all of the set
1090     // bits on that side are also known to be set on the other side, turn this
1091     // into an AND, as we know the bits will be cleared.
1092     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1093     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1094       // all known
1095       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1096         Constant *AndC = Constant::getIntegerValue(VTy,
1097                                                    ~RHSKnownOne & DemandedMask);
1098         Instruction *And = 
1099           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1100         return InsertNewInstBefore(And, *I);
1101       }
1102     }
1103     
1104     // If the RHS is a constant, see if we can simplify it.
1105     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1106     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1107       return I;
1108     
1109     // If our LHS is an 'and' and if it has one use, and if any of the bits we
1110     // are flipping are known to be set, then the xor is just resetting those
1111     // bits to zero.  We can just knock out bits from the 'and' and the 'xor',
1112     // simplifying both of them.
1113     if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1114       if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1115           isa<ConstantInt>(I->getOperand(1)) &&
1116           isa<ConstantInt>(LHSInst->getOperand(1)) &&
1117           (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1118         ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1119         ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1120         APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1121         
1122         Constant *AndC =
1123           ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1124         Instruction *NewAnd = 
1125           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1126         InsertNewInstBefore(NewAnd, *I);
1127         
1128         Constant *XorC =
1129           ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1130         Instruction *NewXor =
1131           BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1132         return InsertNewInstBefore(NewXor, *I);
1133       }
1134           
1135           
1136     RHSKnownZero = KnownZeroOut;
1137     RHSKnownOne  = KnownOneOut;
1138     break;
1139   }
1140   case Instruction::Select:
1141     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1142                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1143         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1144                              LHSKnownZero, LHSKnownOne, Depth+1))
1145       return I;
1146     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1147     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1148     
1149     // If the operands are constants, see if we can simplify them.
1150     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1151         ShrinkDemandedConstant(I, 2, DemandedMask))
1152       return I;
1153     
1154     // Only known if known in both the LHS and RHS.
1155     RHSKnownOne &= LHSKnownOne;
1156     RHSKnownZero &= LHSKnownZero;
1157     break;
1158   case Instruction::Trunc: {
1159     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1160     DemandedMask.zext(truncBf);
1161     RHSKnownZero.zext(truncBf);
1162     RHSKnownOne.zext(truncBf);
1163     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1164                              RHSKnownZero, RHSKnownOne, Depth+1))
1165       return I;
1166     DemandedMask.trunc(BitWidth);
1167     RHSKnownZero.trunc(BitWidth);
1168     RHSKnownOne.trunc(BitWidth);
1169     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1170     break;
1171   }
1172   case Instruction::BitCast:
1173     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1174       return false;  // vector->int or fp->int?
1175
1176     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1177       if (const VectorType *SrcVTy =
1178             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1179         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1180           // Don't touch a bitcast between vectors of different element counts.
1181           return false;
1182       } else
1183         // Don't touch a scalar-to-vector bitcast.
1184         return false;
1185     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1186       // Don't touch a vector-to-scalar bitcast.
1187       return false;
1188
1189     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1190                              RHSKnownZero, RHSKnownOne, Depth+1))
1191       return I;
1192     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1193     break;
1194   case Instruction::ZExt: {
1195     // Compute the bits in the result that are not present in the input.
1196     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1197     
1198     DemandedMask.trunc(SrcBitWidth);
1199     RHSKnownZero.trunc(SrcBitWidth);
1200     RHSKnownOne.trunc(SrcBitWidth);
1201     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1202                              RHSKnownZero, RHSKnownOne, Depth+1))
1203       return I;
1204     DemandedMask.zext(BitWidth);
1205     RHSKnownZero.zext(BitWidth);
1206     RHSKnownOne.zext(BitWidth);
1207     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1208     // The top bits are known to be zero.
1209     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1210     break;
1211   }
1212   case Instruction::SExt: {
1213     // Compute the bits in the result that are not present in the input.
1214     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1215     
1216     APInt InputDemandedBits = DemandedMask & 
1217                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1218
1219     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1220     // If any of the sign extended bits are demanded, we know that the sign
1221     // bit is demanded.
1222     if ((NewBits & DemandedMask) != 0)
1223       InputDemandedBits.set(SrcBitWidth-1);
1224       
1225     InputDemandedBits.trunc(SrcBitWidth);
1226     RHSKnownZero.trunc(SrcBitWidth);
1227     RHSKnownOne.trunc(SrcBitWidth);
1228     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1229                              RHSKnownZero, RHSKnownOne, Depth+1))
1230       return I;
1231     InputDemandedBits.zext(BitWidth);
1232     RHSKnownZero.zext(BitWidth);
1233     RHSKnownOne.zext(BitWidth);
1234     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1235       
1236     // If the sign bit of the input is known set or clear, then we know the
1237     // top bits of the result.
1238
1239     // If the input sign bit is known zero, or if the NewBits are not demanded
1240     // convert this into a zero extension.
1241     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1242       // Convert to ZExt cast
1243       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1244       return InsertNewInstBefore(NewCast, *I);
1245     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1246       RHSKnownOne |= NewBits;
1247     }
1248     break;
1249   }
1250   case Instruction::Add: {
1251     // Figure out what the input bits are.  If the top bits of the and result
1252     // are not demanded, then the add doesn't demand them from its input
1253     // either.
1254     unsigned NLZ = DemandedMask.countLeadingZeros();
1255       
1256     // If there is a constant on the RHS, there are a variety of xformations
1257     // we can do.
1258     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1259       // If null, this should be simplified elsewhere.  Some of the xforms here
1260       // won't work if the RHS is zero.
1261       if (RHS->isZero())
1262         break;
1263       
1264       // If the top bit of the output is demanded, demand everything from the
1265       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1266       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1267
1268       // Find information about known zero/one bits in the input.
1269       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1270                                LHSKnownZero, LHSKnownOne, Depth+1))
1271         return I;
1272
1273       // If the RHS of the add has bits set that can't affect the input, reduce
1274       // the constant.
1275       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1276         return I;
1277       
1278       // Avoid excess work.
1279       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1280         break;
1281       
1282       // Turn it into OR if input bits are zero.
1283       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1284         Instruction *Or =
1285           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1286                                    I->getName());
1287         return InsertNewInstBefore(Or, *I);
1288       }
1289       
1290       // We can say something about the output known-zero and known-one bits,
1291       // depending on potential carries from the input constant and the
1292       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1293       // bits set and the RHS constant is 0x01001, then we know we have a known
1294       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1295       
1296       // To compute this, we first compute the potential carry bits.  These are
1297       // the bits which may be modified.  I'm not aware of a better way to do
1298       // this scan.
1299       const APInt &RHSVal = RHS->getValue();
1300       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1301       
1302       // Now that we know which bits have carries, compute the known-1/0 sets.
1303       
1304       // Bits are known one if they are known zero in one operand and one in the
1305       // other, and there is no input carry.
1306       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1307                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1308       
1309       // Bits are known zero if they are known zero in both operands and there
1310       // is no input carry.
1311       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1312     } else {
1313       // If the high-bits of this ADD are not demanded, then it does not demand
1314       // the high bits of its LHS or RHS.
1315       if (DemandedMask[BitWidth-1] == 0) {
1316         // Right fill the mask of bits for this ADD to demand the most
1317         // significant bit and all those below it.
1318         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1319         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1320                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1321             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1322                                  LHSKnownZero, LHSKnownOne, Depth+1))
1323           return I;
1324       }
1325     }
1326     break;
1327   }
1328   case Instruction::Sub:
1329     // If the high-bits of this SUB are not demanded, then it does not demand
1330     // the high bits of its LHS or RHS.
1331     if (DemandedMask[BitWidth-1] == 0) {
1332       // Right fill the mask of bits for this SUB to demand the most
1333       // significant bit and all those below it.
1334       uint32_t NLZ = DemandedMask.countLeadingZeros();
1335       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1336       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1337                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1338           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1339                                LHSKnownZero, LHSKnownOne, Depth+1))
1340         return I;
1341     }
1342     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1343     // the known zeros and ones.
1344     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1345     break;
1346   case Instruction::Shl:
1347     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1348       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1349       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1350       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1351                                RHSKnownZero, RHSKnownOne, Depth+1))
1352         return I;
1353       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1354       RHSKnownZero <<= ShiftAmt;
1355       RHSKnownOne  <<= ShiftAmt;
1356       // low bits known zero.
1357       if (ShiftAmt)
1358         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1359     }
1360     break;
1361   case Instruction::LShr:
1362     // For a logical shift right
1363     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1364       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1365       
1366       // Unsigned shift right.
1367       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1368       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1369                                RHSKnownZero, RHSKnownOne, Depth+1))
1370         return I;
1371       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1372       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1373       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1374       if (ShiftAmt) {
1375         // Compute the new bits that are at the top now.
1376         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1377         RHSKnownZero |= HighBits;  // high bits known zero.
1378       }
1379     }
1380     break;
1381   case Instruction::AShr:
1382     // If this is an arithmetic shift right and only the low-bit is set, we can
1383     // always convert this into a logical shr, even if the shift amount is
1384     // variable.  The low bit of the shift cannot be an input sign bit unless
1385     // the shift amount is >= the size of the datatype, which is undefined.
1386     if (DemandedMask == 1) {
1387       // Perform the logical shift right.
1388       Instruction *NewVal = BinaryOperator::CreateLShr(
1389                         I->getOperand(0), I->getOperand(1), I->getName());
1390       return InsertNewInstBefore(NewVal, *I);
1391     }    
1392
1393     // If the sign bit is the only bit demanded by this ashr, then there is no
1394     // need to do it, the shift doesn't change the high bit.
1395     if (DemandedMask.isSignBit())
1396       return I->getOperand(0);
1397     
1398     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1399       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1400       
1401       // Signed shift right.
1402       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1403       // If any of the "high bits" are demanded, we should set the sign bit as
1404       // demanded.
1405       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1406         DemandedMaskIn.set(BitWidth-1);
1407       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1408                                RHSKnownZero, RHSKnownOne, Depth+1))
1409         return I;
1410       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1411       // Compute the new bits that are at the top now.
1412       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1413       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1414       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1415         
1416       // Handle the sign bits.
1417       APInt SignBit(APInt::getSignBit(BitWidth));
1418       // Adjust to where it is now in the mask.
1419       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1420         
1421       // If the input sign bit is known to be zero, or if none of the top bits
1422       // are demanded, turn this into an unsigned shift right.
1423       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1424           (HighBits & ~DemandedMask) == HighBits) {
1425         // Perform the logical shift right.
1426         Instruction *NewVal = BinaryOperator::CreateLShr(
1427                           I->getOperand(0), SA, I->getName());
1428         return InsertNewInstBefore(NewVal, *I);
1429       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1430         RHSKnownOne |= HighBits;
1431       }
1432     }
1433     break;
1434   case Instruction::SRem:
1435     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1436       APInt RA = Rem->getValue().abs();
1437       if (RA.isPowerOf2()) {
1438         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1439           return I->getOperand(0);
1440
1441         APInt LowBits = RA - 1;
1442         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1443         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1444                                  LHSKnownZero, LHSKnownOne, Depth+1))
1445           return I;
1446
1447         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1448           LHSKnownZero |= ~LowBits;
1449
1450         KnownZero |= LHSKnownZero & DemandedMask;
1451
1452         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1453       }
1454     }
1455     break;
1456   case Instruction::URem: {
1457     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1458     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1459     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1460                              KnownZero2, KnownOne2, Depth+1) ||
1461         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1462                              KnownZero2, KnownOne2, Depth+1))
1463       return I;
1464
1465     unsigned Leaders = KnownZero2.countLeadingOnes();
1466     Leaders = std::max(Leaders,
1467                        KnownZero2.countLeadingOnes());
1468     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1469     break;
1470   }
1471   case Instruction::Call:
1472     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1473       switch (II->getIntrinsicID()) {
1474       default: break;
1475       case Intrinsic::bswap: {
1476         // If the only bits demanded come from one byte of the bswap result,
1477         // just shift the input byte into position to eliminate the bswap.
1478         unsigned NLZ = DemandedMask.countLeadingZeros();
1479         unsigned NTZ = DemandedMask.countTrailingZeros();
1480           
1481         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1482         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1483         // have 14 leading zeros, round to 8.
1484         NLZ &= ~7;
1485         NTZ &= ~7;
1486         // If we need exactly one byte, we can do this transformation.
1487         if (BitWidth-NLZ-NTZ == 8) {
1488           unsigned ResultBit = NTZ;
1489           unsigned InputBit = BitWidth-NTZ-8;
1490           
1491           // Replace this with either a left or right shift to get the byte into
1492           // the right place.
1493           Instruction *NewVal;
1494           if (InputBit > ResultBit)
1495             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1496                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1497           else
1498             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1499                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1500           NewVal->takeName(I);
1501           return InsertNewInstBefore(NewVal, *I);
1502         }
1503           
1504         // TODO: Could compute known zero/one bits based on the input.
1505         break;
1506       }
1507       }
1508     }
1509     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1510     break;
1511   }
1512   
1513   // If the client is only demanding bits that we know, return the known
1514   // constant.
1515   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1516     return Constant::getIntegerValue(VTy, RHSKnownOne);
1517   return false;
1518 }
1519
1520
1521 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1522 /// any number of elements. DemandedElts contains the set of elements that are
1523 /// actually used by the caller.  This method analyzes which elements of the
1524 /// operand are undef and returns that information in UndefElts.
1525 ///
1526 /// If the information about demanded elements can be used to simplify the
1527 /// operation, the operation is simplified, then the resultant value is
1528 /// returned.  This returns null if no change was made.
1529 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1530                                                 APInt& UndefElts,
1531                                                 unsigned Depth) {
1532   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1533   APInt EltMask(APInt::getAllOnesValue(VWidth));
1534   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1535
1536   if (isa<UndefValue>(V)) {
1537     // If the entire vector is undefined, just return this info.
1538     UndefElts = EltMask;
1539     return 0;
1540   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1541     UndefElts = EltMask;
1542     return UndefValue::get(V->getType());
1543   }
1544
1545   UndefElts = 0;
1546   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1547     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1548     Constant *Undef = UndefValue::get(EltTy);
1549
1550     std::vector<Constant*> Elts;
1551     for (unsigned i = 0; i != VWidth; ++i)
1552       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1553         Elts.push_back(Undef);
1554         UndefElts.set(i);
1555       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1556         Elts.push_back(Undef);
1557         UndefElts.set(i);
1558       } else {                               // Otherwise, defined.
1559         Elts.push_back(CP->getOperand(i));
1560       }
1561
1562     // If we changed the constant, return it.
1563     Constant *NewCP = ConstantVector::get(Elts);
1564     return NewCP != CP ? NewCP : 0;
1565   } else if (isa<ConstantAggregateZero>(V)) {
1566     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1567     // set to undef.
1568     
1569     // Check if this is identity. If so, return 0 since we are not simplifying
1570     // anything.
1571     if (DemandedElts == ((1ULL << VWidth) -1))
1572       return 0;
1573     
1574     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1575     Constant *Zero = Constant::getNullValue(EltTy);
1576     Constant *Undef = UndefValue::get(EltTy);
1577     std::vector<Constant*> Elts;
1578     for (unsigned i = 0; i != VWidth; ++i) {
1579       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1580       Elts.push_back(Elt);
1581     }
1582     UndefElts = DemandedElts ^ EltMask;
1583     return ConstantVector::get(Elts);
1584   }
1585   
1586   // Limit search depth.
1587   if (Depth == 10)
1588     return 0;
1589
1590   // If multiple users are using the root value, procede with
1591   // simplification conservatively assuming that all elements
1592   // are needed.
1593   if (!V->hasOneUse()) {
1594     // Quit if we find multiple users of a non-root value though.
1595     // They'll be handled when it's their turn to be visited by
1596     // the main instcombine process.
1597     if (Depth != 0)
1598       // TODO: Just compute the UndefElts information recursively.
1599       return 0;
1600
1601     // Conservatively assume that all elements are needed.
1602     DemandedElts = EltMask;
1603   }
1604   
1605   Instruction *I = dyn_cast<Instruction>(V);
1606   if (!I) return 0;        // Only analyze instructions.
1607   
1608   bool MadeChange = false;
1609   APInt UndefElts2(VWidth, 0);
1610   Value *TmpV;
1611   switch (I->getOpcode()) {
1612   default: break;
1613     
1614   case Instruction::InsertElement: {
1615     // If this is a variable index, we don't know which element it overwrites.
1616     // demand exactly the same input as we produce.
1617     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1618     if (Idx == 0) {
1619       // Note that we can't propagate undef elt info, because we don't know
1620       // which elt is getting updated.
1621       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1622                                         UndefElts2, Depth+1);
1623       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1624       break;
1625     }
1626     
1627     // If this is inserting an element that isn't demanded, remove this
1628     // insertelement.
1629     unsigned IdxNo = Idx->getZExtValue();
1630     if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1631       Worklist.Add(I);
1632       return I->getOperand(0);
1633     }
1634     
1635     // Otherwise, the element inserted overwrites whatever was there, so the
1636     // input demanded set is simpler than the output set.
1637     APInt DemandedElts2 = DemandedElts;
1638     DemandedElts2.clear(IdxNo);
1639     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1640                                       UndefElts, Depth+1);
1641     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1642
1643     // The inserted element is defined.
1644     UndefElts.clear(IdxNo);
1645     break;
1646   }
1647   case Instruction::ShuffleVector: {
1648     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1649     uint64_t LHSVWidth =
1650       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1651     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1652     for (unsigned i = 0; i < VWidth; i++) {
1653       if (DemandedElts[i]) {
1654         unsigned MaskVal = Shuffle->getMaskValue(i);
1655         if (MaskVal != -1u) {
1656           assert(MaskVal < LHSVWidth * 2 &&
1657                  "shufflevector mask index out of range!");
1658           if (MaskVal < LHSVWidth)
1659             LeftDemanded.set(MaskVal);
1660           else
1661             RightDemanded.set(MaskVal - LHSVWidth);
1662         }
1663       }
1664     }
1665
1666     APInt UndefElts4(LHSVWidth, 0);
1667     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1668                                       UndefElts4, Depth+1);
1669     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1670
1671     APInt UndefElts3(LHSVWidth, 0);
1672     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1673                                       UndefElts3, Depth+1);
1674     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1675
1676     bool NewUndefElts = false;
1677     for (unsigned i = 0; i < VWidth; i++) {
1678       unsigned MaskVal = Shuffle->getMaskValue(i);
1679       if (MaskVal == -1u) {
1680         UndefElts.set(i);
1681       } else if (MaskVal < LHSVWidth) {
1682         if (UndefElts4[MaskVal]) {
1683           NewUndefElts = true;
1684           UndefElts.set(i);
1685         }
1686       } else {
1687         if (UndefElts3[MaskVal - LHSVWidth]) {
1688           NewUndefElts = true;
1689           UndefElts.set(i);
1690         }
1691       }
1692     }
1693
1694     if (NewUndefElts) {
1695       // Add additional discovered undefs.
1696       std::vector<Constant*> Elts;
1697       for (unsigned i = 0; i < VWidth; ++i) {
1698         if (UndefElts[i])
1699           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
1700         else
1701           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
1702                                           Shuffle->getMaskValue(i)));
1703       }
1704       I->setOperand(2, ConstantVector::get(Elts));
1705       MadeChange = true;
1706     }
1707     break;
1708   }
1709   case Instruction::BitCast: {
1710     // Vector->vector casts only.
1711     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1712     if (!VTy) break;
1713     unsigned InVWidth = VTy->getNumElements();
1714     APInt InputDemandedElts(InVWidth, 0);
1715     unsigned Ratio;
1716
1717     if (VWidth == InVWidth) {
1718       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1719       // elements as are demanded of us.
1720       Ratio = 1;
1721       InputDemandedElts = DemandedElts;
1722     } else if (VWidth > InVWidth) {
1723       // Untested so far.
1724       break;
1725       
1726       // If there are more elements in the result than there are in the source,
1727       // then an input element is live if any of the corresponding output
1728       // elements are live.
1729       Ratio = VWidth/InVWidth;
1730       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1731         if (DemandedElts[OutIdx])
1732           InputDemandedElts.set(OutIdx/Ratio);
1733       }
1734     } else {
1735       // Untested so far.
1736       break;
1737       
1738       // If there are more elements in the source than there are in the result,
1739       // then an input element is live if the corresponding output element is
1740       // live.
1741       Ratio = InVWidth/VWidth;
1742       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1743         if (DemandedElts[InIdx/Ratio])
1744           InputDemandedElts.set(InIdx);
1745     }
1746     
1747     // div/rem demand all inputs, because they don't want divide by zero.
1748     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1749                                       UndefElts2, Depth+1);
1750     if (TmpV) {
1751       I->setOperand(0, TmpV);
1752       MadeChange = true;
1753     }
1754     
1755     UndefElts = UndefElts2;
1756     if (VWidth > InVWidth) {
1757       llvm_unreachable("Unimp");
1758       // If there are more elements in the result than there are in the source,
1759       // then an output element is undef if the corresponding input element is
1760       // undef.
1761       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1762         if (UndefElts2[OutIdx/Ratio])
1763           UndefElts.set(OutIdx);
1764     } else if (VWidth < InVWidth) {
1765       llvm_unreachable("Unimp");
1766       // If there are more elements in the source than there are in the result,
1767       // then a result element is undef if all of the corresponding input
1768       // elements are undef.
1769       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1770       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1771         if (!UndefElts2[InIdx])            // Not undef?
1772           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1773     }
1774     break;
1775   }
1776   case Instruction::And:
1777   case Instruction::Or:
1778   case Instruction::Xor:
1779   case Instruction::Add:
1780   case Instruction::Sub:
1781   case Instruction::Mul:
1782     // div/rem demand all inputs, because they don't want divide by zero.
1783     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1784                                       UndefElts, Depth+1);
1785     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1786     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1787                                       UndefElts2, Depth+1);
1788     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1789       
1790     // Output elements are undefined if both are undefined.  Consider things
1791     // like undef&0.  The result is known zero, not undef.
1792     UndefElts &= UndefElts2;
1793     break;
1794     
1795   case Instruction::Call: {
1796     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1797     if (!II) break;
1798     switch (II->getIntrinsicID()) {
1799     default: break;
1800       
1801     // Binary vector operations that work column-wise.  A dest element is a
1802     // function of the corresponding input elements from the two inputs.
1803     case Intrinsic::x86_sse_sub_ss:
1804     case Intrinsic::x86_sse_mul_ss:
1805     case Intrinsic::x86_sse_min_ss:
1806     case Intrinsic::x86_sse_max_ss:
1807     case Intrinsic::x86_sse2_sub_sd:
1808     case Intrinsic::x86_sse2_mul_sd:
1809     case Intrinsic::x86_sse2_min_sd:
1810     case Intrinsic::x86_sse2_max_sd:
1811       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1812                                         UndefElts, Depth+1);
1813       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1814       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1815                                         UndefElts2, Depth+1);
1816       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1817
1818       // If only the low elt is demanded and this is a scalarizable intrinsic,
1819       // scalarize it now.
1820       if (DemandedElts == 1) {
1821         switch (II->getIntrinsicID()) {
1822         default: break;
1823         case Intrinsic::x86_sse_sub_ss:
1824         case Intrinsic::x86_sse_mul_ss:
1825         case Intrinsic::x86_sse2_sub_sd:
1826         case Intrinsic::x86_sse2_mul_sd:
1827           // TODO: Lower MIN/MAX/ABS/etc
1828           Value *LHS = II->getOperand(1);
1829           Value *RHS = II->getOperand(2);
1830           // Extract the element as scalars.
1831           LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS, 
1832             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1833           RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1834             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1835           
1836           switch (II->getIntrinsicID()) {
1837           default: llvm_unreachable("Case stmts out of sync!");
1838           case Intrinsic::x86_sse_sub_ss:
1839           case Intrinsic::x86_sse2_sub_sd:
1840             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1841                                                         II->getName()), *II);
1842             break;
1843           case Intrinsic::x86_sse_mul_ss:
1844           case Intrinsic::x86_sse2_mul_sd:
1845             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1846                                                          II->getName()), *II);
1847             break;
1848           }
1849           
1850           Instruction *New =
1851             InsertElementInst::Create(
1852               UndefValue::get(II->getType()), TmpV,
1853               ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
1854           InsertNewInstBefore(New, *II);
1855           return New;
1856         }            
1857       }
1858         
1859       // Output elements are undefined if both are undefined.  Consider things
1860       // like undef&0.  The result is known zero, not undef.
1861       UndefElts &= UndefElts2;
1862       break;
1863     }
1864     break;
1865   }
1866   }
1867   return MadeChange ? I : 0;
1868 }
1869
1870
1871 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1872 /// function is designed to check a chain of associative operators for a
1873 /// potential to apply a certain optimization.  Since the optimization may be
1874 /// applicable if the expression was reassociated, this checks the chain, then
1875 /// reassociates the expression as necessary to expose the optimization
1876 /// opportunity.  This makes use of a special Functor, which must define
1877 /// 'shouldApply' and 'apply' methods.
1878 ///
1879 template<typename Functor>
1880 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1881   unsigned Opcode = Root.getOpcode();
1882   Value *LHS = Root.getOperand(0);
1883
1884   // Quick check, see if the immediate LHS matches...
1885   if (F.shouldApply(LHS))
1886     return F.apply(Root);
1887
1888   // Otherwise, if the LHS is not of the same opcode as the root, return.
1889   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1890   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1891     // Should we apply this transform to the RHS?
1892     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1893
1894     // If not to the RHS, check to see if we should apply to the LHS...
1895     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1896       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1897       ShouldApply = true;
1898     }
1899
1900     // If the functor wants to apply the optimization to the RHS of LHSI,
1901     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1902     if (ShouldApply) {
1903       // Now all of the instructions are in the current basic block, go ahead
1904       // and perform the reassociation.
1905       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1906
1907       // First move the selected RHS to the LHS of the root...
1908       Root.setOperand(0, LHSI->getOperand(1));
1909
1910       // Make what used to be the LHS of the root be the user of the root...
1911       Value *ExtraOperand = TmpLHSI->getOperand(1);
1912       if (&Root == TmpLHSI) {
1913         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1914         return 0;
1915       }
1916       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1917       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1918       BasicBlock::iterator ARI = &Root; ++ARI;
1919       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1920       ARI = Root;
1921
1922       // Now propagate the ExtraOperand down the chain of instructions until we
1923       // get to LHSI.
1924       while (TmpLHSI != LHSI) {
1925         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1926         // Move the instruction to immediately before the chain we are
1927         // constructing to avoid breaking dominance properties.
1928         NextLHSI->moveBefore(ARI);
1929         ARI = NextLHSI;
1930
1931         Value *NextOp = NextLHSI->getOperand(1);
1932         NextLHSI->setOperand(1, ExtraOperand);
1933         TmpLHSI = NextLHSI;
1934         ExtraOperand = NextOp;
1935       }
1936
1937       // Now that the instructions are reassociated, have the functor perform
1938       // the transformation...
1939       return F.apply(Root);
1940     }
1941
1942     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1943   }
1944   return 0;
1945 }
1946
1947 namespace {
1948
1949 // AddRHS - Implements: X + X --> X << 1
1950 struct AddRHS {
1951   Value *RHS;
1952   explicit AddRHS(Value *rhs) : RHS(rhs) {}
1953   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1954   Instruction *apply(BinaryOperator &Add) const {
1955     return BinaryOperator::CreateShl(Add.getOperand(0),
1956                                      ConstantInt::get(Add.getType(), 1));
1957   }
1958 };
1959
1960 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1961 //                 iff C1&C2 == 0
1962 struct AddMaskingAnd {
1963   Constant *C2;
1964   explicit AddMaskingAnd(Constant *c) : C2(c) {}
1965   bool shouldApply(Value *LHS) const {
1966     ConstantInt *C1;
1967     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1968            ConstantExpr::getAnd(C1, C2)->isNullValue();
1969   }
1970   Instruction *apply(BinaryOperator &Add) const {
1971     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1972   }
1973 };
1974
1975 }
1976
1977 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1978                                              InstCombiner *IC) {
1979   if (CastInst *CI = dyn_cast<CastInst>(&I))
1980     return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
1981
1982   // Figure out if the constant is the left or the right argument.
1983   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1984   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1985
1986   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1987     if (ConstIsRHS)
1988       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1989     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1990   }
1991
1992   Value *Op0 = SO, *Op1 = ConstOperand;
1993   if (!ConstIsRHS)
1994     std::swap(Op0, Op1);
1995   
1996   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1997     return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1998                                     SO->getName()+".op");
1999   if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
2000     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2001                                    SO->getName()+".cmp");
2002   if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
2003     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2004                                    SO->getName()+".cmp");
2005   llvm_unreachable("Unknown binary instruction type!");
2006 }
2007
2008 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
2009 // constant as the other operand, try to fold the binary operator into the
2010 // select arguments.  This also works for Cast instructions, which obviously do
2011 // not have a second operand.
2012 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2013                                      InstCombiner *IC) {
2014   // Don't modify shared select instructions
2015   if (!SI->hasOneUse()) return 0;
2016   Value *TV = SI->getOperand(1);
2017   Value *FV = SI->getOperand(2);
2018
2019   if (isa<Constant>(TV) || isa<Constant>(FV)) {
2020     // Bool selects with constant operands can be folded to logical ops.
2021     if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
2022
2023     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2024     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2025
2026     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2027                               SelectFalseVal);
2028   }
2029   return 0;
2030 }
2031
2032
2033 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2034 /// has a PHI node as operand #0, see if we can fold the instruction into the
2035 /// PHI (which is only possible if all operands to the PHI are constants).
2036 ///
2037 /// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2038 /// that would normally be unprofitable because they strongly encourage jump
2039 /// threading.
2040 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2041                                          bool AllowAggressive) {
2042   AllowAggressive = false;
2043   PHINode *PN = cast<PHINode>(I.getOperand(0));
2044   unsigned NumPHIValues = PN->getNumIncomingValues();
2045   if (NumPHIValues == 0 ||
2046       // We normally only transform phis with a single use, unless we're trying
2047       // hard to make jump threading happen.
2048       (!PN->hasOneUse() && !AllowAggressive))
2049     return 0;
2050   
2051   
2052   // Check to see if all of the operands of the PHI are simple constants
2053   // (constantint/constantfp/undef).  If there is one non-constant value,
2054   // remember the BB it is in.  If there is more than one or if *it* is a PHI,
2055   // bail out.  We don't do arbitrary constant expressions here because moving
2056   // their computation can be expensive without a cost model.
2057   BasicBlock *NonConstBB = 0;
2058   for (unsigned i = 0; i != NumPHIValues; ++i)
2059     if (!isa<Constant>(PN->getIncomingValue(i)) ||
2060         isa<ConstantExpr>(PN->getIncomingValue(i))) {
2061       if (NonConstBB) return 0;  // More than one non-const value.
2062       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
2063       NonConstBB = PN->getIncomingBlock(i);
2064       
2065       // If the incoming non-constant value is in I's block, we have an infinite
2066       // loop.
2067       if (NonConstBB == I.getParent())
2068         return 0;
2069     }
2070   
2071   // If there is exactly one non-constant value, we can insert a copy of the
2072   // operation in that block.  However, if this is a critical edge, we would be
2073   // inserting the computation one some other paths (e.g. inside a loop).  Only
2074   // do this if the pred block is unconditionally branching into the phi block.
2075   if (NonConstBB != 0 && !AllowAggressive) {
2076     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2077     if (!BI || !BI->isUnconditional()) return 0;
2078   }
2079
2080   // Okay, we can do the transformation: create the new PHI node.
2081   PHINode *NewPN = PHINode::Create(I.getType(), "");
2082   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2083   InsertNewInstBefore(NewPN, *PN);
2084   NewPN->takeName(PN);
2085
2086   // Next, add all of the operands to the PHI.
2087   if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2088     // We only currently try to fold the condition of a select when it is a phi,
2089     // not the true/false values.
2090     Value *TrueV = SI->getTrueValue();
2091     Value *FalseV = SI->getFalseValue();
2092     BasicBlock *PhiTransBB = PN->getParent();
2093     for (unsigned i = 0; i != NumPHIValues; ++i) {
2094       BasicBlock *ThisBB = PN->getIncomingBlock(i);
2095       Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2096       Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
2097       Value *InV = 0;
2098       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2099         InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
2100       } else {
2101         assert(PN->getIncomingBlock(i) == NonConstBB);
2102         InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2103                                  FalseVInPred,
2104                                  "phitmp", NonConstBB->getTerminator());
2105         Worklist.Add(cast<Instruction>(InV));
2106       }
2107       NewPN->addIncoming(InV, ThisBB);
2108     }
2109   } else if (I.getNumOperands() == 2) {
2110     Constant *C = cast<Constant>(I.getOperand(1));
2111     for (unsigned i = 0; i != NumPHIValues; ++i) {
2112       Value *InV = 0;
2113       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2114         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2115           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2116         else
2117           InV = ConstantExpr::get(I.getOpcode(), InC, C);
2118       } else {
2119         assert(PN->getIncomingBlock(i) == NonConstBB);
2120         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2121           InV = BinaryOperator::Create(BO->getOpcode(),
2122                                        PN->getIncomingValue(i), C, "phitmp",
2123                                        NonConstBB->getTerminator());
2124         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2125           InV = CmpInst::Create(CI->getOpcode(),
2126                                 CI->getPredicate(),
2127                                 PN->getIncomingValue(i), C, "phitmp",
2128                                 NonConstBB->getTerminator());
2129         else
2130           llvm_unreachable("Unknown binop!");
2131         
2132         Worklist.Add(cast<Instruction>(InV));
2133       }
2134       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2135     }
2136   } else { 
2137     CastInst *CI = cast<CastInst>(&I);
2138     const Type *RetTy = CI->getType();
2139     for (unsigned i = 0; i != NumPHIValues; ++i) {
2140       Value *InV;
2141       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2142         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2143       } else {
2144         assert(PN->getIncomingBlock(i) == NonConstBB);
2145         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2146                                I.getType(), "phitmp", 
2147                                NonConstBB->getTerminator());
2148         Worklist.Add(cast<Instruction>(InV));
2149       }
2150       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2151     }
2152   }
2153   return ReplaceInstUsesWith(I, NewPN);
2154 }
2155
2156
2157 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2158 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2159 /// This basically requires proving that the add in the original type would not
2160 /// overflow to change the sign bit or have a carry out.
2161 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2162   // There are different heuristics we can use for this.  Here are some simple
2163   // ones.
2164   
2165   // Add has the property that adding any two 2's complement numbers can only 
2166   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2167   // have at least two sign bits, we know that the addition of the two values
2168   // will sign extend fine.
2169   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2170     return true;
2171   
2172   
2173   // If one of the operands only has one non-zero bit, and if the other operand
2174   // has a known-zero bit in a more significant place than it (not including the
2175   // sign bit) the ripple may go up to and fill the zero, but won't change the
2176   // sign.  For example, (X & ~4) + 1.
2177   
2178   // TODO: Implement.
2179   
2180   return false;
2181 }
2182
2183
2184 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2185   bool Changed = SimplifyCommutative(I);
2186   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2187
2188   if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
2189                                  I.hasNoUnsignedWrap(), TD))
2190     return ReplaceInstUsesWith(I, V);
2191
2192   
2193   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2194     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2195       // X + (signbit) --> X ^ signbit
2196       const APInt& Val = CI->getValue();
2197       uint32_t BitWidth = Val.getBitWidth();
2198       if (Val == APInt::getSignBit(BitWidth))
2199         return BinaryOperator::CreateXor(LHS, RHS);
2200       
2201       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2202       // (X & 254)+1 -> (X&254)|1
2203       if (SimplifyDemandedInstructionBits(I))
2204         return &I;
2205
2206       // zext(bool) + C -> bool ? C + 1 : C
2207       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2208         if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2209           return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2210     }
2211
2212     if (isa<PHINode>(LHS))
2213       if (Instruction *NV = FoldOpIntoPhi(I))
2214         return NV;
2215     
2216     ConstantInt *XorRHS = 0;
2217     Value *XorLHS = 0;
2218     if (isa<ConstantInt>(RHSC) &&
2219         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2220       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2221       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2222       
2223       uint32_t Size = TySizeBits / 2;
2224       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2225       APInt CFF80Val(-C0080Val);
2226       do {
2227         if (TySizeBits > Size) {
2228           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2229           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2230           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2231               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2232             // This is a sign extend if the top bits are known zero.
2233             if (!MaskedValueIsZero(XorLHS, 
2234                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2235               Size = 0;  // Not a sign ext, but can't be any others either.
2236             break;
2237           }
2238         }
2239         Size >>= 1;
2240         C0080Val = APIntOps::lshr(C0080Val, Size);
2241         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2242       } while (Size >= 1);
2243       
2244       // FIXME: This shouldn't be necessary. When the backends can handle types
2245       // with funny bit widths then this switch statement should be removed. It
2246       // is just here to get the size of the "middle" type back up to something
2247       // that the back ends can handle.
2248       const Type *MiddleType = 0;
2249       switch (Size) {
2250         default: break;
2251         case 32: MiddleType = Type::getInt32Ty(*Context); break;
2252         case 16: MiddleType = Type::getInt16Ty(*Context); break;
2253         case  8: MiddleType = Type::getInt8Ty(*Context); break;
2254       }
2255       if (MiddleType) {
2256         Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
2257         return new SExtInst(NewTrunc, I.getType(), I.getName());
2258       }
2259     }
2260   }
2261
2262   if (I.getType() == Type::getInt1Ty(*Context))
2263     return BinaryOperator::CreateXor(LHS, RHS);
2264
2265   // X + X --> X << 1
2266   if (I.getType()->isInteger()) {
2267     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2268       return Result;
2269
2270     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2271       if (RHSI->getOpcode() == Instruction::Sub)
2272         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2273           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2274     }
2275     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2276       if (LHSI->getOpcode() == Instruction::Sub)
2277         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2278           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2279     }
2280   }
2281
2282   // -A + B  -->  B - A
2283   // -A + -B  -->  -(A + B)
2284   if (Value *LHSV = dyn_castNegVal(LHS)) {
2285     if (LHS->getType()->isIntOrIntVector()) {
2286       if (Value *RHSV = dyn_castNegVal(RHS)) {
2287         Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
2288         return BinaryOperator::CreateNeg(NewAdd);
2289       }
2290     }
2291     
2292     return BinaryOperator::CreateSub(RHS, LHSV);
2293   }
2294
2295   // A + -B  -->  A - B
2296   if (!isa<Constant>(RHS))
2297     if (Value *V = dyn_castNegVal(RHS))
2298       return BinaryOperator::CreateSub(LHS, V);
2299
2300
2301   ConstantInt *C2;
2302   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2303     if (X == RHS)   // X*C + X --> X * (C+1)
2304       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2305
2306     // X*C1 + X*C2 --> X * (C1+C2)
2307     ConstantInt *C1;
2308     if (X == dyn_castFoldableMul(RHS, C1))
2309       return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2310   }
2311
2312   // X + X*C --> X * (C+1)
2313   if (dyn_castFoldableMul(RHS, C2) == LHS)
2314     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2315
2316   // X + ~X --> -1   since   ~X = -X-1
2317   if (dyn_castNotVal(LHS) == RHS ||
2318       dyn_castNotVal(RHS) == LHS)
2319     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2320   
2321
2322   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2323   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2324     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2325       return R;
2326   
2327   // A+B --> A|B iff A and B have no bits set in common.
2328   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2329     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2330     APInt LHSKnownOne(IT->getBitWidth(), 0);
2331     APInt LHSKnownZero(IT->getBitWidth(), 0);
2332     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2333     if (LHSKnownZero != 0) {
2334       APInt RHSKnownOne(IT->getBitWidth(), 0);
2335       APInt RHSKnownZero(IT->getBitWidth(), 0);
2336       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2337       
2338       // No bits in common -> bitwise or.
2339       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2340         return BinaryOperator::CreateOr(LHS, RHS);
2341     }
2342   }
2343
2344   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2345   if (I.getType()->isIntOrIntVector()) {
2346     Value *W, *X, *Y, *Z;
2347     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2348         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2349       if (W != Y) {
2350         if (W == Z) {
2351           std::swap(Y, Z);
2352         } else if (Y == X) {
2353           std::swap(W, X);
2354         } else if (X == Z) {
2355           std::swap(Y, Z);
2356           std::swap(W, X);
2357         }
2358       }
2359
2360       if (W == Y) {
2361         Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
2362         return BinaryOperator::CreateMul(W, NewAdd);
2363       }
2364     }
2365   }
2366
2367   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2368     Value *X = 0;
2369     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2370       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2371
2372     // (X & FF00) + xx00  -> (X+xx00) & FF00
2373     if (LHS->hasOneUse() &&
2374         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2375       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2376       if (Anded == CRHS) {
2377         // See if all bits from the first bit set in the Add RHS up are included
2378         // in the mask.  First, get the rightmost bit.
2379         const APInt& AddRHSV = CRHS->getValue();
2380
2381         // Form a mask of all bits from the lowest bit added through the top.
2382         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2383
2384         // See if the and mask includes all of these bits.
2385         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2386
2387         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2388           // Okay, the xform is safe.  Insert the new add pronto.
2389           Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
2390           return BinaryOperator::CreateAnd(NewAdd, C2);
2391         }
2392       }
2393     }
2394
2395     // Try to fold constant add into select arguments.
2396     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2397       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2398         return R;
2399   }
2400
2401   // add (select X 0 (sub n A)) A  -->  select X A n
2402   {
2403     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2404     Value *A = RHS;
2405     if (!SI) {
2406       SI = dyn_cast<SelectInst>(RHS);
2407       A = LHS;
2408     }
2409     if (SI && SI->hasOneUse()) {
2410       Value *TV = SI->getTrueValue();
2411       Value *FV = SI->getFalseValue();
2412       Value *N;
2413
2414       // Can we fold the add into the argument of the select?
2415       // We check both true and false select arguments for a matching subtract.
2416       if (match(FV, m_Zero()) &&
2417           match(TV, m_Sub(m_Value(N), m_Specific(A))))
2418         // Fold the add into the true select value.
2419         return SelectInst::Create(SI->getCondition(), N, A);
2420       if (match(TV, m_Zero()) &&
2421           match(FV, m_Sub(m_Value(N), m_Specific(A))))
2422         // Fold the add into the false select value.
2423         return SelectInst::Create(SI->getCondition(), A, N);
2424     }
2425   }
2426
2427   // Check for (add (sext x), y), see if we can merge this into an
2428   // integer add followed by a sext.
2429   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2430     // (add (sext x), cst) --> (sext (add x, cst'))
2431     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2432       Constant *CI = 
2433         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2434       if (LHSConv->hasOneUse() &&
2435           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2436           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2437         // Insert the new, smaller add.
2438         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0), 
2439                                               CI, "addconv");
2440         return new SExtInst(NewAdd, I.getType());
2441       }
2442     }
2443     
2444     // (add (sext x), (sext y)) --> (sext (add int x, y))
2445     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2446       // Only do this if x/y have the same type, if at last one of them has a
2447       // single use (so we don't increase the number of sexts), and if the
2448       // integer add will not overflow.
2449       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2450           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2451           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2452                                    RHSConv->getOperand(0))) {
2453         // Insert the new integer add.
2454         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0), 
2455                                               RHSConv->getOperand(0), "addconv");
2456         return new SExtInst(NewAdd, I.getType());
2457       }
2458     }
2459   }
2460
2461   return Changed ? &I : 0;
2462 }
2463
2464 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2465   bool Changed = SimplifyCommutative(I);
2466   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2467
2468   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2469     // X + 0 --> X
2470     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2471       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2472                               (I.getType())->getValueAPF()))
2473         return ReplaceInstUsesWith(I, LHS);
2474     }
2475
2476     if (isa<PHINode>(LHS))
2477       if (Instruction *NV = FoldOpIntoPhi(I))
2478         return NV;
2479   }
2480
2481   // -A + B  -->  B - A
2482   // -A + -B  -->  -(A + B)
2483   if (Value *LHSV = dyn_castFNegVal(LHS))
2484     return BinaryOperator::CreateFSub(RHS, LHSV);
2485
2486   // A + -B  -->  A - B
2487   if (!isa<Constant>(RHS))
2488     if (Value *V = dyn_castFNegVal(RHS))
2489       return BinaryOperator::CreateFSub(LHS, V);
2490
2491   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2492   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2493     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2494       return ReplaceInstUsesWith(I, LHS);
2495
2496   // Check for (add double (sitofp x), y), see if we can merge this into an
2497   // integer add followed by a promotion.
2498   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2499     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2500     // ... if the constant fits in the integer value.  This is useful for things
2501     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2502     // requires a constant pool load, and generally allows the add to be better
2503     // instcombined.
2504     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2505       Constant *CI = 
2506       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2507       if (LHSConv->hasOneUse() &&
2508           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2509           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2510         // Insert the new integer add.
2511         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2512                                               CI, "addconv");
2513         return new SIToFPInst(NewAdd, I.getType());
2514       }
2515     }
2516     
2517     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2518     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2519       // Only do this if x/y have the same type, if at last one of them has a
2520       // single use (so we don't increase the number of int->fp conversions),
2521       // and if the integer add will not overflow.
2522       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2523           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2524           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2525                                    RHSConv->getOperand(0))) {
2526         // Insert the new integer add.
2527         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0), 
2528                                               RHSConv->getOperand(0),"addconv");
2529         return new SIToFPInst(NewAdd, I.getType());
2530       }
2531     }
2532   }
2533   
2534   return Changed ? &I : 0;
2535 }
2536
2537
2538 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2539 /// code necessary to compute the offset from the base pointer (without adding
2540 /// in the base pointer).  Return the result as a signed integer of intptr size.
2541 static Value *EmitGEPOffset(User *GEP, InstCombiner &IC) {
2542   TargetData &TD = *IC.getTargetData();
2543   gep_type_iterator GTI = gep_type_begin(GEP);
2544   const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
2545   Value *Result = Constant::getNullValue(IntPtrTy);
2546
2547   // Build a mask for high order bits.
2548   unsigned IntPtrWidth = TD.getPointerSizeInBits();
2549   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2550
2551   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
2552        ++i, ++GTI) {
2553     Value *Op = *i;
2554     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
2555     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
2556       if (OpC->isZero()) continue;
2557       
2558       // Handle a struct index, which adds its field offset to the pointer.
2559       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2560         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
2561         
2562         Result = IC.Builder->CreateAdd(Result,
2563                                        ConstantInt::get(IntPtrTy, Size),
2564                                        GEP->getName()+".offs");
2565         continue;
2566       }
2567       
2568       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2569       Constant *OC =
2570               ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
2571       Scale = ConstantExpr::getMul(OC, Scale);
2572       // Emit an add instruction.
2573       Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
2574       continue;
2575     }
2576     // Convert to correct type.
2577     if (Op->getType() != IntPtrTy)
2578       Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
2579     if (Size != 1) {
2580       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2581       // We'll let instcombine(mul) convert this to a shl if possible.
2582       Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
2583     }
2584
2585     // Emit an add instruction.
2586     Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
2587   }
2588   return Result;
2589 }
2590
2591
2592 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
2593 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
2594 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
2595 /// be complex, and scales are involved.  The above expression would also be
2596 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
2597 /// This later form is less amenable to optimization though, and we are allowed
2598 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
2599 ///
2600 /// If we can't emit an optimized form for this expression, this returns null.
2601 /// 
2602 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
2603                                           InstCombiner &IC) {
2604   TargetData &TD = *IC.getTargetData();
2605   gep_type_iterator GTI = gep_type_begin(GEP);
2606
2607   // Check to see if this gep only has a single variable index.  If so, and if
2608   // any constant indices are a multiple of its scale, then we can compute this
2609   // in terms of the scale of the variable index.  For example, if the GEP
2610   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
2611   // because the expression will cross zero at the same point.
2612   unsigned i, e = GEP->getNumOperands();
2613   int64_t Offset = 0;
2614   for (i = 1; i != e; ++i, ++GTI) {
2615     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2616       // Compute the aggregate offset of constant indices.
2617       if (CI->isZero()) continue;
2618
2619       // Handle a struct index, which adds its field offset to the pointer.
2620       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2621         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2622       } else {
2623         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2624         Offset += Size*CI->getSExtValue();
2625       }
2626     } else {
2627       // Found our variable index.
2628       break;
2629     }
2630   }
2631   
2632   // If there are no variable indices, we must have a constant offset, just
2633   // evaluate it the general way.
2634   if (i == e) return 0;
2635   
2636   Value *VariableIdx = GEP->getOperand(i);
2637   // Determine the scale factor of the variable element.  For example, this is
2638   // 4 if the variable index is into an array of i32.
2639   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
2640   
2641   // Verify that there are no other variable indices.  If so, emit the hard way.
2642   for (++i, ++GTI; i != e; ++i, ++GTI) {
2643     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
2644     if (!CI) return 0;
2645    
2646     // Compute the aggregate offset of constant indices.
2647     if (CI->isZero()) continue;
2648     
2649     // Handle a struct index, which adds its field offset to the pointer.
2650     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2651       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2652     } else {
2653       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2654       Offset += Size*CI->getSExtValue();
2655     }
2656   }
2657   
2658   // Okay, we know we have a single variable index, which must be a
2659   // pointer/array/vector index.  If there is no offset, life is simple, return
2660   // the index.
2661   unsigned IntPtrWidth = TD.getPointerSizeInBits();
2662   if (Offset == 0) {
2663     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
2664     // we don't need to bother extending: the extension won't affect where the
2665     // computation crosses zero.
2666     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
2667       VariableIdx = new TruncInst(VariableIdx, 
2668                                   TD.getIntPtrType(VariableIdx->getContext()),
2669                                   VariableIdx->getName(), &I);
2670     return VariableIdx;
2671   }
2672   
2673   // Otherwise, there is an index.  The computation we will do will be modulo
2674   // the pointer size, so get it.
2675   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2676   
2677   Offset &= PtrSizeMask;
2678   VariableScale &= PtrSizeMask;
2679
2680   // To do this transformation, any constant index must be a multiple of the
2681   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
2682   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
2683   // multiple of the variable scale.
2684   int64_t NewOffs = Offset / (int64_t)VariableScale;
2685   if (Offset != NewOffs*(int64_t)VariableScale)
2686     return 0;
2687
2688   // Okay, we can do this evaluation.  Start by converting the index to intptr.
2689   const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
2690   if (VariableIdx->getType() != IntPtrTy)
2691     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
2692                                               true /*SExt*/, 
2693                                               VariableIdx->getName(), &I);
2694   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
2695   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
2696 }
2697
2698
2699 /// Optimize pointer differences into the same array into a size.  Consider:
2700 ///  &A[10] - &A[0]: we should compile this to "10".  LHS/RHS are the pointer
2701 /// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2702 ///
2703 Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
2704                                                const Type *Ty) {
2705   assert(TD && "Must have target data info for this");
2706   
2707   // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
2708   // this.
2709   bool Swapped;
2710   GetElementPtrInst *GEP;
2711   
2712   if ((GEP = dyn_cast<GetElementPtrInst>(LHS)) &&
2713       GEP->getOperand(0) == RHS)
2714     Swapped = false;
2715   else if ((GEP = dyn_cast<GetElementPtrInst>(RHS)) &&
2716            GEP->getOperand(0) == LHS)
2717     Swapped = true;
2718   else
2719     return 0;
2720   
2721   // TODO: Could also optimize &A[i] - &A[j] -> "i-j".
2722   
2723   // Emit the offset of the GEP and an intptr_t.
2724   Value *Result = EmitGEPOffset(GEP, *this);
2725
2726   // If we have p - gep(p, ...)  then we have to negate the result.
2727   if (Swapped)
2728     Result = Builder->CreateNeg(Result, "diff.neg");
2729
2730   return Builder->CreateIntCast(Result, Ty, true);
2731 }
2732
2733
2734 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2735   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2736
2737   if (Op0 == Op1)                        // sub X, X  -> 0
2738     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2739
2740   // If this is a 'B = x-(-A)', change to B = x+A.
2741   if (Value *V = dyn_castNegVal(Op1))
2742     return BinaryOperator::CreateAdd(Op0, V);
2743
2744   if (isa<UndefValue>(Op0))
2745     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2746   if (isa<UndefValue>(Op1))
2747     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2748   if (I.getType() == Type::getInt1Ty(*Context))
2749     return BinaryOperator::CreateXor(Op0, Op1);
2750   
2751   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2752     // Replace (-1 - A) with (~A).
2753     if (C->isAllOnesValue())
2754       return BinaryOperator::CreateNot(Op1);
2755
2756     // C - ~X == X + (1+C)
2757     Value *X = 0;
2758     if (match(Op1, m_Not(m_Value(X))))
2759       return BinaryOperator::CreateAdd(X, AddOne(C));
2760
2761     // -(X >>u 31) -> (X >>s 31)
2762     // -(X >>s 31) -> (X >>u 31)
2763     if (C->isZero()) {
2764       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2765         if (SI->getOpcode() == Instruction::LShr) {
2766           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2767             // Check to see if we are shifting out everything but the sign bit.
2768             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2769                 SI->getType()->getPrimitiveSizeInBits()-1) {
2770               // Ok, the transformation is safe.  Insert AShr.
2771               return BinaryOperator::Create(Instruction::AShr, 
2772                                           SI->getOperand(0), CU, SI->getName());
2773             }
2774           }
2775         } else if (SI->getOpcode() == Instruction::AShr) {
2776           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2777             // Check to see if we are shifting out everything but the sign bit.
2778             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2779                 SI->getType()->getPrimitiveSizeInBits()-1) {
2780               // Ok, the transformation is safe.  Insert LShr. 
2781               return BinaryOperator::CreateLShr(
2782                                           SI->getOperand(0), CU, SI->getName());
2783             }
2784           }
2785         }
2786       }
2787     }
2788
2789     // Try to fold constant sub into select arguments.
2790     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2791       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2792         return R;
2793
2794     // C - zext(bool) -> bool ? C - 1 : C
2795     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2796       if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2797         return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2798   }
2799
2800   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2801     if (Op1I->getOpcode() == Instruction::Add) {
2802       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2803         return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2804                                          I.getName());
2805       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2806         return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2807                                          I.getName());
2808       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2809         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2810           // C1-(X+C2) --> (C1-C2)-X
2811           return BinaryOperator::CreateSub(
2812             ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2813       }
2814     }
2815
2816     if (Op1I->hasOneUse()) {
2817       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2818       // is not used by anyone else...
2819       //
2820       if (Op1I->getOpcode() == Instruction::Sub) {
2821         // Swap the two operands of the subexpr...
2822         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2823         Op1I->setOperand(0, IIOp1);
2824         Op1I->setOperand(1, IIOp0);
2825
2826         // Create the new top level add instruction...
2827         return BinaryOperator::CreateAdd(Op0, Op1);
2828       }
2829
2830       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2831       //
2832       if (Op1I->getOpcode() == Instruction::And &&
2833           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2834         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2835
2836         Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
2837         return BinaryOperator::CreateAnd(Op0, NewNot);
2838       }
2839
2840       // 0 - (X sdiv C)  -> (X sdiv -C)
2841       if (Op1I->getOpcode() == Instruction::SDiv)
2842         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2843           if (CSI->isZero())
2844             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2845               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2846                                           ConstantExpr::getNeg(DivRHS));
2847
2848       // X - X*C --> X * (1-C)
2849       ConstantInt *C2 = 0;
2850       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2851         Constant *CP1 = 
2852           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2853                                              C2);
2854         return BinaryOperator::CreateMul(Op0, CP1);
2855       }
2856     }
2857   }
2858
2859   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2860     if (Op0I->getOpcode() == Instruction::Add) {
2861       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2862         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2863       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2864         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2865     } else if (Op0I->getOpcode() == Instruction::Sub) {
2866       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2867         return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2868                                          I.getName());
2869     }
2870   }
2871
2872   ConstantInt *C1;
2873   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2874     if (X == Op1)  // X*C - X --> X * (C-1)
2875       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2876
2877     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2878     if (X == dyn_castFoldableMul(Op1, C2))
2879       return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2880   }
2881   
2882   // Optimize pointer differences into the same array into a size.  Consider:
2883   //  &A[10] - &A[0]: we should compile this to "10".
2884   if (TD) {
2885     if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(Op0))
2886       if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(Op1))
2887         if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2888                                                    RHS->getOperand(0),
2889                                                    I.getType()))
2890           return ReplaceInstUsesWith(I, Res);
2891     
2892     // trunc(p)-trunc(q) -> trunc(p-q)
2893     if (TruncInst *LHST = dyn_cast<TruncInst>(Op0))
2894       if (TruncInst *RHST = dyn_cast<TruncInst>(Op1))
2895         if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(LHST->getOperand(0)))
2896           if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(RHST->getOperand(0)))
2897             if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2898                                                        RHS->getOperand(0),
2899                                                        I.getType()))
2900               return ReplaceInstUsesWith(I, Res);
2901   }
2902   
2903   return 0;
2904 }
2905
2906 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2907   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2908
2909   // If this is a 'B = x-(-A)', change to B = x+A...
2910   if (Value *V = dyn_castFNegVal(Op1))
2911     return BinaryOperator::CreateFAdd(Op0, V);
2912
2913   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2914     if (Op1I->getOpcode() == Instruction::FAdd) {
2915       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2916         return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
2917                                           I.getName());
2918       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2919         return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
2920                                           I.getName());
2921     }
2922   }
2923
2924   return 0;
2925 }
2926
2927 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2928 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2929 /// TrueIfSigned if the result of the comparison is true when the input value is
2930 /// signed.
2931 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2932                            bool &TrueIfSigned) {
2933   switch (pred) {
2934   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2935     TrueIfSigned = true;
2936     return RHS->isZero();
2937   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2938     TrueIfSigned = true;
2939     return RHS->isAllOnesValue();
2940   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2941     TrueIfSigned = false;
2942     return RHS->isAllOnesValue();
2943   case ICmpInst::ICMP_UGT:
2944     // True if LHS u> RHS and RHS == high-bit-mask - 1
2945     TrueIfSigned = true;
2946     return RHS->getValue() ==
2947       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2948   case ICmpInst::ICMP_UGE: 
2949     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2950     TrueIfSigned = true;
2951     return RHS->getValue().isSignBit();
2952   default:
2953     return false;
2954   }
2955 }
2956
2957 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2958   bool Changed = SimplifyCommutative(I);
2959   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2960
2961   if (isa<UndefValue>(Op1))              // undef * X -> 0
2962     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2963
2964   // Simplify mul instructions with a constant RHS.
2965   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2966     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
2967
2968       // ((X << C1)*C2) == (X * (C2 << C1))
2969       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2970         if (SI->getOpcode() == Instruction::Shl)
2971           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2972             return BinaryOperator::CreateMul(SI->getOperand(0),
2973                                         ConstantExpr::getShl(CI, ShOp));
2974
2975       if (CI->isZero())
2976         return ReplaceInstUsesWith(I, Op1C);  // X * 0  == 0
2977       if (CI->equalsInt(1))                  // X * 1  == X
2978         return ReplaceInstUsesWith(I, Op0);
2979       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2980         return BinaryOperator::CreateNeg(Op0, I.getName());
2981
2982       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2983       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2984         return BinaryOperator::CreateShl(Op0,
2985                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2986       }
2987     } else if (isa<VectorType>(Op1C->getType())) {
2988       if (Op1C->isNullValue())
2989         return ReplaceInstUsesWith(I, Op1C);
2990
2991       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
2992         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2993           return BinaryOperator::CreateNeg(Op0, I.getName());
2994
2995         // As above, vector X*splat(1.0) -> X in all defined cases.
2996         if (Constant *Splat = Op1V->getSplatValue()) {
2997           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2998             if (CI->equalsInt(1))
2999               return ReplaceInstUsesWith(I, Op0);
3000         }
3001       }
3002     }
3003     
3004     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3005       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
3006           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
3007         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
3008         Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
3009         Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
3010         return BinaryOperator::CreateAdd(Add, C1C2);
3011         
3012       }
3013
3014     // Try to fold constant mul into select arguments.
3015     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3016       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3017         return R;
3018
3019     if (isa<PHINode>(Op0))
3020       if (Instruction *NV = FoldOpIntoPhi(I))
3021         return NV;
3022   }
3023
3024   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
3025     if (Value *Op1v = dyn_castNegVal(Op1))
3026       return BinaryOperator::CreateMul(Op0v, Op1v);
3027
3028   // (X / Y) *  Y = X - (X % Y)
3029   // (X / Y) * -Y = (X % Y) - X
3030   {
3031     Value *Op1C = Op1;
3032     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
3033     if (!BO ||
3034         (BO->getOpcode() != Instruction::UDiv && 
3035          BO->getOpcode() != Instruction::SDiv)) {
3036       Op1C = Op0;
3037       BO = dyn_cast<BinaryOperator>(Op1);
3038     }
3039     Value *Neg = dyn_castNegVal(Op1C);
3040     if (BO && BO->hasOneUse() &&
3041         (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
3042         (BO->getOpcode() == Instruction::UDiv ||
3043          BO->getOpcode() == Instruction::SDiv)) {
3044       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
3045
3046       // If the division is exact, X % Y is zero.
3047       if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
3048         if (SDiv->isExact()) {
3049           if (Op1BO == Op1C)
3050             return ReplaceInstUsesWith(I, Op0BO);
3051           return BinaryOperator::CreateNeg(Op0BO);
3052         }
3053
3054       Value *Rem;
3055       if (BO->getOpcode() == Instruction::UDiv)
3056         Rem = Builder->CreateURem(Op0BO, Op1BO);
3057       else
3058         Rem = Builder->CreateSRem(Op0BO, Op1BO);
3059       Rem->takeName(BO);
3060
3061       if (Op1BO == Op1C)
3062         return BinaryOperator::CreateSub(Op0BO, Rem);
3063       return BinaryOperator::CreateSub(Rem, Op0BO);
3064     }
3065   }
3066
3067   /// i1 mul -> i1 and.
3068   if (I.getType() == Type::getInt1Ty(*Context))
3069     return BinaryOperator::CreateAnd(Op0, Op1);
3070
3071   // X*(1 << Y) --> X << Y
3072   // (1 << Y)*X --> X << Y
3073   {
3074     Value *Y;
3075     if (match(Op0, m_Shl(m_One(), m_Value(Y))))
3076       return BinaryOperator::CreateShl(Op1, Y);
3077     if (match(Op1, m_Shl(m_One(), m_Value(Y))))
3078       return BinaryOperator::CreateShl(Op0, Y);
3079   }
3080   
3081   // If one of the operands of the multiply is a cast from a boolean value, then
3082   // we know the bool is either zero or one, so this is a 'masking' multiply.
3083   //   X * Y (where Y is 0 or 1) -> X & (0-Y)
3084   if (!isa<VectorType>(I.getType())) {
3085     // -2 is "-1 << 1" so it is all bits set except the low one.
3086     APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
3087     
3088     Value *BoolCast = 0, *OtherOp = 0;
3089     if (MaskedValueIsZero(Op0, Negative2))
3090       BoolCast = Op0, OtherOp = Op1;
3091     else if (MaskedValueIsZero(Op1, Negative2))
3092       BoolCast = Op1, OtherOp = Op0;
3093
3094     if (BoolCast) {
3095       Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
3096                                     BoolCast, "tmp");
3097       return BinaryOperator::CreateAnd(V, OtherOp);
3098     }
3099   }
3100
3101   return Changed ? &I : 0;
3102 }
3103
3104 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
3105   bool Changed = SimplifyCommutative(I);
3106   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3107
3108   // Simplify mul instructions with a constant RHS...
3109   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3110     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
3111       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
3112       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3113       if (Op1F->isExactlyValue(1.0))
3114         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
3115     } else if (isa<VectorType>(Op1C->getType())) {
3116       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
3117         // As above, vector X*splat(1.0) -> X in all defined cases.
3118         if (Constant *Splat = Op1V->getSplatValue()) {
3119           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
3120             if (F->isExactlyValue(1.0))
3121               return ReplaceInstUsesWith(I, Op0);
3122         }
3123       }
3124     }
3125
3126     // Try to fold constant mul into select arguments.
3127     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3128       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3129         return R;
3130
3131     if (isa<PHINode>(Op0))
3132       if (Instruction *NV = FoldOpIntoPhi(I))
3133         return NV;
3134   }
3135
3136   if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
3137     if (Value *Op1v = dyn_castFNegVal(Op1))
3138       return BinaryOperator::CreateFMul(Op0v, Op1v);
3139
3140   return Changed ? &I : 0;
3141 }
3142
3143 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
3144 /// instruction.
3145 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
3146   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
3147   
3148   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
3149   int NonNullOperand = -1;
3150   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3151     if (ST->isNullValue())
3152       NonNullOperand = 2;
3153   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
3154   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3155     if (ST->isNullValue())
3156       NonNullOperand = 1;
3157   
3158   if (NonNullOperand == -1)
3159     return false;
3160   
3161   Value *SelectCond = SI->getOperand(0);
3162   
3163   // Change the div/rem to use 'Y' instead of the select.
3164   I.setOperand(1, SI->getOperand(NonNullOperand));
3165   
3166   // Okay, we know we replace the operand of the div/rem with 'Y' with no
3167   // problem.  However, the select, or the condition of the select may have
3168   // multiple uses.  Based on our knowledge that the operand must be non-zero,
3169   // propagate the known value for the select into other uses of it, and
3170   // propagate a known value of the condition into its other users.
3171   
3172   // If the select and condition only have a single use, don't bother with this,
3173   // early exit.
3174   if (SI->use_empty() && SelectCond->hasOneUse())
3175     return true;
3176   
3177   // Scan the current block backward, looking for other uses of SI.
3178   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
3179   
3180   while (BBI != BBFront) {
3181     --BBI;
3182     // If we found a call to a function, we can't assume it will return, so
3183     // information from below it cannot be propagated above it.
3184     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
3185       break;
3186     
3187     // Replace uses of the select or its condition with the known values.
3188     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
3189          I != E; ++I) {
3190       if (*I == SI) {
3191         *I = SI->getOperand(NonNullOperand);
3192         Worklist.Add(BBI);
3193       } else if (*I == SelectCond) {
3194         *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
3195                                    ConstantInt::getFalse(*Context);
3196         Worklist.Add(BBI);
3197       }
3198     }
3199     
3200     // If we past the instruction, quit looking for it.
3201     if (&*BBI == SI)
3202       SI = 0;
3203     if (&*BBI == SelectCond)
3204       SelectCond = 0;
3205     
3206     // If we ran out of things to eliminate, break out of the loop.
3207     if (SelectCond == 0 && SI == 0)
3208       break;
3209     
3210   }
3211   return true;
3212 }
3213
3214
3215 /// This function implements the transforms on div instructions that work
3216 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3217 /// used by the visitors to those instructions.
3218 /// @brief Transforms common to all three div instructions
3219 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
3220   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3221
3222   // undef / X -> 0        for integer.
3223   // undef / X -> undef    for FP (the undef could be a snan).
3224   if (isa<UndefValue>(Op0)) {
3225     if (Op0->getType()->isFPOrFPVector())
3226       return ReplaceInstUsesWith(I, Op0);
3227     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3228   }
3229
3230   // X / undef -> undef
3231   if (isa<UndefValue>(Op1))
3232     return ReplaceInstUsesWith(I, Op1);
3233
3234   return 0;
3235 }
3236
3237 /// This function implements the transforms common to both integer division
3238 /// instructions (udiv and sdiv). It is called by the visitors to those integer
3239 /// division instructions.
3240 /// @brief Common integer divide transforms
3241 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3242   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3243
3244   // (sdiv X, X) --> 1     (udiv X, X) --> 1
3245   if (Op0 == Op1) {
3246     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
3247       Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
3248       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
3249       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
3250     }
3251
3252     Constant *CI = ConstantInt::get(I.getType(), 1);
3253     return ReplaceInstUsesWith(I, CI);
3254   }
3255   
3256   if (Instruction *Common = commonDivTransforms(I))
3257     return Common;
3258   
3259   // Handle cases involving: [su]div X, (select Cond, Y, Z)
3260   // This does not apply for fdiv.
3261   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3262     return &I;
3263
3264   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3265     // div X, 1 == X
3266     if (RHS->equalsInt(1))
3267       return ReplaceInstUsesWith(I, Op0);
3268
3269     // (X / C1) / C2  -> X / (C1*C2)
3270     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3271       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3272         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3273           if (MultiplyOverflows(RHS, LHSRHS,
3274                                 I.getOpcode()==Instruction::SDiv))
3275             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3276           else 
3277             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
3278                                       ConstantExpr::getMul(RHS, LHSRHS));
3279         }
3280
3281     if (!RHS->isZero()) { // avoid X udiv 0
3282       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3283         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3284           return R;
3285       if (isa<PHINode>(Op0))
3286         if (Instruction *NV = FoldOpIntoPhi(I))
3287           return NV;
3288     }
3289   }
3290
3291   // 0 / X == 0, we don't need to preserve faults!
3292   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3293     if (LHS->equalsInt(0))
3294       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3295
3296   // It can't be division by zero, hence it must be division by one.
3297   if (I.getType() == Type::getInt1Ty(*Context))
3298     return ReplaceInstUsesWith(I, Op0);
3299
3300   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3301     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3302       // div X, 1 == X
3303       if (X->isOne())
3304         return ReplaceInstUsesWith(I, Op0);
3305   }
3306
3307   return 0;
3308 }
3309
3310 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3311   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3312
3313   // Handle the integer div common cases
3314   if (Instruction *Common = commonIDivTransforms(I))
3315     return Common;
3316
3317   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3318     // X udiv C^2 -> X >> C
3319     // Check to see if this is an unsigned division with an exact power of 2,
3320     // if so, convert to a right shift.
3321     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3322       return BinaryOperator::CreateLShr(Op0, 
3323             ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3324
3325     // X udiv C, where C >= signbit
3326     if (C->getValue().isNegative()) {
3327       Value *IC = Builder->CreateICmpULT( Op0, C);
3328       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3329                                 ConstantInt::get(I.getType(), 1));
3330     }
3331   }
3332
3333   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3334   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3335     if (RHSI->getOpcode() == Instruction::Shl &&
3336         isa<ConstantInt>(RHSI->getOperand(0))) {
3337       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3338       if (C1.isPowerOf2()) {
3339         Value *N = RHSI->getOperand(1);
3340         const Type *NTy = N->getType();
3341         if (uint32_t C2 = C1.logBase2())
3342           N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
3343         return BinaryOperator::CreateLShr(Op0, N);
3344       }
3345     }
3346   }
3347   
3348   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3349   // where C1&C2 are powers of two.
3350   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3351     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3352       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3353         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3354         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3355           // Compute the shift amounts
3356           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3357           // Construct the "on true" case of the select
3358           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3359           Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
3360   
3361           // Construct the "on false" case of the select
3362           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3363           Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
3364
3365           // construct the select instruction and return it.
3366           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3367         }
3368       }
3369   return 0;
3370 }
3371
3372 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3373   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3374
3375   // Handle the integer div common cases
3376   if (Instruction *Common = commonIDivTransforms(I))
3377     return Common;
3378
3379   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3380     // sdiv X, -1 == -X
3381     if (RHS->isAllOnesValue())
3382       return BinaryOperator::CreateNeg(Op0);
3383
3384     // sdiv X, C  -->  ashr X, log2(C)
3385     if (cast<SDivOperator>(&I)->isExact() &&
3386         RHS->getValue().isNonNegative() &&
3387         RHS->getValue().isPowerOf2()) {
3388       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3389                                             RHS->getValue().exactLogBase2());
3390       return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3391     }
3392
3393     // -X/C  -->  X/-C  provided the negation doesn't overflow.
3394     if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3395       if (isa<Constant>(Sub->getOperand(0)) &&
3396           cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3397           Sub->hasNoSignedWrap())
3398         return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3399                                           ConstantExpr::getNeg(RHS));
3400   }
3401
3402   // If the sign bits of both operands are zero (i.e. we can prove they are
3403   // unsigned inputs), turn this into a udiv.
3404   if (I.getType()->isInteger()) {
3405     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3406     if (MaskedValueIsZero(Op0, Mask)) {
3407       if (MaskedValueIsZero(Op1, Mask)) {
3408         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3409         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3410       }
3411       ConstantInt *ShiftedInt;
3412       if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3413           ShiftedInt->getValue().isPowerOf2()) {
3414         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3415         // Safe because the only negative value (1 << Y) can take on is
3416         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3417         // the sign bit set.
3418         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3419       }
3420     }
3421   }
3422   
3423   return 0;
3424 }
3425
3426 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3427   return commonDivTransforms(I);
3428 }
3429
3430 /// This function implements the transforms on rem instructions that work
3431 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3432 /// is used by the visitors to those instructions.
3433 /// @brief Transforms common to all three rem instructions
3434 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3435   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3436
3437   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3438     if (I.getType()->isFPOrFPVector())
3439       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3440     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3441   }
3442   if (isa<UndefValue>(Op1))
3443     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3444
3445   // Handle cases involving: rem X, (select Cond, Y, Z)
3446   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3447     return &I;
3448
3449   return 0;
3450 }
3451
3452 /// This function implements the transforms common to both integer remainder
3453 /// instructions (urem and srem). It is called by the visitors to those integer
3454 /// remainder instructions.
3455 /// @brief Common integer remainder transforms
3456 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3457   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3458
3459   if (Instruction *common = commonRemTransforms(I))
3460     return common;
3461
3462   // 0 % X == 0 for integer, we don't need to preserve faults!
3463   if (Constant *LHS = dyn_cast<Constant>(Op0))
3464     if (LHS->isNullValue())
3465       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3466
3467   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3468     // X % 0 == undef, we don't need to preserve faults!
3469     if (RHS->equalsInt(0))
3470       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3471     
3472     if (RHS->equalsInt(1))  // X % 1 == 0
3473       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3474
3475     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3476       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3477         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3478           return R;
3479       } else if (isa<PHINode>(Op0I)) {
3480         if (Instruction *NV = FoldOpIntoPhi(I))
3481           return NV;
3482       }
3483
3484       // See if we can fold away this rem instruction.
3485       if (SimplifyDemandedInstructionBits(I))
3486         return &I;
3487     }
3488   }
3489
3490   return 0;
3491 }
3492
3493 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3494   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3495
3496   if (Instruction *common = commonIRemTransforms(I))
3497     return common;
3498   
3499   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3500     // X urem C^2 -> X and C
3501     // Check to see if this is an unsigned remainder with an exact power of 2,
3502     // if so, convert to a bitwise and.
3503     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3504       if (C->getValue().isPowerOf2())
3505         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3506   }
3507
3508   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3509     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3510     if (RHSI->getOpcode() == Instruction::Shl &&
3511         isa<ConstantInt>(RHSI->getOperand(0))) {
3512       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3513         Constant *N1 = Constant::getAllOnesValue(I.getType());
3514         Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
3515         return BinaryOperator::CreateAnd(Op0, Add);
3516       }
3517     }
3518   }
3519
3520   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3521   // where C1&C2 are powers of two.
3522   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3523     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3524       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3525         // STO == 0 and SFO == 0 handled above.
3526         if ((STO->getValue().isPowerOf2()) && 
3527             (SFO->getValue().isPowerOf2())) {
3528           Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3529                                               SI->getName()+".t");
3530           Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3531                                                SI->getName()+".f");
3532           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3533         }
3534       }
3535   }
3536   
3537   return 0;
3538 }
3539
3540 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3541   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3542
3543   // Handle the integer rem common cases
3544   if (Instruction *Common = commonIRemTransforms(I))
3545     return Common;
3546   
3547   if (Value *RHSNeg = dyn_castNegVal(Op1))
3548     if (!isa<Constant>(RHSNeg) ||
3549         (isa<ConstantInt>(RHSNeg) &&
3550          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3551       // X % -Y -> X % Y
3552       Worklist.AddValue(I.getOperand(1));
3553       I.setOperand(1, RHSNeg);
3554       return &I;
3555     }
3556
3557   // If the sign bits of both operands are zero (i.e. we can prove they are
3558   // unsigned inputs), turn this into a urem.
3559   if (I.getType()->isInteger()) {
3560     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3561     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3562       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3563       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3564     }
3565   }
3566
3567   // If it's a constant vector, flip any negative values positive.
3568   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3569     unsigned VWidth = RHSV->getNumOperands();
3570
3571     bool hasNegative = false;
3572     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3573       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3574         if (RHS->getValue().isNegative())
3575           hasNegative = true;
3576
3577     if (hasNegative) {
3578       std::vector<Constant *> Elts(VWidth);
3579       for (unsigned i = 0; i != VWidth; ++i) {
3580         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3581           if (RHS->getValue().isNegative())
3582             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3583           else
3584             Elts[i] = RHS;
3585         }
3586       }
3587
3588       Constant *NewRHSV = ConstantVector::get(Elts);
3589       if (NewRHSV != RHSV) {
3590         Worklist.AddValue(I.getOperand(1));
3591         I.setOperand(1, NewRHSV);
3592         return &I;
3593       }
3594     }
3595   }
3596
3597   return 0;
3598 }
3599
3600 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3601   return commonRemTransforms(I);
3602 }
3603
3604 // isOneBitSet - Return true if there is exactly one bit set in the specified
3605 // constant.
3606 static bool isOneBitSet(const ConstantInt *CI) {
3607   return CI->getValue().isPowerOf2();
3608 }
3609
3610 // isHighOnes - Return true if the constant is of the form 1+0+.
3611 // This is the same as lowones(~X).
3612 static bool isHighOnes(const ConstantInt *CI) {
3613   return (~CI->getValue() + 1).isPowerOf2();
3614 }
3615
3616 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3617 /// are carefully arranged to allow folding of expressions such as:
3618 ///
3619 ///      (A < B) | (A > B) --> (A != B)
3620 ///
3621 /// Note that this is only valid if the first and second predicates have the
3622 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3623 ///
3624 /// Three bits are used to represent the condition, as follows:
3625 ///   0  A > B
3626 ///   1  A == B
3627 ///   2  A < B
3628 ///
3629 /// <=>  Value  Definition
3630 /// 000     0   Always false
3631 /// 001     1   A >  B
3632 /// 010     2   A == B
3633 /// 011     3   A >= B
3634 /// 100     4   A <  B
3635 /// 101     5   A != B
3636 /// 110     6   A <= B
3637 /// 111     7   Always true
3638 ///  
3639 static unsigned getICmpCode(const ICmpInst *ICI) {
3640   switch (ICI->getPredicate()) {
3641     // False -> 0
3642   case ICmpInst::ICMP_UGT: return 1;  // 001
3643   case ICmpInst::ICMP_SGT: return 1;  // 001
3644   case ICmpInst::ICMP_EQ:  return 2;  // 010
3645   case ICmpInst::ICMP_UGE: return 3;  // 011
3646   case ICmpInst::ICMP_SGE: return 3;  // 011
3647   case ICmpInst::ICMP_ULT: return 4;  // 100
3648   case ICmpInst::ICMP_SLT: return 4;  // 100
3649   case ICmpInst::ICMP_NE:  return 5;  // 101
3650   case ICmpInst::ICMP_ULE: return 6;  // 110
3651   case ICmpInst::ICMP_SLE: return 6;  // 110
3652     // True -> 7
3653   default:
3654     llvm_unreachable("Invalid ICmp predicate!");
3655     return 0;
3656   }
3657 }
3658
3659 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3660 /// predicate into a three bit mask. It also returns whether it is an ordered
3661 /// predicate by reference.
3662 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3663   isOrdered = false;
3664   switch (CC) {
3665   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3666   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3667   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3668   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3669   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3670   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3671   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3672   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3673   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3674   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3675   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3676   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3677   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3678   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3679     // True -> 7
3680   default:
3681     // Not expecting FCMP_FALSE and FCMP_TRUE;
3682     llvm_unreachable("Unexpected FCmp predicate!");
3683     return 0;
3684   }
3685 }
3686
3687 /// getICmpValue - This is the complement of getICmpCode, which turns an
3688 /// opcode and two operands into either a constant true or false, or a brand 
3689 /// new ICmp instruction. The sign is passed in to determine which kind
3690 /// of predicate to use in the new icmp instruction.
3691 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3692                            LLVMContext *Context) {
3693   switch (code) {
3694   default: llvm_unreachable("Illegal ICmp code!");
3695   case  0: return ConstantInt::getFalse(*Context);
3696   case  1: 
3697     if (sign)
3698       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3699     else
3700       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3701   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3702   case  3: 
3703     if (sign)
3704       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3705     else
3706       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3707   case  4: 
3708     if (sign)
3709       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3710     else
3711       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3712   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3713   case  6: 
3714     if (sign)
3715       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3716     else
3717       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3718   case  7: return ConstantInt::getTrue(*Context);
3719   }
3720 }
3721
3722 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3723 /// opcode and two operands into either a FCmp instruction. isordered is passed
3724 /// in to determine which kind of predicate to use in the new fcmp instruction.
3725 static Value *getFCmpValue(bool isordered, unsigned code,
3726                            Value *LHS, Value *RHS, LLVMContext *Context) {
3727   switch (code) {
3728   default: llvm_unreachable("Illegal FCmp code!");
3729   case  0:
3730     if (isordered)
3731       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3732     else
3733       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3734   case  1: 
3735     if (isordered)
3736       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3737     else
3738       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3739   case  2: 
3740     if (isordered)
3741       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3742     else
3743       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3744   case  3: 
3745     if (isordered)
3746       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3747     else
3748       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3749   case  4: 
3750     if (isordered)
3751       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3752     else
3753       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3754   case  5: 
3755     if (isordered)
3756       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3757     else
3758       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3759   case  6: 
3760     if (isordered)
3761       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3762     else
3763       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3764   case  7: return ConstantInt::getTrue(*Context);
3765   }
3766 }
3767
3768 /// PredicatesFoldable - Return true if both predicates match sign or if at
3769 /// least one of them is an equality comparison (which is signless).
3770 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3771   return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3772          (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3773          (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
3774 }
3775
3776 namespace { 
3777 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3778 struct FoldICmpLogical {
3779   InstCombiner &IC;
3780   Value *LHS, *RHS;
3781   ICmpInst::Predicate pred;
3782   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3783     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3784       pred(ICI->getPredicate()) {}
3785   bool shouldApply(Value *V) const {
3786     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3787       if (PredicatesFoldable(pred, ICI->getPredicate()))
3788         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3789                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3790     return false;
3791   }
3792   Instruction *apply(Instruction &Log) const {
3793     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3794     if (ICI->getOperand(0) != LHS) {
3795       assert(ICI->getOperand(1) == LHS);
3796       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3797     }
3798
3799     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3800     unsigned LHSCode = getICmpCode(ICI);
3801     unsigned RHSCode = getICmpCode(RHSICI);
3802     unsigned Code;
3803     switch (Log.getOpcode()) {
3804     case Instruction::And: Code = LHSCode & RHSCode; break;
3805     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3806     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3807     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3808     }
3809
3810     bool isSigned = RHSICI->isSigned() || ICI->isSigned();
3811     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3812     if (Instruction *I = dyn_cast<Instruction>(RV))
3813       return I;
3814     // Otherwise, it's a constant boolean value...
3815     return IC.ReplaceInstUsesWith(Log, RV);
3816   }
3817 };
3818 } // end anonymous namespace
3819
3820 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3821 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3822 // guaranteed to be a binary operator.
3823 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3824                                     ConstantInt *OpRHS,
3825                                     ConstantInt *AndRHS,
3826                                     BinaryOperator &TheAnd) {
3827   Value *X = Op->getOperand(0);
3828   Constant *Together = 0;
3829   if (!Op->isShift())
3830     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3831
3832   switch (Op->getOpcode()) {
3833   case Instruction::Xor:
3834     if (Op->hasOneUse()) {
3835       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3836       Value *And = Builder->CreateAnd(X, AndRHS);
3837       And->takeName(Op);
3838       return BinaryOperator::CreateXor(And, Together);
3839     }
3840     break;
3841   case Instruction::Or:
3842     if (Together == AndRHS) // (X | C) & C --> C
3843       return ReplaceInstUsesWith(TheAnd, AndRHS);
3844
3845     if (Op->hasOneUse() && Together != OpRHS) {
3846       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3847       Value *Or = Builder->CreateOr(X, Together);
3848       Or->takeName(Op);
3849       return BinaryOperator::CreateAnd(Or, AndRHS);
3850     }
3851     break;
3852   case Instruction::Add:
3853     if (Op->hasOneUse()) {
3854       // Adding a one to a single bit bit-field should be turned into an XOR
3855       // of the bit.  First thing to check is to see if this AND is with a
3856       // single bit constant.
3857       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3858
3859       // If there is only one bit set...
3860       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3861         // Ok, at this point, we know that we are masking the result of the
3862         // ADD down to exactly one bit.  If the constant we are adding has
3863         // no bits set below this bit, then we can eliminate the ADD.
3864         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3865
3866         // Check to see if any bits below the one bit set in AndRHSV are set.
3867         if ((AddRHS & (AndRHSV-1)) == 0) {
3868           // If not, the only thing that can effect the output of the AND is
3869           // the bit specified by AndRHSV.  If that bit is set, the effect of
3870           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3871           // no effect.
3872           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3873             TheAnd.setOperand(0, X);
3874             return &TheAnd;
3875           } else {
3876             // Pull the XOR out of the AND.
3877             Value *NewAnd = Builder->CreateAnd(X, AndRHS);
3878             NewAnd->takeName(Op);
3879             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3880           }
3881         }
3882       }
3883     }
3884     break;
3885
3886   case Instruction::Shl: {
3887     // We know that the AND will not produce any of the bits shifted in, so if
3888     // the anded constant includes them, clear them now!
3889     //
3890     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3891     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3892     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3893     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3894
3895     if (CI->getValue() == ShlMask) { 
3896     // Masking out bits that the shift already masks
3897       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3898     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3899       TheAnd.setOperand(1, CI);
3900       return &TheAnd;
3901     }
3902     break;
3903   }
3904   case Instruction::LShr:
3905   {
3906     // We know that the AND will not produce any of the bits shifted in, so if
3907     // the anded constant includes them, clear them now!  This only applies to
3908     // unsigned shifts, because a signed shr may bring in set bits!
3909     //
3910     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3911     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3912     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3913     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3914
3915     if (CI->getValue() == ShrMask) {   
3916     // Masking out bits that the shift already masks.
3917       return ReplaceInstUsesWith(TheAnd, Op);
3918     } else if (CI != AndRHS) {
3919       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3920       return &TheAnd;
3921     }
3922     break;
3923   }
3924   case Instruction::AShr:
3925     // Signed shr.
3926     // See if this is shifting in some sign extension, then masking it out
3927     // with an and.
3928     if (Op->hasOneUse()) {
3929       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3930       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3931       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3932       Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3933       if (C == AndRHS) {          // Masking out bits shifted in.
3934         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3935         // Make the argument unsigned.
3936         Value *ShVal = Op->getOperand(0);
3937         ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
3938         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3939       }
3940     }
3941     break;
3942   }
3943   return 0;
3944 }
3945
3946
3947 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3948 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3949 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3950 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3951 /// insert new instructions.
3952 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3953                                            bool isSigned, bool Inside, 
3954                                            Instruction &IB) {
3955   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3956             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3957          "Lo is not <= Hi in range emission code!");
3958     
3959   if (Inside) {
3960     if (Lo == Hi)  // Trivially false.
3961       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3962
3963     // V >= Min && V < Hi --> V < Hi
3964     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3965       ICmpInst::Predicate pred = (isSigned ? 
3966         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3967       return new ICmpInst(pred, V, Hi);
3968     }
3969
3970     // Emit V-Lo <u Hi-Lo
3971     Constant *NegLo = ConstantExpr::getNeg(Lo);
3972     Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3973     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3974     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3975   }
3976
3977   if (Lo == Hi)  // Trivially true.
3978     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3979
3980   // V < Min || V >= Hi -> V > Hi-1
3981   Hi = SubOne(cast<ConstantInt>(Hi));
3982   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3983     ICmpInst::Predicate pred = (isSigned ? 
3984         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3985     return new ICmpInst(pred, V, Hi);
3986   }
3987
3988   // Emit V-Lo >u Hi-1-Lo
3989   // Note that Hi has already had one subtracted from it, above.
3990   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3991   Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3992   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3993   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3994 }
3995
3996 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3997 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3998 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3999 // not, since all 1s are not contiguous.
4000 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
4001   const APInt& V = Val->getValue();
4002   uint32_t BitWidth = Val->getType()->getBitWidth();
4003   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
4004
4005   // look for the first zero bit after the run of ones
4006   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
4007   // look for the first non-zero bit
4008   ME = V.getActiveBits(); 
4009   return true;
4010 }
4011
4012 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
4013 /// where isSub determines whether the operator is a sub.  If we can fold one of
4014 /// the following xforms:
4015 /// 
4016 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
4017 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4018 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4019 ///
4020 /// return (A +/- B).
4021 ///
4022 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
4023                                         ConstantInt *Mask, bool isSub,
4024                                         Instruction &I) {
4025   Instruction *LHSI = dyn_cast<Instruction>(LHS);
4026   if (!LHSI || LHSI->getNumOperands() != 2 ||
4027       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
4028
4029   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
4030
4031   switch (LHSI->getOpcode()) {
4032   default: return 0;
4033   case Instruction::And:
4034     if (ConstantExpr::getAnd(N, Mask) == Mask) {
4035       // If the AndRHS is a power of two minus one (0+1+), this is simple.
4036       if ((Mask->getValue().countLeadingZeros() + 
4037            Mask->getValue().countPopulation()) == 
4038           Mask->getValue().getBitWidth())
4039         break;
4040
4041       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4042       // part, we don't need any explicit masks to take them out of A.  If that
4043       // is all N is, ignore it.
4044       uint32_t MB = 0, ME = 0;
4045       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
4046         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
4047         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
4048         if (MaskedValueIsZero(RHS, Mask))
4049           break;
4050       }
4051     }
4052     return 0;
4053   case Instruction::Or:
4054   case Instruction::Xor:
4055     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
4056     if ((Mask->getValue().countLeadingZeros() + 
4057          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
4058         && ConstantExpr::getAnd(N, Mask)->isNullValue())
4059       break;
4060     return 0;
4061   }
4062   
4063   if (isSub)
4064     return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
4065   return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
4066 }
4067
4068 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
4069 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
4070                                           ICmpInst *LHS, ICmpInst *RHS) {
4071   // (icmp eq A, null) & (icmp eq B, null) -->
4072   //     (icmp eq (ptrtoint(A)|ptrtoint(B)), 0)
4073   if (TD &&
4074       LHS->getPredicate() == ICmpInst::ICMP_EQ &&
4075       RHS->getPredicate() == ICmpInst::ICMP_EQ &&
4076       isa<ConstantPointerNull>(LHS->getOperand(1)) &&
4077       isa<ConstantPointerNull>(RHS->getOperand(1))) {
4078     const Type *IntPtrTy = TD->getIntPtrType(I.getContext());
4079     Value *A = Builder->CreatePtrToInt(LHS->getOperand(0), IntPtrTy);
4080     Value *B = Builder->CreatePtrToInt(RHS->getOperand(0), IntPtrTy);
4081     Value *NewOr = Builder->CreateOr(A, B);
4082     return new ICmpInst(ICmpInst::ICMP_EQ, NewOr,
4083                         Constant::getNullValue(IntPtrTy));
4084   }
4085   
4086   Value *Val, *Val2;
4087   ConstantInt *LHSCst, *RHSCst;
4088   ICmpInst::Predicate LHSCC, RHSCC;
4089   
4090   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
4091   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4092                          m_ConstantInt(LHSCst))) ||
4093       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4094                          m_ConstantInt(RHSCst))))
4095     return 0;
4096   
4097   if (LHSCst == RHSCst && LHSCC == RHSCC) {
4098     // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
4099     // where C is a power of 2
4100     if (LHSCC == ICmpInst::ICMP_ULT &&
4101         LHSCst->getValue().isPowerOf2()) {
4102       Value *NewOr = Builder->CreateOr(Val, Val2);
4103       return new ICmpInst(LHSCC, NewOr, LHSCst);
4104     }
4105     
4106     // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
4107     if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
4108       Value *NewOr = Builder->CreateOr(Val, Val2);
4109       return new ICmpInst(LHSCC, NewOr, LHSCst);
4110     }
4111   }
4112   
4113   // From here on, we only handle:
4114   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
4115   if (Val != Val2) return 0;
4116   
4117   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4118   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4119       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4120       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4121       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4122     return 0;
4123   
4124   // We can't fold (ugt x, C) & (sgt x, C2).
4125   if (!PredicatesFoldable(LHSCC, RHSCC))
4126     return 0;
4127     
4128   // Ensure that the larger constant is on the RHS.
4129   bool ShouldSwap;
4130   if (CmpInst::isSigned(LHSCC) ||
4131       (ICmpInst::isEquality(LHSCC) && 
4132        CmpInst::isSigned(RHSCC)))
4133     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4134   else
4135     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4136     
4137   if (ShouldSwap) {
4138     std::swap(LHS, RHS);
4139     std::swap(LHSCst, RHSCst);
4140     std::swap(LHSCC, RHSCC);
4141   }
4142
4143   // At this point, we know we have have two icmp instructions
4144   // comparing a value against two constants and and'ing the result
4145   // together.  Because of the above check, we know that we only have
4146   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
4147   // (from the FoldICmpLogical check above), that the two constants 
4148   // are not equal and that the larger constant is on the RHS
4149   assert(LHSCst != RHSCst && "Compares not folded above?");
4150
4151   switch (LHSCC) {
4152   default: llvm_unreachable("Unknown integer condition code!");
4153   case ICmpInst::ICMP_EQ:
4154     switch (RHSCC) {
4155     default: llvm_unreachable("Unknown integer condition code!");
4156     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
4157     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
4158     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
4159       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4160     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
4161     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
4162     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
4163       return ReplaceInstUsesWith(I, LHS);
4164     }
4165   case ICmpInst::ICMP_NE:
4166     switch (RHSCC) {
4167     default: llvm_unreachable("Unknown integer condition code!");
4168     case ICmpInst::ICMP_ULT:
4169       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4170         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
4171       break;                        // (X != 13 & X u< 15) -> no change
4172     case ICmpInst::ICMP_SLT:
4173       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4174         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
4175       break;                        // (X != 13 & X s< 15) -> no change
4176     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
4177     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
4178     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
4179       return ReplaceInstUsesWith(I, RHS);
4180     case ICmpInst::ICMP_NE:
4181       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
4182         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4183         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4184         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4185                             ConstantInt::get(Add->getType(), 1));
4186       }
4187       break;                        // (X != 13 & X != 15) -> no change
4188     }
4189     break;
4190   case ICmpInst::ICMP_ULT:
4191     switch (RHSCC) {
4192     default: llvm_unreachable("Unknown integer condition code!");
4193     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
4194     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
4195       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4196     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
4197       break;
4198     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
4199     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
4200       return ReplaceInstUsesWith(I, LHS);
4201     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
4202       break;
4203     }
4204     break;
4205   case ICmpInst::ICMP_SLT:
4206     switch (RHSCC) {
4207     default: llvm_unreachable("Unknown integer condition code!");
4208     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
4209     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
4210       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4211     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
4212       break;
4213     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
4214     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
4215       return ReplaceInstUsesWith(I, LHS);
4216     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
4217       break;
4218     }
4219     break;
4220   case ICmpInst::ICMP_UGT:
4221     switch (RHSCC) {
4222     default: llvm_unreachable("Unknown integer condition code!");
4223     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
4224     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
4225       return ReplaceInstUsesWith(I, RHS);
4226     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
4227       break;
4228     case ICmpInst::ICMP_NE:
4229       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4230         return new ICmpInst(LHSCC, Val, RHSCst);
4231       break;                        // (X u> 13 & X != 15) -> no change
4232     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
4233       return InsertRangeTest(Val, AddOne(LHSCst),
4234                              RHSCst, false, true, I);
4235     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
4236       break;
4237     }
4238     break;
4239   case ICmpInst::ICMP_SGT:
4240     switch (RHSCC) {
4241     default: llvm_unreachable("Unknown integer condition code!");
4242     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
4243     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
4244       return ReplaceInstUsesWith(I, RHS);
4245     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
4246       break;
4247     case ICmpInst::ICMP_NE:
4248       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4249         return new ICmpInst(LHSCC, Val, RHSCst);
4250       break;                        // (X s> 13 & X != 15) -> no change
4251     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
4252       return InsertRangeTest(Val, AddOne(LHSCst),
4253                              RHSCst, true, true, I);
4254     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
4255       break;
4256     }
4257     break;
4258   }
4259  
4260   return 0;
4261 }
4262
4263 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4264                                           FCmpInst *RHS) {
4265   
4266   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4267       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4268     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4269     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4270       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4271         // If either of the constants are nans, then the whole thing returns
4272         // false.
4273         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4274           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4275         return new FCmpInst(FCmpInst::FCMP_ORD,
4276                             LHS->getOperand(0), RHS->getOperand(0));
4277       }
4278     
4279     // Handle vector zeros.  This occurs because the canonical form of
4280     // "fcmp ord x,x" is "fcmp ord x, 0".
4281     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4282         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4283       return new FCmpInst(FCmpInst::FCMP_ORD,
4284                           LHS->getOperand(0), RHS->getOperand(0));
4285     return 0;
4286   }
4287   
4288   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4289   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4290   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4291   
4292   
4293   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4294     // Swap RHS operands to match LHS.
4295     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4296     std::swap(Op1LHS, Op1RHS);
4297   }
4298   
4299   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4300     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4301     if (Op0CC == Op1CC)
4302       return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4303     
4304     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
4305       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4306     if (Op0CC == FCmpInst::FCMP_TRUE)
4307       return ReplaceInstUsesWith(I, RHS);
4308     if (Op1CC == FCmpInst::FCMP_TRUE)
4309       return ReplaceInstUsesWith(I, LHS);
4310     
4311     bool Op0Ordered;
4312     bool Op1Ordered;
4313     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4314     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4315     if (Op1Pred == 0) {
4316       std::swap(LHS, RHS);
4317       std::swap(Op0Pred, Op1Pred);
4318       std::swap(Op0Ordered, Op1Ordered);
4319     }
4320     if (Op0Pred == 0) {
4321       // uno && ueq -> uno && (uno || eq) -> ueq
4322       // ord && olt -> ord && (ord && lt) -> olt
4323       if (Op0Ordered == Op1Ordered)
4324         return ReplaceInstUsesWith(I, RHS);
4325       
4326       // uno && oeq -> uno && (ord && eq) -> false
4327       // uno && ord -> false
4328       if (!Op0Ordered)
4329         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4330       // ord && ueq -> ord && (uno || eq) -> oeq
4331       return cast<Instruction>(getFCmpValue(true, Op1Pred,
4332                                             Op0LHS, Op0RHS, Context));
4333     }
4334   }
4335
4336   return 0;
4337 }
4338
4339
4340 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4341   bool Changed = SimplifyCommutative(I);
4342   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4343
4344   if (Value *V = SimplifyAndInst(Op0, Op1, TD))
4345     return ReplaceInstUsesWith(I, V);
4346
4347   // See if we can simplify any instructions used by the instruction whose sole 
4348   // purpose is to compute bits we don't care about.
4349   if (SimplifyDemandedInstructionBits(I))
4350     return &I;
4351   
4352
4353   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4354     const APInt &AndRHSMask = AndRHS->getValue();
4355     APInt NotAndRHS(~AndRHSMask);
4356
4357     // Optimize a variety of ((val OP C1) & C2) combinations...
4358     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4359       Value *Op0LHS = Op0I->getOperand(0);
4360       Value *Op0RHS = Op0I->getOperand(1);
4361       switch (Op0I->getOpcode()) {
4362       default: break;
4363       case Instruction::Xor:
4364       case Instruction::Or:
4365         // If the mask is only needed on one incoming arm, push it up.
4366         if (!Op0I->hasOneUse()) break;
4367           
4368         if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4369           // Not masking anything out for the LHS, move to RHS.
4370           Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4371                                              Op0RHS->getName()+".masked");
4372           return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4373         }
4374         if (!isa<Constant>(Op0RHS) &&
4375             MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4376           // Not masking anything out for the RHS, move to LHS.
4377           Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4378                                              Op0LHS->getName()+".masked");
4379           return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
4380         }
4381
4382         break;
4383       case Instruction::Add:
4384         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4385         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4386         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4387         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4388           return BinaryOperator::CreateAnd(V, AndRHS);
4389         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4390           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4391         break;
4392
4393       case Instruction::Sub:
4394         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4395         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4396         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4397         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4398           return BinaryOperator::CreateAnd(V, AndRHS);
4399
4400         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4401         // has 1's for all bits that the subtraction with A might affect.
4402         if (Op0I->hasOneUse()) {
4403           uint32_t BitWidth = AndRHSMask.getBitWidth();
4404           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4405           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4406
4407           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4408           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4409               MaskedValueIsZero(Op0LHS, Mask)) {
4410             Value *NewNeg = Builder->CreateNeg(Op0RHS);
4411             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4412           }
4413         }
4414         break;
4415
4416       case Instruction::Shl:
4417       case Instruction::LShr:
4418         // (1 << x) & 1 --> zext(x == 0)
4419         // (1 >> x) & 1 --> zext(x == 0)
4420         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4421           Value *NewICmp =
4422             Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
4423           return new ZExtInst(NewICmp, I.getType());
4424         }
4425         break;
4426       }
4427
4428       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4429         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4430           return Res;
4431     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4432       // If this is an integer truncation or change from signed-to-unsigned, and
4433       // if the source is an and/or with immediate, transform it.  This
4434       // frequently occurs for bitfield accesses.
4435       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4436         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4437             CastOp->getNumOperands() == 2)
4438           if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
4439             if (CastOp->getOpcode() == Instruction::And) {
4440               // Change: and (cast (and X, C1) to T), C2
4441               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4442               // This will fold the two constants together, which may allow 
4443               // other simplifications.
4444               Value *NewCast = Builder->CreateTruncOrBitCast(
4445                 CastOp->getOperand(0), I.getType(), 
4446                 CastOp->getName()+".shrunk");
4447               // trunc_or_bitcast(C1)&C2
4448               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4449               C3 = ConstantExpr::getAnd(C3, AndRHS);
4450               return BinaryOperator::CreateAnd(NewCast, C3);
4451             } else if (CastOp->getOpcode() == Instruction::Or) {
4452               // Change: and (cast (or X, C1) to T), C2
4453               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4454               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4455               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4456                 // trunc(C1)&C2
4457                 return ReplaceInstUsesWith(I, AndRHS);
4458             }
4459           }
4460       }
4461     }
4462
4463     // Try to fold constant and into select arguments.
4464     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4465       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4466         return R;
4467     if (isa<PHINode>(Op0))
4468       if (Instruction *NV = FoldOpIntoPhi(I))
4469         return NV;
4470   }
4471
4472
4473   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4474   if (Value *Op0NotVal = dyn_castNotVal(Op0))
4475     if (Value *Op1NotVal = dyn_castNotVal(Op1))
4476       if (Op0->hasOneUse() && Op1->hasOneUse()) {
4477         Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4478                                       I.getName()+".demorgan");
4479         return BinaryOperator::CreateNot(Or);
4480       }
4481
4482   {
4483     Value *A = 0, *B = 0, *C = 0, *D = 0;
4484     // (A|B) & ~(A&B) -> A^B
4485     if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
4486         match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4487         ((A == C && B == D) || (A == D && B == C)))
4488       return BinaryOperator::CreateXor(A, B);
4489     
4490     // ~(A&B) & (A|B) -> A^B
4491     if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
4492         match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4493         ((A == C && B == D) || (A == D && B == C)))
4494       return BinaryOperator::CreateXor(A, B);
4495     
4496     if (Op0->hasOneUse() &&
4497         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4498       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4499         I.swapOperands();     // Simplify below
4500         std::swap(Op0, Op1);
4501       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4502         cast<BinaryOperator>(Op0)->swapOperands();
4503         I.swapOperands();     // Simplify below
4504         std::swap(Op0, Op1);
4505       }
4506     }
4507
4508     if (Op1->hasOneUse() &&
4509         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4510       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4511         cast<BinaryOperator>(Op1)->swapOperands();
4512         std::swap(A, B);
4513       }
4514       if (A == Op0)                                // A&(A^B) -> A & ~B
4515         return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
4516     }
4517
4518     // (A&((~A)|B)) -> A&B
4519     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4520         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4521       return BinaryOperator::CreateAnd(A, Op1);
4522     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4523         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4524       return BinaryOperator::CreateAnd(A, Op0);
4525   }
4526   
4527   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4528     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4529     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4530       return R;
4531
4532     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4533       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4534         return Res;
4535   }
4536
4537   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4538   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4539     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4540       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4541         const Type *SrcTy = Op0C->getOperand(0)->getType();
4542         if (SrcTy == Op1C->getOperand(0)->getType() &&
4543             SrcTy->isIntOrIntVector() &&
4544             // Only do this if the casts both really cause code to be generated.
4545             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4546                               I.getType(), TD) &&
4547             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4548                               I.getType(), TD)) {
4549           Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4550                                             Op1C->getOperand(0), I.getName());
4551           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4552         }
4553       }
4554     
4555   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4556   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4557     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4558       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4559           SI0->getOperand(1) == SI1->getOperand(1) &&
4560           (SI0->hasOneUse() || SI1->hasOneUse())) {
4561         Value *NewOp =
4562           Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4563                              SI0->getName());
4564         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4565                                       SI1->getOperand(1));
4566       }
4567   }
4568
4569   // If and'ing two fcmp, try combine them into one.
4570   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4571     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4572       if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4573         return Res;
4574   }
4575
4576   return Changed ? &I : 0;
4577 }
4578
4579 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4580 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4581 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4582 /// the expression came from the corresponding "byte swapped" byte in some other
4583 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4584 /// we know that the expression deposits the low byte of %X into the high byte
4585 /// of the bswap result and that all other bytes are zero.  This expression is
4586 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4587 /// match.
4588 ///
4589 /// This function returns true if the match was unsuccessful and false if so.
4590 /// On entry to the function the "OverallLeftShift" is a signed integer value
4591 /// indicating the number of bytes that the subexpression is later shifted.  For
4592 /// example, if the expression is later right shifted by 16 bits, the
4593 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4594 /// byte of ByteValues is actually being set.
4595 ///
4596 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4597 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4598 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4599 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4600 /// always in the local (OverallLeftShift) coordinate space.
4601 ///
4602 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4603                               SmallVector<Value*, 8> &ByteValues) {
4604   if (Instruction *I = dyn_cast<Instruction>(V)) {
4605     // If this is an or instruction, it may be an inner node of the bswap.
4606     if (I->getOpcode() == Instruction::Or) {
4607       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4608                                ByteValues) ||
4609              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4610                                ByteValues);
4611     }
4612   
4613     // If this is a logical shift by a constant multiple of 8, recurse with
4614     // OverallLeftShift and ByteMask adjusted.
4615     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4616       unsigned ShAmt = 
4617         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4618       // Ensure the shift amount is defined and of a byte value.
4619       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4620         return true;
4621
4622       unsigned ByteShift = ShAmt >> 3;
4623       if (I->getOpcode() == Instruction::Shl) {
4624         // X << 2 -> collect(X, +2)
4625         OverallLeftShift += ByteShift;
4626         ByteMask >>= ByteShift;
4627       } else {
4628         // X >>u 2 -> collect(X, -2)
4629         OverallLeftShift -= ByteShift;
4630         ByteMask <<= ByteShift;
4631         ByteMask &= (~0U >> (32-ByteValues.size()));
4632       }
4633
4634       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4635       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4636
4637       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4638                                ByteValues);
4639     }
4640
4641     // If this is a logical 'and' with a mask that clears bytes, clear the
4642     // corresponding bytes in ByteMask.
4643     if (I->getOpcode() == Instruction::And &&
4644         isa<ConstantInt>(I->getOperand(1))) {
4645       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4646       unsigned NumBytes = ByteValues.size();
4647       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4648       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4649       
4650       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4651         // If this byte is masked out by a later operation, we don't care what
4652         // the and mask is.
4653         if ((ByteMask & (1 << i)) == 0)
4654           continue;
4655         
4656         // If the AndMask is all zeros for this byte, clear the bit.
4657         APInt MaskB = AndMask & Byte;
4658         if (MaskB == 0) {
4659           ByteMask &= ~(1U << i);
4660           continue;
4661         }
4662         
4663         // If the AndMask is not all ones for this byte, it's not a bytezap.
4664         if (MaskB != Byte)
4665           return true;
4666
4667         // Otherwise, this byte is kept.
4668       }
4669
4670       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4671                                ByteValues);
4672     }
4673   }
4674   
4675   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4676   // the input value to the bswap.  Some observations: 1) if more than one byte
4677   // is demanded from this input, then it could not be successfully assembled
4678   // into a byteswap.  At least one of the two bytes would not be aligned with
4679   // their ultimate destination.
4680   if (!isPowerOf2_32(ByteMask)) return true;
4681   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4682   
4683   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4684   // is demanded, it needs to go into byte 0 of the result.  This means that the
4685   // byte needs to be shifted until it lands in the right byte bucket.  The
4686   // shift amount depends on the position: if the byte is coming from the high
4687   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4688   // low part, it must be shifted left.
4689   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4690   if (InputByteNo < ByteValues.size()/2) {
4691     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4692       return true;
4693   } else {
4694     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4695       return true;
4696   }
4697   
4698   // If the destination byte value is already defined, the values are or'd
4699   // together, which isn't a bswap (unless it's an or of the same bits).
4700   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4701     return true;
4702   ByteValues[DestByteNo] = V;
4703   return false;
4704 }
4705
4706 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4707 /// If so, insert the new bswap intrinsic and return it.
4708 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4709   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4710   if (!ITy || ITy->getBitWidth() % 16 || 
4711       // ByteMask only allows up to 32-byte values.
4712       ITy->getBitWidth() > 32*8) 
4713     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4714   
4715   /// ByteValues - For each byte of the result, we keep track of which value
4716   /// defines each byte.
4717   SmallVector<Value*, 8> ByteValues;
4718   ByteValues.resize(ITy->getBitWidth()/8);
4719     
4720   // Try to find all the pieces corresponding to the bswap.
4721   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4722   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4723     return 0;
4724   
4725   // Check to see if all of the bytes come from the same value.
4726   Value *V = ByteValues[0];
4727   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4728   
4729   // Check to make sure that all of the bytes come from the same value.
4730   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4731     if (ByteValues[i] != V)
4732       return 0;
4733   const Type *Tys[] = { ITy };
4734   Module *M = I.getParent()->getParent()->getParent();
4735   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4736   return CallInst::Create(F, V);
4737 }
4738
4739 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4740 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4741 /// we can simplify this expression to "cond ? C : D or B".
4742 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4743                                          Value *C, Value *D,
4744                                          LLVMContext *Context) {
4745   // If A is not a select of -1/0, this cannot match.
4746   Value *Cond = 0;
4747   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4748     return 0;
4749
4750   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4751   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4752     return SelectInst::Create(Cond, C, B);
4753   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4754     return SelectInst::Create(Cond, C, B);
4755   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4756   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4757     return SelectInst::Create(Cond, C, D);
4758   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4759     return SelectInst::Create(Cond, C, D);
4760   return 0;
4761 }
4762
4763 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4764 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4765                                          ICmpInst *LHS, ICmpInst *RHS) {
4766   // (icmp ne A, null) | (icmp ne B, null) -->
4767   //     (icmp ne (ptrtoint(A)|ptrtoint(B)), 0)
4768   if (TD &&
4769       LHS->getPredicate() == ICmpInst::ICMP_NE &&
4770       RHS->getPredicate() == ICmpInst::ICMP_NE &&
4771       isa<ConstantPointerNull>(LHS->getOperand(1)) &&
4772       isa<ConstantPointerNull>(RHS->getOperand(1))) {
4773     const Type *IntPtrTy = TD->getIntPtrType(I.getContext());
4774     Value *A = Builder->CreatePtrToInt(LHS->getOperand(0), IntPtrTy);
4775     Value *B = Builder->CreatePtrToInt(RHS->getOperand(0), IntPtrTy);
4776     Value *NewOr = Builder->CreateOr(A, B);
4777     return new ICmpInst(ICmpInst::ICMP_NE, NewOr,
4778                         Constant::getNullValue(IntPtrTy));
4779   }
4780   
4781   Value *Val, *Val2;
4782   ConstantInt *LHSCst, *RHSCst;
4783   ICmpInst::Predicate LHSCC, RHSCC;
4784   
4785   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4786   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4787       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4788     return 0;
4789
4790   
4791   // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
4792   if (LHSCst == RHSCst && LHSCC == RHSCC &&
4793       LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
4794     Value *NewOr = Builder->CreateOr(Val, Val2);
4795     return new ICmpInst(LHSCC, NewOr, LHSCst);
4796   }
4797   
4798   // From here on, we only handle:
4799   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4800   if (Val != Val2) return 0;
4801   
4802   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4803   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4804       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4805       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4806       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4807     return 0;
4808   
4809   // We can't fold (ugt x, C) | (sgt x, C2).
4810   if (!PredicatesFoldable(LHSCC, RHSCC))
4811     return 0;
4812   
4813   // Ensure that the larger constant is on the RHS.
4814   bool ShouldSwap;
4815   if (CmpInst::isSigned(LHSCC) ||
4816       (ICmpInst::isEquality(LHSCC) && 
4817        CmpInst::isSigned(RHSCC)))
4818     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4819   else
4820     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4821   
4822   if (ShouldSwap) {
4823     std::swap(LHS, RHS);
4824     std::swap(LHSCst, RHSCst);
4825     std::swap(LHSCC, RHSCC);
4826   }
4827   
4828   // At this point, we know we have have two icmp instructions
4829   // comparing a value against two constants and or'ing the result
4830   // together.  Because of the above check, we know that we only have
4831   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4832   // FoldICmpLogical check above), that the two constants are not
4833   // equal.
4834   assert(LHSCst != RHSCst && "Compares not folded above?");
4835
4836   switch (LHSCC) {
4837   default: llvm_unreachable("Unknown integer condition code!");
4838   case ICmpInst::ICMP_EQ:
4839     switch (RHSCC) {
4840     default: llvm_unreachable("Unknown integer condition code!");
4841     case ICmpInst::ICMP_EQ:
4842       if (LHSCst == SubOne(RHSCst)) {
4843         // (X == 13 | X == 14) -> X-13 <u 2
4844         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4845         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4846         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4847         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4848       }
4849       break;                         // (X == 13 | X == 15) -> no change
4850     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4851     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4852       break;
4853     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4854     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4855     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4856       return ReplaceInstUsesWith(I, RHS);
4857     }
4858     break;
4859   case ICmpInst::ICMP_NE:
4860     switch (RHSCC) {
4861     default: llvm_unreachable("Unknown integer condition code!");
4862     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4863     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4864     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4865       return ReplaceInstUsesWith(I, LHS);
4866     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4867     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4868     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4869       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4870     }
4871     break;
4872   case ICmpInst::ICMP_ULT:
4873     switch (RHSCC) {
4874     default: llvm_unreachable("Unknown integer condition code!");
4875     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4876       break;
4877     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4878       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4879       // this can cause overflow.
4880       if (RHSCst->isMaxValue(false))
4881         return ReplaceInstUsesWith(I, LHS);
4882       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4883                              false, false, I);
4884     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4885       break;
4886     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4887     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4888       return ReplaceInstUsesWith(I, RHS);
4889     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4890       break;
4891     }
4892     break;
4893   case ICmpInst::ICMP_SLT:
4894     switch (RHSCC) {
4895     default: llvm_unreachable("Unknown integer condition code!");
4896     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4897       break;
4898     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4899       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4900       // this can cause overflow.
4901       if (RHSCst->isMaxValue(true))
4902         return ReplaceInstUsesWith(I, LHS);
4903       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4904                              true, false, I);
4905     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4906       break;
4907     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4908     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4909       return ReplaceInstUsesWith(I, RHS);
4910     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4911       break;
4912     }
4913     break;
4914   case ICmpInst::ICMP_UGT:
4915     switch (RHSCC) {
4916     default: llvm_unreachable("Unknown integer condition code!");
4917     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4918     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4919       return ReplaceInstUsesWith(I, LHS);
4920     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4921       break;
4922     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4923     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4924       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4925     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4926       break;
4927     }
4928     break;
4929   case ICmpInst::ICMP_SGT:
4930     switch (RHSCC) {
4931     default: llvm_unreachable("Unknown integer condition code!");
4932     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4933     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4934       return ReplaceInstUsesWith(I, LHS);
4935     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4936       break;
4937     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4938     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4939       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4940     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4941       break;
4942     }
4943     break;
4944   }
4945   return 0;
4946 }
4947
4948 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4949                                          FCmpInst *RHS) {
4950   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4951       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4952       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4953     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4954       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4955         // If either of the constants are nans, then the whole thing returns
4956         // true.
4957         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4958           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4959         
4960         // Otherwise, no need to compare the two constants, compare the
4961         // rest.
4962         return new FCmpInst(FCmpInst::FCMP_UNO,
4963                             LHS->getOperand(0), RHS->getOperand(0));
4964       }
4965     
4966     // Handle vector zeros.  This occurs because the canonical form of
4967     // "fcmp uno x,x" is "fcmp uno x, 0".
4968     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4969         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4970       return new FCmpInst(FCmpInst::FCMP_UNO,
4971                           LHS->getOperand(0), RHS->getOperand(0));
4972     
4973     return 0;
4974   }
4975   
4976   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4977   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4978   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4979   
4980   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4981     // Swap RHS operands to match LHS.
4982     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4983     std::swap(Op1LHS, Op1RHS);
4984   }
4985   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4986     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4987     if (Op0CC == Op1CC)
4988       return new FCmpInst((FCmpInst::Predicate)Op0CC,
4989                           Op0LHS, Op0RHS);
4990     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4991       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4992     if (Op0CC == FCmpInst::FCMP_FALSE)
4993       return ReplaceInstUsesWith(I, RHS);
4994     if (Op1CC == FCmpInst::FCMP_FALSE)
4995       return ReplaceInstUsesWith(I, LHS);
4996     bool Op0Ordered;
4997     bool Op1Ordered;
4998     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4999     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
5000     if (Op0Ordered == Op1Ordered) {
5001       // If both are ordered or unordered, return a new fcmp with
5002       // or'ed predicates.
5003       Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
5004                                Op0LHS, Op0RHS, Context);
5005       if (Instruction *I = dyn_cast<Instruction>(RV))
5006         return I;
5007       // Otherwise, it's a constant boolean value...
5008       return ReplaceInstUsesWith(I, RV);
5009     }
5010   }
5011   return 0;
5012 }
5013
5014 /// FoldOrWithConstants - This helper function folds:
5015 ///
5016 ///     ((A | B) & C1) | (B & C2)
5017 ///
5018 /// into:
5019 /// 
5020 ///     (A & C1) | B
5021 ///
5022 /// when the XOR of the two constants is "all ones" (-1).
5023 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
5024                                                Value *A, Value *B, Value *C) {
5025   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
5026   if (!CI1) return 0;
5027
5028   Value *V1 = 0;
5029   ConstantInt *CI2 = 0;
5030   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
5031
5032   APInt Xor = CI1->getValue() ^ CI2->getValue();
5033   if (!Xor.isAllOnesValue()) return 0;
5034
5035   if (V1 == A || V1 == B) {
5036     Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
5037     return BinaryOperator::CreateOr(NewOp, V1);
5038   }
5039
5040   return 0;
5041 }
5042
5043 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
5044   bool Changed = SimplifyCommutative(I);
5045   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5046
5047   if (Value *V = SimplifyOrInst(Op0, Op1, TD))
5048     return ReplaceInstUsesWith(I, V);
5049   
5050   
5051   // See if we can simplify any instructions used by the instruction whose sole 
5052   // purpose is to compute bits we don't care about.
5053   if (SimplifyDemandedInstructionBits(I))
5054     return &I;
5055
5056   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5057     ConstantInt *C1 = 0; Value *X = 0;
5058     // (X & C1) | C2 --> (X | C2) & (C1|C2)
5059     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
5060         isOnlyUse(Op0)) {
5061       Value *Or = Builder->CreateOr(X, RHS);
5062       Or->takeName(Op0);
5063       return BinaryOperator::CreateAnd(Or, 
5064                ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
5065     }
5066
5067     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
5068     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
5069         isOnlyUse(Op0)) {
5070       Value *Or = Builder->CreateOr(X, RHS);
5071       Or->takeName(Op0);
5072       return BinaryOperator::CreateXor(Or,
5073                  ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
5074     }
5075
5076     // Try to fold constant and into select arguments.
5077     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5078       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5079         return R;
5080     if (isa<PHINode>(Op0))
5081       if (Instruction *NV = FoldOpIntoPhi(I))
5082         return NV;
5083   }
5084
5085   Value *A = 0, *B = 0;
5086   ConstantInt *C1 = 0, *C2 = 0;
5087
5088   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
5089   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
5090   if (match(Op0, m_Or(m_Value(), m_Value())) ||
5091       match(Op1, m_Or(m_Value(), m_Value())) ||
5092       (match(Op0, m_Shift(m_Value(), m_Value())) &&
5093        match(Op1, m_Shift(m_Value(), m_Value())))) {
5094     if (Instruction *BSwap = MatchBSwap(I))
5095       return BSwap;
5096   }
5097   
5098   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
5099   if (Op0->hasOneUse() &&
5100       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
5101       MaskedValueIsZero(Op1, C1->getValue())) {
5102     Value *NOr = Builder->CreateOr(A, Op1);
5103     NOr->takeName(Op0);
5104     return BinaryOperator::CreateXor(NOr, C1);
5105   }
5106
5107   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
5108   if (Op1->hasOneUse() &&
5109       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
5110       MaskedValueIsZero(Op0, C1->getValue())) {
5111     Value *NOr = Builder->CreateOr(A, Op0);
5112     NOr->takeName(Op0);
5113     return BinaryOperator::CreateXor(NOr, C1);
5114   }
5115
5116   // (A & C)|(B & D)
5117   Value *C = 0, *D = 0;
5118   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
5119       match(Op1, m_And(m_Value(B), m_Value(D)))) {
5120     Value *V1 = 0, *V2 = 0, *V3 = 0;
5121     C1 = dyn_cast<ConstantInt>(C);
5122     C2 = dyn_cast<ConstantInt>(D);
5123     if (C1 && C2) {  // (A & C1)|(B & C2)
5124       // If we have: ((V + N) & C1) | (V & C2)
5125       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
5126       // replace with V+N.
5127       if (C1->getValue() == ~C2->getValue()) {
5128         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
5129             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
5130           // Add commutes, try both ways.
5131           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
5132             return ReplaceInstUsesWith(I, A);
5133           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
5134             return ReplaceInstUsesWith(I, A);
5135         }
5136         // Or commutes, try both ways.
5137         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
5138             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
5139           // Add commutes, try both ways.
5140           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
5141             return ReplaceInstUsesWith(I, B);
5142           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
5143             return ReplaceInstUsesWith(I, B);
5144         }
5145       }
5146       V1 = 0; V2 = 0; V3 = 0;
5147     }
5148     
5149     // Check to see if we have any common things being and'ed.  If so, find the
5150     // terms for V1 & (V2|V3).
5151     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
5152       if (A == B)      // (A & C)|(A & D) == A & (C|D)
5153         V1 = A, V2 = C, V3 = D;
5154       else if (A == D) // (A & C)|(B & A) == A & (B|C)
5155         V1 = A, V2 = B, V3 = C;
5156       else if (C == B) // (A & C)|(C & D) == C & (A|D)
5157         V1 = C, V2 = A, V3 = D;
5158       else if (C == D) // (A & C)|(B & C) == C & (A|B)
5159         V1 = C, V2 = A, V3 = B;
5160       
5161       if (V1) {
5162         Value *Or = Builder->CreateOr(V2, V3, "tmp");
5163         return BinaryOperator::CreateAnd(V1, Or);
5164       }
5165     }
5166
5167     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
5168     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
5169       return Match;
5170     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
5171       return Match;
5172     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
5173       return Match;
5174     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
5175       return Match;
5176
5177     // ((A&~B)|(~A&B)) -> A^B
5178     if ((match(C, m_Not(m_Specific(D))) &&
5179          match(B, m_Not(m_Specific(A)))))
5180       return BinaryOperator::CreateXor(A, D);
5181     // ((~B&A)|(~A&B)) -> A^B
5182     if ((match(A, m_Not(m_Specific(D))) &&
5183          match(B, m_Not(m_Specific(C)))))
5184       return BinaryOperator::CreateXor(C, D);
5185     // ((A&~B)|(B&~A)) -> A^B
5186     if ((match(C, m_Not(m_Specific(B))) &&
5187          match(D, m_Not(m_Specific(A)))))
5188       return BinaryOperator::CreateXor(A, B);
5189     // ((~B&A)|(B&~A)) -> A^B
5190     if ((match(A, m_Not(m_Specific(B))) &&
5191          match(D, m_Not(m_Specific(C)))))
5192       return BinaryOperator::CreateXor(C, B);
5193   }
5194   
5195   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
5196   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
5197     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
5198       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
5199           SI0->getOperand(1) == SI1->getOperand(1) &&
5200           (SI0->hasOneUse() || SI1->hasOneUse())) {
5201         Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
5202                                          SI0->getName());
5203         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
5204                                       SI1->getOperand(1));
5205       }
5206   }
5207
5208   // ((A|B)&1)|(B&-2) -> (A&1) | B
5209   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5210       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
5211     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
5212     if (Ret) return Ret;
5213   }
5214   // (B&-2)|((A|B)&1) -> (A&1) | B
5215   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5216       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
5217     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
5218     if (Ret) return Ret;
5219   }
5220
5221   // (~A | ~B) == (~(A & B)) - De Morgan's Law
5222   if (Value *Op0NotVal = dyn_castNotVal(Op0))
5223     if (Value *Op1NotVal = dyn_castNotVal(Op1))
5224       if (Op0->hasOneUse() && Op1->hasOneUse()) {
5225         Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
5226                                         I.getName()+".demorgan");
5227         return BinaryOperator::CreateNot(And);
5228       }
5229
5230   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5231   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
5232     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5233       return R;
5234
5235     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5236       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5237         return Res;
5238   }
5239     
5240   // fold (or (cast A), (cast B)) -> (cast (or A, B))
5241   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5242     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5243       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
5244         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5245             !isa<ICmpInst>(Op1C->getOperand(0))) {
5246           const Type *SrcTy = Op0C->getOperand(0)->getType();
5247           if (SrcTy == Op1C->getOperand(0)->getType() &&
5248               SrcTy->isIntOrIntVector() &&
5249               // Only do this if the casts both really cause code to be
5250               // generated.
5251               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5252                                 I.getType(), TD) &&
5253               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5254                                 I.getType(), TD)) {
5255             Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5256                                              Op1C->getOperand(0), I.getName());
5257             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5258           }
5259         }
5260       }
5261   }
5262   
5263     
5264   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
5265   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
5266     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5267       if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5268         return Res;
5269   }
5270
5271   return Changed ? &I : 0;
5272 }
5273
5274 namespace {
5275
5276 // XorSelf - Implements: X ^ X --> 0
5277 struct XorSelf {
5278   Value *RHS;
5279   XorSelf(Value *rhs) : RHS(rhs) {}
5280   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5281   Instruction *apply(BinaryOperator &Xor) const {
5282     return &Xor;
5283   }
5284 };
5285
5286 }
5287
5288 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5289   bool Changed = SimplifyCommutative(I);
5290   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5291
5292   if (isa<UndefValue>(Op1)) {
5293     if (isa<UndefValue>(Op0))
5294       // Handle undef ^ undef -> 0 special case. This is a common
5295       // idiom (misuse).
5296       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5297     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5298   }
5299
5300   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5301   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
5302     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5303     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5304   }
5305   
5306   // See if we can simplify any instructions used by the instruction whose sole 
5307   // purpose is to compute bits we don't care about.
5308   if (SimplifyDemandedInstructionBits(I))
5309     return &I;
5310   if (isa<VectorType>(I.getType()))
5311     if (isa<ConstantAggregateZero>(Op1))
5312       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5313
5314   // Is this a ~ operation?
5315   if (Value *NotOp = dyn_castNotVal(&I)) {
5316     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5317       if (Op0I->getOpcode() == Instruction::And || 
5318           Op0I->getOpcode() == Instruction::Or) {
5319         // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5320         // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5321         if (dyn_castNotVal(Op0I->getOperand(1)))
5322           Op0I->swapOperands();
5323         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5324           Value *NotY =
5325             Builder->CreateNot(Op0I->getOperand(1),
5326                                Op0I->getOperand(1)->getName()+".not");
5327           if (Op0I->getOpcode() == Instruction::And)
5328             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5329           return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5330         }
5331         
5332         // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5333         // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5334         if (isFreeToInvert(Op0I->getOperand(0)) && 
5335             isFreeToInvert(Op0I->getOperand(1))) {
5336           Value *NotX =
5337             Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5338           Value *NotY =
5339             Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5340           if (Op0I->getOpcode() == Instruction::And)
5341             return BinaryOperator::CreateOr(NotX, NotY);
5342           return BinaryOperator::CreateAnd(NotX, NotY);
5343         }
5344       }
5345     }
5346   }
5347   
5348   
5349   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5350     if (RHS->isOne() && Op0->hasOneUse()) {
5351       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5352       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5353         return new ICmpInst(ICI->getInversePredicate(),
5354                             ICI->getOperand(0), ICI->getOperand(1));
5355
5356       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5357         return new FCmpInst(FCI->getInversePredicate(),
5358                             FCI->getOperand(0), FCI->getOperand(1));
5359     }
5360
5361     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5362     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5363       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5364         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5365           Instruction::CastOps Opcode = Op0C->getOpcode();
5366           if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5367               (RHS == ConstantExpr::getCast(Opcode, 
5368                                             ConstantInt::getTrue(*Context),
5369                                             Op0C->getDestTy()))) {
5370             CI->setPredicate(CI->getInversePredicate());
5371             return CastInst::Create(Opcode, CI, Op0C->getType());
5372           }
5373         }
5374       }
5375     }
5376
5377     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5378       // ~(c-X) == X-c-1 == X+(-c-1)
5379       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5380         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5381           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5382           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5383                                       ConstantInt::get(I.getType(), 1));
5384           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5385         }
5386           
5387       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5388         if (Op0I->getOpcode() == Instruction::Add) {
5389           // ~(X-c) --> (-c-1)-X
5390           if (RHS->isAllOnesValue()) {
5391             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5392             return BinaryOperator::CreateSub(
5393                            ConstantExpr::getSub(NegOp0CI,
5394                                       ConstantInt::get(I.getType(), 1)),
5395                                       Op0I->getOperand(0));
5396           } else if (RHS->getValue().isSignBit()) {
5397             // (X + C) ^ signbit -> (X + C + signbit)
5398             Constant *C = ConstantInt::get(*Context,
5399                                            RHS->getValue() + Op0CI->getValue());
5400             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5401
5402           }
5403         } else if (Op0I->getOpcode() == Instruction::Or) {
5404           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5405           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5406             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5407             // Anything in both C1 and C2 is known to be zero, remove it from
5408             // NewRHS.
5409             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5410             NewRHS = ConstantExpr::getAnd(NewRHS, 
5411                                        ConstantExpr::getNot(CommonBits));
5412             Worklist.Add(Op0I);
5413             I.setOperand(0, Op0I->getOperand(0));
5414             I.setOperand(1, NewRHS);
5415             return &I;
5416           }
5417         }
5418       }
5419     }
5420
5421     // Try to fold constant and into select arguments.
5422     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5423       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5424         return R;
5425     if (isa<PHINode>(Op0))
5426       if (Instruction *NV = FoldOpIntoPhi(I))
5427         return NV;
5428   }
5429
5430   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5431     if (X == Op1)
5432       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5433
5434   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5435     if (X == Op0)
5436       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5437
5438   
5439   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5440   if (Op1I) {
5441     Value *A, *B;
5442     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5443       if (A == Op0) {              // B^(B|A) == (A|B)^B
5444         Op1I->swapOperands();
5445         I.swapOperands();
5446         std::swap(Op0, Op1);
5447       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5448         I.swapOperands();     // Simplified below.
5449         std::swap(Op0, Op1);
5450       }
5451     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5452       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5453     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5454       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5455     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && 
5456                Op1I->hasOneUse()){
5457       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5458         Op1I->swapOperands();
5459         std::swap(A, B);
5460       }
5461       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5462         I.swapOperands();     // Simplified below.
5463         std::swap(Op0, Op1);
5464       }
5465     }
5466   }
5467   
5468   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5469   if (Op0I) {
5470     Value *A, *B;
5471     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5472         Op0I->hasOneUse()) {
5473       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5474         std::swap(A, B);
5475       if (B == Op1)                                  // (A|B)^B == A & ~B
5476         return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
5477     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5478       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5479     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5480       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5481     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && 
5482                Op0I->hasOneUse()){
5483       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5484         std::swap(A, B);
5485       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5486           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5487         return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
5488       }
5489     }
5490   }
5491   
5492   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5493   if (Op0I && Op1I && Op0I->isShift() && 
5494       Op0I->getOpcode() == Op1I->getOpcode() && 
5495       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5496       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5497     Value *NewOp =
5498       Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5499                          Op0I->getName());
5500     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5501                                   Op1I->getOperand(1));
5502   }
5503     
5504   if (Op0I && Op1I) {
5505     Value *A, *B, *C, *D;
5506     // (A & B)^(A | B) -> A ^ B
5507     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5508         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5509       if ((A == C && B == D) || (A == D && B == C)) 
5510         return BinaryOperator::CreateXor(A, B);
5511     }
5512     // (A | B)^(A & B) -> A ^ B
5513     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5514         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5515       if ((A == C && B == D) || (A == D && B == C)) 
5516         return BinaryOperator::CreateXor(A, B);
5517     }
5518     
5519     // (A & B)^(C & D)
5520     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5521         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5522         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5523       // (X & Y)^(X & Y) -> (Y^Z) & X
5524       Value *X = 0, *Y = 0, *Z = 0;
5525       if (A == C)
5526         X = A, Y = B, Z = D;
5527       else if (A == D)
5528         X = A, Y = B, Z = C;
5529       else if (B == C)
5530         X = B, Y = A, Z = D;
5531       else if (B == D)
5532         X = B, Y = A, Z = C;
5533       
5534       if (X) {
5535         Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
5536         return BinaryOperator::CreateAnd(NewOp, X);
5537       }
5538     }
5539   }
5540     
5541   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5542   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5543     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5544       return R;
5545
5546   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5547   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5548     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5549       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5550         const Type *SrcTy = Op0C->getOperand(0)->getType();
5551         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5552             // Only do this if the casts both really cause code to be generated.
5553             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5554                               I.getType(), TD) &&
5555             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5556                               I.getType(), TD)) {
5557           Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5558                                             Op1C->getOperand(0), I.getName());
5559           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5560         }
5561       }
5562   }
5563
5564   return Changed ? &I : 0;
5565 }
5566
5567 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5568                                    LLVMContext *Context) {
5569   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5570 }
5571
5572 static bool HasAddOverflow(ConstantInt *Result,
5573                            ConstantInt *In1, ConstantInt *In2,
5574                            bool IsSigned) {
5575   if (IsSigned)
5576     if (In2->getValue().isNegative())
5577       return Result->getValue().sgt(In1->getValue());
5578     else
5579       return Result->getValue().slt(In1->getValue());
5580   else
5581     return Result->getValue().ult(In1->getValue());
5582 }
5583
5584 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5585 /// overflowed for this type.
5586 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5587                             Constant *In2, LLVMContext *Context,
5588                             bool IsSigned = false) {
5589   Result = ConstantExpr::getAdd(In1, In2);
5590
5591   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5592     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5593       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5594       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5595                          ExtractElement(In1, Idx, Context),
5596                          ExtractElement(In2, Idx, Context),
5597                          IsSigned))
5598         return true;
5599     }
5600     return false;
5601   }
5602
5603   return HasAddOverflow(cast<ConstantInt>(Result),
5604                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5605                         IsSigned);
5606 }
5607
5608 static bool HasSubOverflow(ConstantInt *Result,
5609                            ConstantInt *In1, ConstantInt *In2,
5610                            bool IsSigned) {
5611   if (IsSigned)
5612     if (In2->getValue().isNegative())
5613       return Result->getValue().slt(In1->getValue());
5614     else
5615       return Result->getValue().sgt(In1->getValue());
5616   else
5617     return Result->getValue().ugt(In1->getValue());
5618 }
5619
5620 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5621 /// overflowed for this type.
5622 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5623                             Constant *In2, LLVMContext *Context,
5624                             bool IsSigned = false) {
5625   Result = ConstantExpr::getSub(In1, In2);
5626
5627   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5628     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5629       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5630       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5631                          ExtractElement(In1, Idx, Context),
5632                          ExtractElement(In2, Idx, Context),
5633                          IsSigned))
5634         return true;
5635     }
5636     return false;
5637   }
5638
5639   return HasSubOverflow(cast<ConstantInt>(Result),
5640                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5641                         IsSigned);
5642 }
5643
5644
5645 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5646 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5647 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5648                                        ICmpInst::Predicate Cond,
5649                                        Instruction &I) {
5650   // Look through bitcasts.
5651   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5652     RHS = BCI->getOperand(0);
5653
5654   Value *PtrBase = GEPLHS->getOperand(0);
5655   if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5656     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5657     // This transformation (ignoring the base and scales) is valid because we
5658     // know pointers can't overflow since the gep is inbounds.  See if we can
5659     // output an optimized form.
5660     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5661     
5662     // If not, synthesize the offset the hard way.
5663     if (Offset == 0)
5664       Offset = EmitGEPOffset(GEPLHS, *this);
5665     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5666                         Constant::getNullValue(Offset->getType()));
5667   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5668     // If the base pointers are different, but the indices are the same, just
5669     // compare the base pointer.
5670     if (PtrBase != GEPRHS->getOperand(0)) {
5671       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5672       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5673                         GEPRHS->getOperand(0)->getType();
5674       if (IndicesTheSame)
5675         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5676           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5677             IndicesTheSame = false;
5678             break;
5679           }
5680
5681       // If all indices are the same, just compare the base pointers.
5682       if (IndicesTheSame)
5683         return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5684                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5685
5686       // Otherwise, the base pointers are different and the indices are
5687       // different, bail out.
5688       return 0;
5689     }
5690
5691     // If one of the GEPs has all zero indices, recurse.
5692     bool AllZeros = true;
5693     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5694       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5695           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5696         AllZeros = false;
5697         break;
5698       }
5699     if (AllZeros)
5700       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5701                           ICmpInst::getSwappedPredicate(Cond), I);
5702
5703     // If the other GEP has all zero indices, recurse.
5704     AllZeros = true;
5705     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5706       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5707           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5708         AllZeros = false;
5709         break;
5710       }
5711     if (AllZeros)
5712       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5713
5714     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5715       // If the GEPs only differ by one index, compare it.
5716       unsigned NumDifferences = 0;  // Keep track of # differences.
5717       unsigned DiffOperand = 0;     // The operand that differs.
5718       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5719         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5720           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5721                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5722             // Irreconcilable differences.
5723             NumDifferences = 2;
5724             break;
5725           } else {
5726             if (NumDifferences++) break;
5727             DiffOperand = i;
5728           }
5729         }
5730
5731       if (NumDifferences == 0)   // SAME GEP?
5732         return ReplaceInstUsesWith(I, // No comparison is needed here.
5733                                    ConstantInt::get(Type::getInt1Ty(*Context),
5734                                              ICmpInst::isTrueWhenEqual(Cond)));
5735
5736       else if (NumDifferences == 1) {
5737         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5738         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5739         // Make sure we do a signed comparison here.
5740         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5741       }
5742     }
5743
5744     // Only lower this if the icmp is the only user of the GEP or if we expect
5745     // the result to fold to a constant!
5746     if (TD &&
5747         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5748         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5749       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5750       Value *L = EmitGEPOffset(GEPLHS, *this);
5751       Value *R = EmitGEPOffset(GEPRHS, *this);
5752       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5753     }
5754   }
5755   return 0;
5756 }
5757
5758 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5759 ///
5760 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5761                                                 Instruction *LHSI,
5762                                                 Constant *RHSC) {
5763   if (!isa<ConstantFP>(RHSC)) return 0;
5764   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5765   
5766   // Get the width of the mantissa.  We don't want to hack on conversions that
5767   // might lose information from the integer, e.g. "i64 -> float"
5768   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5769   if (MantissaWidth == -1) return 0;  // Unknown.
5770   
5771   // Check to see that the input is converted from an integer type that is small
5772   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5773   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5774   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5775   
5776   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5777   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5778   if (LHSUnsigned)
5779     ++InputSize;
5780   
5781   // If the conversion would lose info, don't hack on this.
5782   if ((int)InputSize > MantissaWidth)
5783     return 0;
5784   
5785   // Otherwise, we can potentially simplify the comparison.  We know that it
5786   // will always come through as an integer value and we know the constant is
5787   // not a NAN (it would have been previously simplified).
5788   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5789   
5790   ICmpInst::Predicate Pred;
5791   switch (I.getPredicate()) {
5792   default: llvm_unreachable("Unexpected predicate!");
5793   case FCmpInst::FCMP_UEQ:
5794   case FCmpInst::FCMP_OEQ:
5795     Pred = ICmpInst::ICMP_EQ;
5796     break;
5797   case FCmpInst::FCMP_UGT:
5798   case FCmpInst::FCMP_OGT:
5799     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5800     break;
5801   case FCmpInst::FCMP_UGE:
5802   case FCmpInst::FCMP_OGE:
5803     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5804     break;
5805   case FCmpInst::FCMP_ULT:
5806   case FCmpInst::FCMP_OLT:
5807     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5808     break;
5809   case FCmpInst::FCMP_ULE:
5810   case FCmpInst::FCMP_OLE:
5811     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5812     break;
5813   case FCmpInst::FCMP_UNE:
5814   case FCmpInst::FCMP_ONE:
5815     Pred = ICmpInst::ICMP_NE;
5816     break;
5817   case FCmpInst::FCMP_ORD:
5818     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5819   case FCmpInst::FCMP_UNO:
5820     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5821   }
5822   
5823   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5824   
5825   // Now we know that the APFloat is a normal number, zero or inf.
5826   
5827   // See if the FP constant is too large for the integer.  For example,
5828   // comparing an i8 to 300.0.
5829   unsigned IntWidth = IntTy->getScalarSizeInBits();
5830   
5831   if (!LHSUnsigned) {
5832     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5833     // and large values.
5834     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5835     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5836                           APFloat::rmNearestTiesToEven);
5837     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5838       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5839           Pred == ICmpInst::ICMP_SLE)
5840         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5841       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5842     }
5843   } else {
5844     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5845     // +INF and large values.
5846     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5847     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5848                           APFloat::rmNearestTiesToEven);
5849     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5850       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5851           Pred == ICmpInst::ICMP_ULE)
5852         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5853       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5854     }
5855   }
5856   
5857   if (!LHSUnsigned) {
5858     // See if the RHS value is < SignedMin.
5859     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5860     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5861                           APFloat::rmNearestTiesToEven);
5862     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5863       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5864           Pred == ICmpInst::ICMP_SGE)
5865         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5866       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5867     }
5868   }
5869
5870   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5871   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5872   // casting the FP value to the integer value and back, checking for equality.
5873   // Don't do this for zero, because -0.0 is not fractional.
5874   Constant *RHSInt = LHSUnsigned
5875     ? ConstantExpr::getFPToUI(RHSC, IntTy)
5876     : ConstantExpr::getFPToSI(RHSC, IntTy);
5877   if (!RHS.isZero()) {
5878     bool Equal = LHSUnsigned
5879       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5880       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5881     if (!Equal) {
5882       // If we had a comparison against a fractional value, we have to adjust
5883       // the compare predicate and sometimes the value.  RHSC is rounded towards
5884       // zero at this point.
5885       switch (Pred) {
5886       default: llvm_unreachable("Unexpected integer comparison!");
5887       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5888         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5889       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5890         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5891       case ICmpInst::ICMP_ULE:
5892         // (float)int <= 4.4   --> int <= 4
5893         // (float)int <= -4.4  --> false
5894         if (RHS.isNegative())
5895           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5896         break;
5897       case ICmpInst::ICMP_SLE:
5898         // (float)int <= 4.4   --> int <= 4
5899         // (float)int <= -4.4  --> int < -4
5900         if (RHS.isNegative())
5901           Pred = ICmpInst::ICMP_SLT;
5902         break;
5903       case ICmpInst::ICMP_ULT:
5904         // (float)int < -4.4   --> false
5905         // (float)int < 4.4    --> int <= 4
5906         if (RHS.isNegative())
5907           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5908         Pred = ICmpInst::ICMP_ULE;
5909         break;
5910       case ICmpInst::ICMP_SLT:
5911         // (float)int < -4.4   --> int < -4
5912         // (float)int < 4.4    --> int <= 4
5913         if (!RHS.isNegative())
5914           Pred = ICmpInst::ICMP_SLE;
5915         break;
5916       case ICmpInst::ICMP_UGT:
5917         // (float)int > 4.4    --> int > 4
5918         // (float)int > -4.4   --> true
5919         if (RHS.isNegative())
5920           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5921         break;
5922       case ICmpInst::ICMP_SGT:
5923         // (float)int > 4.4    --> int > 4
5924         // (float)int > -4.4   --> int >= -4
5925         if (RHS.isNegative())
5926           Pred = ICmpInst::ICMP_SGE;
5927         break;
5928       case ICmpInst::ICMP_UGE:
5929         // (float)int >= -4.4   --> true
5930         // (float)int >= 4.4    --> int > 4
5931         if (!RHS.isNegative())
5932           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5933         Pred = ICmpInst::ICMP_UGT;
5934         break;
5935       case ICmpInst::ICMP_SGE:
5936         // (float)int >= -4.4   --> int >= -4
5937         // (float)int >= 4.4    --> int > 4
5938         if (!RHS.isNegative())
5939           Pred = ICmpInst::ICMP_SGT;
5940         break;
5941       }
5942     }
5943   }
5944
5945   // Lower this FP comparison into an appropriate integer version of the
5946   // comparison.
5947   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5948 }
5949
5950 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5951   bool Changed = false;
5952   
5953   /// Orders the operands of the compare so that they are listed from most
5954   /// complex to least complex.  This puts constants before unary operators,
5955   /// before binary operators.
5956   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
5957     I.swapOperands();
5958     Changed = true;
5959   }
5960
5961   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5962   
5963   if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
5964     return ReplaceInstUsesWith(I, V);
5965
5966   // Simplify 'fcmp pred X, X'
5967   if (Op0 == Op1) {
5968     switch (I.getPredicate()) {
5969     default: llvm_unreachable("Unknown predicate!");
5970     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5971     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5972     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5973     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5974       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5975       I.setPredicate(FCmpInst::FCMP_UNO);
5976       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5977       return &I;
5978       
5979     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5980     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5981     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5982     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5983       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5984       I.setPredicate(FCmpInst::FCMP_ORD);
5985       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5986       return &I;
5987     }
5988   }
5989     
5990   // Handle fcmp with constant RHS
5991   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5992     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5993       switch (LHSI->getOpcode()) {
5994       case Instruction::PHI:
5995         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5996         // block.  If in the same block, we're encouraging jump threading.  If
5997         // not, we are just pessimizing the code by making an i1 phi.
5998         if (LHSI->getParent() == I.getParent())
5999           if (Instruction *NV = FoldOpIntoPhi(I, true))
6000             return NV;
6001         break;
6002       case Instruction::SIToFP:
6003       case Instruction::UIToFP:
6004         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
6005           return NV;
6006         break;
6007       case Instruction::Select:
6008         // If either operand of the select is a constant, we can fold the
6009         // comparison into the select arms, which will cause one to be
6010         // constant folded and the select turned into a bitwise or.
6011         Value *Op1 = 0, *Op2 = 0;
6012         if (LHSI->hasOneUse()) {
6013           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6014             // Fold the known value into the constant operand.
6015             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
6016             // Insert a new FCmp of the other select operand.
6017             Op2 = Builder->CreateFCmp(I.getPredicate(),
6018                                       LHSI->getOperand(2), RHSC, I.getName());
6019           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6020             // Fold the known value into the constant operand.
6021             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
6022             // Insert a new FCmp of the other select operand.
6023             Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
6024                                       RHSC, I.getName());
6025           }
6026         }
6027
6028         if (Op1)
6029           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6030         break;
6031       }
6032   }
6033
6034   return Changed ? &I : 0;
6035 }
6036
6037 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
6038   bool Changed = false;
6039   
6040   /// Orders the operands of the compare so that they are listed from most
6041   /// complex to least complex.  This puts constants before unary operators,
6042   /// before binary operators.
6043   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6044     I.swapOperands();
6045     Changed = true;
6046   }
6047   
6048   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6049   
6050   if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
6051     return ReplaceInstUsesWith(I, V);
6052   
6053   const Type *Ty = Op0->getType();
6054
6055   // icmp's with boolean values can always be turned into bitwise operations
6056   if (Ty == Type::getInt1Ty(*Context)) {
6057     switch (I.getPredicate()) {
6058     default: llvm_unreachable("Invalid icmp instruction!");
6059     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
6060       Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
6061       return BinaryOperator::CreateNot(Xor);
6062     }
6063     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
6064       return BinaryOperator::CreateXor(Op0, Op1);
6065
6066     case ICmpInst::ICMP_UGT:
6067       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
6068       // FALL THROUGH
6069     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
6070       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
6071       return BinaryOperator::CreateAnd(Not, Op1);
6072     }
6073     case ICmpInst::ICMP_SGT:
6074       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
6075       // FALL THROUGH
6076     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
6077       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
6078       return BinaryOperator::CreateAnd(Not, Op0);
6079     }
6080     case ICmpInst::ICMP_UGE:
6081       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6082       // FALL THROUGH
6083     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6084       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
6085       return BinaryOperator::CreateOr(Not, Op1);
6086     }
6087     case ICmpInst::ICMP_SGE:
6088       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6089       // FALL THROUGH
6090     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6091       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
6092       return BinaryOperator::CreateOr(Not, Op0);
6093     }
6094     }
6095   }
6096
6097   unsigned BitWidth = 0;
6098   if (TD)
6099     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6100   else if (Ty->isIntOrIntVector())
6101     BitWidth = Ty->getScalarSizeInBits();
6102
6103   bool isSignBit = false;
6104
6105   // See if we are doing a comparison with a constant.
6106   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6107     Value *A = 0, *B = 0;
6108     
6109     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6110     if (I.isEquality() && CI->isNullValue() &&
6111         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
6112       // (icmp cond A B) if cond is equality
6113       return new ICmpInst(I.getPredicate(), A, B);
6114     }
6115     
6116     // If we have an icmp le or icmp ge instruction, turn it into the
6117     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6118     // them being folded in the code below.  The SimplifyICmpInst code has
6119     // already handled the edge cases for us, so we just assert on them.
6120     switch (I.getPredicate()) {
6121     default: break;
6122     case ICmpInst::ICMP_ULE:
6123       assert(!CI->isMaxValue(false));                 // A <=u MAX -> TRUE
6124       return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
6125                           AddOne(CI));
6126     case ICmpInst::ICMP_SLE:
6127       assert(!CI->isMaxValue(true));                  // A <=s MAX -> TRUE
6128       return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6129                           AddOne(CI));
6130     case ICmpInst::ICMP_UGE:
6131       assert(!CI->isMinValue(false));                  // A >=u MIN -> TRUE
6132       return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
6133                           SubOne(CI));
6134     case ICmpInst::ICMP_SGE:
6135       assert(!CI->isMinValue(true));                   // A >=s MIN -> TRUE
6136       return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6137                           SubOne(CI));
6138     }
6139     
6140     // If this comparison is a normal comparison, it demands all
6141     // bits, if it is a sign bit comparison, it only demands the sign bit.
6142     bool UnusedBit;
6143     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6144   }
6145
6146   // See if we can fold the comparison based on range information we can get
6147   // by checking whether bits are known to be zero or one in the input.
6148   if (BitWidth != 0) {
6149     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6150     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6151
6152     if (SimplifyDemandedBits(I.getOperandUse(0),
6153                              isSignBit ? APInt::getSignBit(BitWidth)
6154                                        : APInt::getAllOnesValue(BitWidth),
6155                              Op0KnownZero, Op0KnownOne, 0))
6156       return &I;
6157     if (SimplifyDemandedBits(I.getOperandUse(1),
6158                              APInt::getAllOnesValue(BitWidth),
6159                              Op1KnownZero, Op1KnownOne, 0))
6160       return &I;
6161
6162     // Given the known and unknown bits, compute a range that the LHS could be
6163     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6164     // EQ and NE we use unsigned values.
6165     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6166     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6167     if (I.isSigned()) {
6168       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6169                                              Op0Min, Op0Max);
6170       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6171                                              Op1Min, Op1Max);
6172     } else {
6173       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6174                                                Op0Min, Op0Max);
6175       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6176                                                Op1Min, Op1Max);
6177     }
6178
6179     // If Min and Max are known to be the same, then SimplifyDemandedBits
6180     // figured out that the LHS is a constant.  Just constant fold this now so
6181     // that code below can assume that Min != Max.
6182     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6183       return new ICmpInst(I.getPredicate(),
6184                           ConstantInt::get(*Context, Op0Min), Op1);
6185     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6186       return new ICmpInst(I.getPredicate(), Op0,
6187                           ConstantInt::get(*Context, Op1Min));
6188
6189     // Based on the range information we know about the LHS, see if we can
6190     // simplify this comparison.  For example, (x&4) < 8  is always true.
6191     switch (I.getPredicate()) {
6192     default: llvm_unreachable("Unknown icmp opcode!");
6193     case ICmpInst::ICMP_EQ:
6194       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6195         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6196       break;
6197     case ICmpInst::ICMP_NE:
6198       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6199         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6200       break;
6201     case ICmpInst::ICMP_ULT:
6202       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6203         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6204       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6205         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6206       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6207         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6208       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6209         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6210           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6211                               SubOne(CI));
6212
6213         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6214         if (CI->isMinValue(true))
6215           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6216                            Constant::getAllOnesValue(Op0->getType()));
6217       }
6218       break;
6219     case ICmpInst::ICMP_UGT:
6220       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6221         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6222       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6223         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6224
6225       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6226         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6227       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6228         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6229           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6230                               AddOne(CI));
6231
6232         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6233         if (CI->isMaxValue(true))
6234           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6235                               Constant::getNullValue(Op0->getType()));
6236       }
6237       break;
6238     case ICmpInst::ICMP_SLT:
6239       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6240         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6241       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6242         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6243       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6244         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6245       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6246         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6247           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6248                               SubOne(CI));
6249       }
6250       break;
6251     case ICmpInst::ICMP_SGT:
6252       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6253         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6254       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6255         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6256
6257       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6258         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6259       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6260         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6261           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6262                               AddOne(CI));
6263       }
6264       break;
6265     case ICmpInst::ICMP_SGE:
6266       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6267       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6268         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6269       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6270         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6271       break;
6272     case ICmpInst::ICMP_SLE:
6273       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6274       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6275         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6276       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6277         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6278       break;
6279     case ICmpInst::ICMP_UGE:
6280       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6281       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6282         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6283       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6284         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6285       break;
6286     case ICmpInst::ICMP_ULE:
6287       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6288       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6289         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6290       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6291         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6292       break;
6293     }
6294
6295     // Turn a signed comparison into an unsigned one if both operands
6296     // are known to have the same sign.
6297     if (I.isSigned() &&
6298         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6299          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6300       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6301   }
6302
6303   // Test if the ICmpInst instruction is used exclusively by a select as
6304   // part of a minimum or maximum operation. If so, refrain from doing
6305   // any other folding. This helps out other analyses which understand
6306   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6307   // and CodeGen. And in this case, at least one of the comparison
6308   // operands has at least one user besides the compare (the select),
6309   // which would often largely negate the benefit of folding anyway.
6310   if (I.hasOneUse())
6311     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6312       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6313           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6314         return 0;
6315
6316   // See if we are doing a comparison between a constant and an instruction that
6317   // can be folded into the comparison.
6318   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6319     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6320     // instruction, see if that instruction also has constants so that the 
6321     // instruction can be folded into the icmp 
6322     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6323       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6324         return Res;
6325   }
6326
6327   // Handle icmp with constant (but not simple integer constant) RHS
6328   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6329     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6330       switch (LHSI->getOpcode()) {
6331       case Instruction::GetElementPtr:
6332         if (RHSC->isNullValue()) {
6333           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6334           bool isAllZeros = true;
6335           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6336             if (!isa<Constant>(LHSI->getOperand(i)) ||
6337                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6338               isAllZeros = false;
6339               break;
6340             }
6341           if (isAllZeros)
6342             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6343                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6344         }
6345         break;
6346
6347       case Instruction::PHI:
6348         // Only fold icmp into the PHI if the phi and icmp are in the same
6349         // block.  If in the same block, we're encouraging jump threading.  If
6350         // not, we are just pessimizing the code by making an i1 phi.
6351         if (LHSI->getParent() == I.getParent())
6352           if (Instruction *NV = FoldOpIntoPhi(I, true))
6353             return NV;
6354         break;
6355       case Instruction::Select: {
6356         // If either operand of the select is a constant, we can fold the
6357         // comparison into the select arms, which will cause one to be
6358         // constant folded and the select turned into a bitwise or.
6359         Value *Op1 = 0, *Op2 = 0;
6360         if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
6361           Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6362         if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
6363           Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6364
6365         // We only want to perform this transformation if it will not lead to
6366         // additional code. This is true if either both sides of the select
6367         // fold to a constant (in which case the icmp is replaced with a select
6368         // which will usually simplify) or this is the only user of the
6369         // select (in which case we are trading a select+icmp for a simpler
6370         // select+icmp).
6371         if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
6372           if (!Op1)
6373             Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6374                                       RHSC, I.getName());
6375           if (!Op2)
6376             Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6377                                       RHSC, I.getName());
6378           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6379         }
6380         break;
6381       }
6382       case Instruction::Call:
6383         // If we have (malloc != null), and if the malloc has a single use, we
6384         // can assume it is successful and remove the malloc.
6385         if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6386             isa<ConstantPointerNull>(RHSC)) {
6387           // Need to explicitly erase malloc call here, instead of adding it to
6388           // Worklist, because it won't get DCE'd from the Worklist since
6389           // isInstructionTriviallyDead() returns false for function calls.
6390           // It is OK to replace LHSI/MallocCall with Undef because the 
6391           // instruction that uses it will be erased via Worklist.
6392           if (extractMallocCall(LHSI)) {
6393             LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6394             EraseInstFromFunction(*LHSI);
6395             return ReplaceInstUsesWith(I,
6396                                      ConstantInt::get(Type::getInt1Ty(*Context),
6397                                                       !I.isTrueWhenEqual()));
6398           }
6399           if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6400             if (MallocCall->hasOneUse()) {
6401               MallocCall->replaceAllUsesWith(
6402                                         UndefValue::get(MallocCall->getType()));
6403               EraseInstFromFunction(*MallocCall);
6404               Worklist.Add(LHSI); // The malloc's bitcast use.
6405               return ReplaceInstUsesWith(I,
6406                                      ConstantInt::get(Type::getInt1Ty(*Context),
6407                                                       !I.isTrueWhenEqual()));
6408             }
6409         }
6410         break;
6411       }
6412   }
6413
6414   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6415   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6416     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6417       return NI;
6418   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6419     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6420                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6421       return NI;
6422
6423   // Test to see if the operands of the icmp are casted versions of other
6424   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6425   // now.
6426   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6427     if (isa<PointerType>(Op0->getType()) && 
6428         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6429       // We keep moving the cast from the left operand over to the right
6430       // operand, where it can often be eliminated completely.
6431       Op0 = CI->getOperand(0);
6432
6433       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6434       // so eliminate it as well.
6435       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6436         Op1 = CI2->getOperand(0);
6437
6438       // If Op1 is a constant, we can fold the cast into the constant.
6439       if (Op0->getType() != Op1->getType()) {
6440         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6441           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6442         } else {
6443           // Otherwise, cast the RHS right before the icmp
6444           Op1 = Builder->CreateBitCast(Op1, Op0->getType());
6445         }
6446       }
6447       return new ICmpInst(I.getPredicate(), Op0, Op1);
6448     }
6449   }
6450   
6451   if (isa<CastInst>(Op0)) {
6452     // Handle the special case of: icmp (cast bool to X), <cst>
6453     // This comes up when you have code like
6454     //   int X = A < B;
6455     //   if (X) ...
6456     // For generality, we handle any zero-extension of any operand comparison
6457     // with a constant or another cast from the same type.
6458     if (isa<Constant>(Op1) || isa<CastInst>(Op1))
6459       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6460         return R;
6461   }
6462   
6463   // See if it's the same type of instruction on the left and right.
6464   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6465     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6466       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6467           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6468         switch (Op0I->getOpcode()) {
6469         default: break;
6470         case Instruction::Add:
6471         case Instruction::Sub:
6472         case Instruction::Xor:
6473           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6474             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6475                                 Op1I->getOperand(0));
6476           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6477           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6478             if (CI->getValue().isSignBit()) {
6479               ICmpInst::Predicate Pred = I.isSigned()
6480                                              ? I.getUnsignedPredicate()
6481                                              : I.getSignedPredicate();
6482               return new ICmpInst(Pred, Op0I->getOperand(0),
6483                                   Op1I->getOperand(0));
6484             }
6485             
6486             if (CI->getValue().isMaxSignedValue()) {
6487               ICmpInst::Predicate Pred = I.isSigned()
6488                                              ? I.getUnsignedPredicate()
6489                                              : I.getSignedPredicate();
6490               Pred = I.getSwappedPredicate(Pred);
6491               return new ICmpInst(Pred, Op0I->getOperand(0),
6492                                   Op1I->getOperand(0));
6493             }
6494           }
6495           break;
6496         case Instruction::Mul:
6497           if (!I.isEquality())
6498             break;
6499
6500           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6501             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6502             // Mask = -1 >> count-trailing-zeros(Cst).
6503             if (!CI->isZero() && !CI->isOne()) {
6504               const APInt &AP = CI->getValue();
6505               ConstantInt *Mask = ConstantInt::get(*Context, 
6506                                       APInt::getLowBitsSet(AP.getBitWidth(),
6507                                                            AP.getBitWidth() -
6508                                                       AP.countTrailingZeros()));
6509               Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6510               Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
6511               return new ICmpInst(I.getPredicate(), And1, And2);
6512             }
6513           }
6514           break;
6515         }
6516       }
6517     }
6518   }
6519   
6520   // ~x < ~y --> y < x
6521   { Value *A, *B;
6522     if (match(Op0, m_Not(m_Value(A))) &&
6523         match(Op1, m_Not(m_Value(B))))
6524       return new ICmpInst(I.getPredicate(), B, A);
6525   }
6526   
6527   if (I.isEquality()) {
6528     Value *A, *B, *C, *D;
6529     
6530     // -x == -y --> x == y
6531     if (match(Op0, m_Neg(m_Value(A))) &&
6532         match(Op1, m_Neg(m_Value(B))))
6533       return new ICmpInst(I.getPredicate(), A, B);
6534     
6535     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6536       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6537         Value *OtherVal = A == Op1 ? B : A;
6538         return new ICmpInst(I.getPredicate(), OtherVal,
6539                             Constant::getNullValue(A->getType()));
6540       }
6541
6542       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6543         // A^c1 == C^c2 --> A == C^(c1^c2)
6544         ConstantInt *C1, *C2;
6545         if (match(B, m_ConstantInt(C1)) &&
6546             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6547           Constant *NC = 
6548                    ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6549           Value *Xor = Builder->CreateXor(C, NC, "tmp");
6550           return new ICmpInst(I.getPredicate(), A, Xor);
6551         }
6552         
6553         // A^B == A^D -> B == D
6554         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6555         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6556         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6557         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6558       }
6559     }
6560     
6561     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6562         (A == Op0 || B == Op0)) {
6563       // A == (A^B)  ->  B == 0
6564       Value *OtherVal = A == Op0 ? B : A;
6565       return new ICmpInst(I.getPredicate(), OtherVal,
6566                           Constant::getNullValue(A->getType()));
6567     }
6568
6569     // (A-B) == A  ->  B == 0
6570     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6571       return new ICmpInst(I.getPredicate(), B, 
6572                           Constant::getNullValue(B->getType()));
6573
6574     // A == (A-B)  ->  B == 0
6575     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6576       return new ICmpInst(I.getPredicate(), B,
6577                           Constant::getNullValue(B->getType()));
6578     
6579     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6580     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6581         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6582         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6583       Value *X = 0, *Y = 0, *Z = 0;
6584       
6585       if (A == C) {
6586         X = B; Y = D; Z = A;
6587       } else if (A == D) {
6588         X = B; Y = C; Z = A;
6589       } else if (B == C) {
6590         X = A; Y = D; Z = B;
6591       } else if (B == D) {
6592         X = A; Y = C; Z = B;
6593       }
6594       
6595       if (X) {   // Build (X^Y) & Z
6596         Op1 = Builder->CreateXor(X, Y, "tmp");
6597         Op1 = Builder->CreateAnd(Op1, Z, "tmp");
6598         I.setOperand(0, Op1);
6599         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6600         return &I;
6601       }
6602     }
6603   }
6604   
6605   {
6606     Value *X; ConstantInt *Cst;
6607     // icmp (X+Cst), X
6608     if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
6609       return FoldICmpAddOpCst(I, X, Cst, I.getPredicate());
6610       
6611     // icmp X, X+Cst
6612     if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
6613       return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate());
6614   }
6615   return Changed ? &I : 0;
6616 }
6617
6618 /// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
6619 Instruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI,
6620                                             Value *X, ConstantInt *CI,
6621                                             ICmpInst::Predicate Pred) {
6622   // If we have X+0, exit early (simplifying logic below) and let it get folded
6623   // elsewhere.   icmp X+0, X  -> icmp X, X
6624   if (CI->isZero()) {
6625     bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
6626     return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6627   }
6628   
6629   // (X+4) == X -> false.
6630   if (Pred == ICmpInst::ICMP_EQ)
6631     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
6632
6633   // (X+4) != X -> true.
6634   if (Pred == ICmpInst::ICMP_NE)
6635     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
6636   
6637   // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
6638   // so the values can never be equal.  Similiarly for all other "or equals"
6639   // operators.
6640   
6641   // (X+1) <u X        --> X >u (MAXUINT-1)        --> X != 255
6642   // (X+2) <u X        --> X >u (MAXUINT-2)        --> X > 253
6643   // (X+MAXUINT) <u X  --> X >u (MAXUINT-MAXUINT)  --> X != 0
6644   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
6645     Value *R = ConstantExpr::getSub(ConstantInt::get(CI->getType(), -1ULL), CI);
6646     return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
6647   }
6648   
6649   // (X+1) >u X        --> X <u (0-1)        --> X != 255
6650   // (X+2) >u X        --> X <u (0-2)        --> X <u 254
6651   // (X+MAXUINT) >u X  --> X <u (0-MAXUINT)  --> X <u 1  --> X == 0
6652   if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
6653     return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
6654   
6655   unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
6656   ConstantInt *SMax = ConstantInt::get(X->getContext(),
6657                                        APInt::getSignedMaxValue(BitWidth));
6658
6659   // (X+ 1) <s X       --> X >s (MAXSINT-1)          --> X == 127
6660   // (X+ 2) <s X       --> X >s (MAXSINT-2)          --> X >s 125
6661   // (X+MAXSINT) <s X  --> X >s (MAXSINT-MAXSINT)    --> X >s 0
6662   // (X+MINSINT) <s X  --> X >s (MAXSINT-MINSINT)    --> X >s -1
6663   // (X+ -2) <s X      --> X >s (MAXSINT- -2)        --> X >s 126
6664   // (X+ -1) <s X      --> X >s (MAXSINT- -1)        --> X != 127
6665   if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
6666     return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
6667   
6668   // (X+ 1) >s X       --> X <s (MAXSINT-(1-1))       --> X != 127
6669   // (X+ 2) >s X       --> X <s (MAXSINT-(2-1))       --> X <s 126
6670   // (X+MAXSINT) >s X  --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
6671   // (X+MINSINT) >s X  --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
6672   // (X+ -2) >s X      --> X <s (MAXSINT-(-2-1))      --> X <s -126
6673   // (X+ -1) >s X      --> X <s (MAXSINT-(-1-1))      --> X == -128
6674   assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
6675   Constant *C = ConstantInt::get(X->getContext(), CI->getValue()-1);
6676   return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
6677 }
6678
6679 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6680 /// and CmpRHS are both known to be integer constants.
6681 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6682                                           ConstantInt *DivRHS) {
6683   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6684   const APInt &CmpRHSV = CmpRHS->getValue();
6685   
6686   // FIXME: If the operand types don't match the type of the divide 
6687   // then don't attempt this transform. The code below doesn't have the
6688   // logic to deal with a signed divide and an unsigned compare (and
6689   // vice versa). This is because (x /s C1) <s C2  produces different 
6690   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6691   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6692   // work. :(  The if statement below tests that condition and bails 
6693   // if it finds it. 
6694   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6695   if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
6696     return 0;
6697   if (DivRHS->isZero())
6698     return 0; // The ProdOV computation fails on divide by zero.
6699   if (DivIsSigned && DivRHS->isAllOnesValue())
6700     return 0; // The overflow computation also screws up here
6701   if (DivRHS->isOne())
6702     return 0; // Not worth bothering, and eliminates some funny cases
6703               // with INT_MIN.
6704
6705   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6706   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6707   // C2 (CI). By solving for X we can turn this into a range check 
6708   // instead of computing a divide. 
6709   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6710
6711   // Determine if the product overflows by seeing if the product is
6712   // not equal to the divide. Make sure we do the same kind of divide
6713   // as in the LHS instruction that we're folding. 
6714   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6715                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6716
6717   // Get the ICmp opcode
6718   ICmpInst::Predicate Pred = ICI.getPredicate();
6719
6720   // Figure out the interval that is being checked.  For example, a comparison
6721   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6722   // Compute this interval based on the constants involved and the signedness of
6723   // the compare/divide.  This computes a half-open interval, keeping track of
6724   // whether either value in the interval overflows.  After analysis each
6725   // overflow variable is set to 0 if it's corresponding bound variable is valid
6726   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6727   int LoOverflow = 0, HiOverflow = 0;
6728   Constant *LoBound = 0, *HiBound = 0;
6729   
6730   if (!DivIsSigned) {  // udiv
6731     // e.g. X/5 op 3  --> [15, 20)
6732     LoBound = Prod;
6733     HiOverflow = LoOverflow = ProdOV;
6734     if (!HiOverflow)
6735       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6736   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6737     if (CmpRHSV == 0) {       // (X / pos) op 0
6738       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6739       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6740       HiBound = DivRHS;
6741     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6742       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6743       HiOverflow = LoOverflow = ProdOV;
6744       if (!HiOverflow)
6745         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6746     } else {                       // (X / pos) op neg
6747       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6748       HiBound = AddOne(Prod);
6749       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6750       if (!LoOverflow) {
6751         ConstantInt* DivNeg =
6752                          cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6753         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6754                                      true) ? -1 : 0;
6755        }
6756     }
6757   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6758     if (CmpRHSV == 0) {       // (X / neg) op 0
6759       // e.g. X/-5 op 0  --> [-4, 5)
6760       LoBound = AddOne(DivRHS);
6761       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6762       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6763         HiOverflow = 1;            // [INTMIN+1, overflow)
6764         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6765       }
6766     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6767       // e.g. X/-5 op 3  --> [-19, -14)
6768       HiBound = AddOne(Prod);
6769       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6770       if (!LoOverflow)
6771         LoOverflow = AddWithOverflow(LoBound, HiBound,
6772                                      DivRHS, Context, true) ? -1 : 0;
6773     } else {                       // (X / neg) op neg
6774       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6775       LoOverflow = HiOverflow = ProdOV;
6776       if (!HiOverflow)
6777         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6778     }
6779     
6780     // Dividing by a negative swaps the condition.  LT <-> GT
6781     Pred = ICmpInst::getSwappedPredicate(Pred);
6782   }
6783
6784   Value *X = DivI->getOperand(0);
6785   switch (Pred) {
6786   default: llvm_unreachable("Unhandled icmp opcode!");
6787   case ICmpInst::ICMP_EQ:
6788     if (LoOverflow && HiOverflow)
6789       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6790     else if (HiOverflow)
6791       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6792                           ICmpInst::ICMP_UGE, X, LoBound);
6793     else if (LoOverflow)
6794       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6795                           ICmpInst::ICMP_ULT, X, HiBound);
6796     else
6797       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6798   case ICmpInst::ICMP_NE:
6799     if (LoOverflow && HiOverflow)
6800       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6801     else if (HiOverflow)
6802       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6803                           ICmpInst::ICMP_ULT, X, LoBound);
6804     else if (LoOverflow)
6805       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6806                           ICmpInst::ICMP_UGE, X, HiBound);
6807     else
6808       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6809   case ICmpInst::ICMP_ULT:
6810   case ICmpInst::ICMP_SLT:
6811     if (LoOverflow == +1)   // Low bound is greater than input range.
6812       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6813     if (LoOverflow == -1)   // Low bound is less than input range.
6814       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6815     return new ICmpInst(Pred, X, LoBound);
6816   case ICmpInst::ICMP_UGT:
6817   case ICmpInst::ICMP_SGT:
6818     if (HiOverflow == +1)       // High bound greater than input range.
6819       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6820     else if (HiOverflow == -1)  // High bound less than input range.
6821       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6822     if (Pred == ICmpInst::ICMP_UGT)
6823       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6824     else
6825       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6826   }
6827 }
6828
6829
6830 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6831 ///
6832 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6833                                                           Instruction *LHSI,
6834                                                           ConstantInt *RHS) {
6835   const APInt &RHSV = RHS->getValue();
6836   
6837   switch (LHSI->getOpcode()) {
6838   case Instruction::Trunc:
6839     if (ICI.isEquality() && LHSI->hasOneUse()) {
6840       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6841       // of the high bits truncated out of x are known.
6842       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6843              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6844       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6845       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6846       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6847       
6848       // If all the high bits are known, we can do this xform.
6849       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6850         // Pull in the high bits from known-ones set.
6851         APInt NewRHS(RHS->getValue());
6852         NewRHS.zext(SrcBits);
6853         NewRHS |= KnownOne;
6854         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6855                             ConstantInt::get(*Context, NewRHS));
6856       }
6857     }
6858     break;
6859       
6860   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6861     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6862       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6863       // fold the xor.
6864       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6865           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6866         Value *CompareVal = LHSI->getOperand(0);
6867         
6868         // If the sign bit of the XorCST is not set, there is no change to
6869         // the operation, just stop using the Xor.
6870         if (!XorCST->getValue().isNegative()) {
6871           ICI.setOperand(0, CompareVal);
6872           Worklist.Add(LHSI);
6873           return &ICI;
6874         }
6875         
6876         // Was the old condition true if the operand is positive?
6877         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6878         
6879         // If so, the new one isn't.
6880         isTrueIfPositive ^= true;
6881         
6882         if (isTrueIfPositive)
6883           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
6884                               SubOne(RHS));
6885         else
6886           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
6887                               AddOne(RHS));
6888       }
6889
6890       if (LHSI->hasOneUse()) {
6891         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6892         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6893           const APInt &SignBit = XorCST->getValue();
6894           ICmpInst::Predicate Pred = ICI.isSigned()
6895                                          ? ICI.getUnsignedPredicate()
6896                                          : ICI.getSignedPredicate();
6897           return new ICmpInst(Pred, LHSI->getOperand(0),
6898                               ConstantInt::get(*Context, RHSV ^ SignBit));
6899         }
6900
6901         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6902         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6903           const APInt &NotSignBit = XorCST->getValue();
6904           ICmpInst::Predicate Pred = ICI.isSigned()
6905                                          ? ICI.getUnsignedPredicate()
6906                                          : ICI.getSignedPredicate();
6907           Pred = ICI.getSwappedPredicate(Pred);
6908           return new ICmpInst(Pred, LHSI->getOperand(0),
6909                               ConstantInt::get(*Context, RHSV ^ NotSignBit));
6910         }
6911       }
6912     }
6913     break;
6914   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6915     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6916         LHSI->getOperand(0)->hasOneUse()) {
6917       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6918       
6919       // If the LHS is an AND of a truncating cast, we can widen the
6920       // and/compare to be the input width without changing the value
6921       // produced, eliminating a cast.
6922       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6923         // We can do this transformation if either the AND constant does not
6924         // have its sign bit set or if it is an equality comparison. 
6925         // Extending a relational comparison when we're checking the sign
6926         // bit would not work.
6927         if (Cast->hasOneUse() &&
6928             (ICI.isEquality() ||
6929              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6930           uint32_t BitWidth = 
6931             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6932           APInt NewCST = AndCST->getValue();
6933           NewCST.zext(BitWidth);
6934           APInt NewCI = RHSV;
6935           NewCI.zext(BitWidth);
6936           Value *NewAnd = 
6937             Builder->CreateAnd(Cast->getOperand(0),
6938                            ConstantInt::get(*Context, NewCST), LHSI->getName());
6939           return new ICmpInst(ICI.getPredicate(), NewAnd,
6940                               ConstantInt::get(*Context, NewCI));
6941         }
6942       }
6943       
6944       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6945       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6946       // happens a LOT in code produced by the C front-end, for bitfield
6947       // access.
6948       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6949       if (Shift && !Shift->isShift())
6950         Shift = 0;
6951       
6952       ConstantInt *ShAmt;
6953       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6954       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6955       const Type *AndTy = AndCST->getType();          // Type of the and.
6956       
6957       // We can fold this as long as we can't shift unknown bits
6958       // into the mask.  This can only happen with signed shift
6959       // rights, as they sign-extend.
6960       if (ShAmt) {
6961         bool CanFold = Shift->isLogicalShift();
6962         if (!CanFold) {
6963           // To test for the bad case of the signed shr, see if any
6964           // of the bits shifted in could be tested after the mask.
6965           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6966           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6967           
6968           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6969           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6970                AndCST->getValue()) == 0)
6971             CanFold = true;
6972         }
6973         
6974         if (CanFold) {
6975           Constant *NewCst;
6976           if (Shift->getOpcode() == Instruction::Shl)
6977             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6978           else
6979             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6980           
6981           // Check to see if we are shifting out any of the bits being
6982           // compared.
6983           if (ConstantExpr::get(Shift->getOpcode(),
6984                                        NewCst, ShAmt) != RHS) {
6985             // If we shifted bits out, the fold is not going to work out.
6986             // As a special case, check to see if this means that the
6987             // result is always true or false now.
6988             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6989               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6990             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6991               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6992           } else {
6993             ICI.setOperand(1, NewCst);
6994             Constant *NewAndCST;
6995             if (Shift->getOpcode() == Instruction::Shl)
6996               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6997             else
6998               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6999             LHSI->setOperand(1, NewAndCST);
7000             LHSI->setOperand(0, Shift->getOperand(0));
7001             Worklist.Add(Shift); // Shift is dead.
7002             return &ICI;
7003           }
7004         }
7005       }
7006       
7007       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
7008       // preferable because it allows the C<<Y expression to be hoisted out
7009       // of a loop if Y is invariant and X is not.
7010       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
7011           ICI.isEquality() && !Shift->isArithmeticShift() &&
7012           !isa<Constant>(Shift->getOperand(0))) {
7013         // Compute C << Y.
7014         Value *NS;
7015         if (Shift->getOpcode() == Instruction::LShr) {
7016           NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
7017         } else {
7018           // Insert a logical shift.
7019           NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
7020         }
7021         
7022         // Compute X & (C << Y).
7023         Value *NewAnd = 
7024           Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
7025         
7026         ICI.setOperand(0, NewAnd);
7027         return &ICI;
7028       }
7029     }
7030     break;
7031     
7032   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
7033     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7034     if (!ShAmt) break;
7035     
7036     uint32_t TypeBits = RHSV.getBitWidth();
7037     
7038     // Check that the shift amount is in range.  If not, don't perform
7039     // undefined shifts.  When the shift is visited it will be
7040     // simplified.
7041     if (ShAmt->uge(TypeBits))
7042       break;
7043     
7044     if (ICI.isEquality()) {
7045       // If we are comparing against bits always shifted out, the
7046       // comparison cannot succeed.
7047       Constant *Comp =
7048         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
7049                                                                  ShAmt);
7050       if (Comp != RHS) {// Comparing against a bit that we know is zero.
7051         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7052         Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
7053         return ReplaceInstUsesWith(ICI, Cst);
7054       }
7055       
7056       if (LHSI->hasOneUse()) {
7057         // Otherwise strength reduce the shift into an and.
7058         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
7059         Constant *Mask =
7060           ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits, 
7061                                                        TypeBits-ShAmtVal));
7062         
7063         Value *And =
7064           Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
7065         return new ICmpInst(ICI.getPredicate(), And,
7066                             ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
7067       }
7068     }
7069     
7070     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
7071     bool TrueIfSigned = false;
7072     if (LHSI->hasOneUse() &&
7073         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
7074       // (X << 31) <s 0  --> (X&1) != 0
7075       Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
7076                                            (TypeBits-ShAmt->getZExtValue()-1));
7077       Value *And =
7078         Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
7079       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
7080                           And, Constant::getNullValue(And->getType()));
7081     }
7082     break;
7083   }
7084     
7085   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
7086   case Instruction::AShr: {
7087     // Only handle equality comparisons of shift-by-constant.
7088     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7089     if (!ShAmt || !ICI.isEquality()) break;
7090
7091     // Check that the shift amount is in range.  If not, don't perform
7092     // undefined shifts.  When the shift is visited it will be
7093     // simplified.
7094     uint32_t TypeBits = RHSV.getBitWidth();
7095     if (ShAmt->uge(TypeBits))
7096       break;
7097     
7098     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
7099       
7100     // If we are comparing against bits always shifted out, the
7101     // comparison cannot succeed.
7102     APInt Comp = RHSV << ShAmtVal;
7103     if (LHSI->getOpcode() == Instruction::LShr)
7104       Comp = Comp.lshr(ShAmtVal);
7105     else
7106       Comp = Comp.ashr(ShAmtVal);
7107     
7108     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7109       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7110       Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
7111       return ReplaceInstUsesWith(ICI, Cst);
7112     }
7113     
7114     // Otherwise, check to see if the bits shifted out are known to be zero.
7115     // If so, we can compare against the unshifted value:
7116     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
7117     if (LHSI->hasOneUse() &&
7118         MaskedValueIsZero(LHSI->getOperand(0), 
7119                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
7120       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
7121                           ConstantExpr::getShl(RHS, ShAmt));
7122     }
7123       
7124     if (LHSI->hasOneUse()) {
7125       // Otherwise strength reduce the shift into an and.
7126       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7127       Constant *Mask = ConstantInt::get(*Context, Val);
7128       
7129       Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7130                                       Mask, LHSI->getName()+".mask");
7131       return new ICmpInst(ICI.getPredicate(), And,
7132                           ConstantExpr::getShl(RHS, ShAmt));
7133     }
7134     break;
7135   }
7136     
7137   case Instruction::SDiv:
7138   case Instruction::UDiv:
7139     // Fold: icmp pred ([us]div X, C1), C2 -> range test
7140     // Fold this div into the comparison, producing a range check. 
7141     // Determine, based on the divide type, what the range is being 
7142     // checked.  If there is an overflow on the low or high side, remember 
7143     // it, otherwise compute the range [low, hi) bounding the new value.
7144     // See: InsertRangeTest above for the kinds of replacements possible.
7145     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7146       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7147                                           DivRHS))
7148         return R;
7149     break;
7150
7151   case Instruction::Add:
7152     // Fold: icmp pred (add X, C1), C2
7153     if (!ICI.isEquality()) {
7154       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7155       if (!LHSC) break;
7156       const APInt &LHSV = LHSC->getValue();
7157
7158       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7159                             .subtract(LHSV);
7160
7161       if (ICI.isSigned()) {
7162         if (CR.getLower().isSignBit()) {
7163           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7164                               ConstantInt::get(*Context, CR.getUpper()));
7165         } else if (CR.getUpper().isSignBit()) {
7166           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7167                               ConstantInt::get(*Context, CR.getLower()));
7168         }
7169       } else {
7170         if (CR.getLower().isMinValue()) {
7171           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7172                               ConstantInt::get(*Context, CR.getUpper()));
7173         } else if (CR.getUpper().isMinValue()) {
7174           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7175                               ConstantInt::get(*Context, CR.getLower()));
7176         }
7177       }
7178     }
7179     break;
7180   }
7181   
7182   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7183   if (ICI.isEquality()) {
7184     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7185     
7186     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7187     // the second operand is a constant, simplify a bit.
7188     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7189       switch (BO->getOpcode()) {
7190       case Instruction::SRem:
7191         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7192         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7193           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7194           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7195             Value *NewRem =
7196               Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7197                                   BO->getName());
7198             return new ICmpInst(ICI.getPredicate(), NewRem,
7199                                 Constant::getNullValue(BO->getType()));
7200           }
7201         }
7202         break;
7203       case Instruction::Add:
7204         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7205         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7206           if (BO->hasOneUse())
7207             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7208                                 ConstantExpr::getSub(RHS, BOp1C));
7209         } else if (RHSV == 0) {
7210           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7211           // efficiently invertible, or if the add has just this one use.
7212           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7213           
7214           if (Value *NegVal = dyn_castNegVal(BOp1))
7215             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
7216           else if (Value *NegVal = dyn_castNegVal(BOp0))
7217             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
7218           else if (BO->hasOneUse()) {
7219             Value *Neg = Builder->CreateNeg(BOp1);
7220             Neg->takeName(BO);
7221             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
7222           }
7223         }
7224         break;
7225       case Instruction::Xor:
7226         // For the xor case, we can xor two constants together, eliminating
7227         // the explicit xor.
7228         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7229           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
7230                               ConstantExpr::getXor(RHS, BOC));
7231         
7232         // FALLTHROUGH
7233       case Instruction::Sub:
7234         // Replace (([sub|xor] A, B) != 0) with (A != B)
7235         if (RHSV == 0)
7236           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7237                               BO->getOperand(1));
7238         break;
7239         
7240       case Instruction::Or:
7241         // If bits are being or'd in that are not present in the constant we
7242         // are comparing against, then the comparison could never succeed!
7243         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7244           Constant *NotCI = ConstantExpr::getNot(RHS);
7245           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7246             return ReplaceInstUsesWith(ICI,
7247                                        ConstantInt::get(Type::getInt1Ty(*Context), 
7248                                        isICMP_NE));
7249         }
7250         break;
7251         
7252       case Instruction::And:
7253         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7254           // If bits are being compared against that are and'd out, then the
7255           // comparison can never succeed!
7256           if ((RHSV & ~BOC->getValue()) != 0)
7257             return ReplaceInstUsesWith(ICI,
7258                                        ConstantInt::get(Type::getInt1Ty(*Context),
7259                                        isICMP_NE));
7260           
7261           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7262           if (RHS == BOC && RHSV.isPowerOf2())
7263             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7264                                 ICmpInst::ICMP_NE, LHSI,
7265                                 Constant::getNullValue(RHS->getType()));
7266           
7267           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7268           if (BOC->getValue().isSignBit()) {
7269             Value *X = BO->getOperand(0);
7270             Constant *Zero = Constant::getNullValue(X->getType());
7271             ICmpInst::Predicate pred = isICMP_NE ? 
7272               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7273             return new ICmpInst(pred, X, Zero);
7274           }
7275           
7276           // ((X & ~7) == 0) --> X < 8
7277           if (RHSV == 0 && isHighOnes(BOC)) {
7278             Value *X = BO->getOperand(0);
7279             Constant *NegX = ConstantExpr::getNeg(BOC);
7280             ICmpInst::Predicate pred = isICMP_NE ? 
7281               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7282             return new ICmpInst(pred, X, NegX);
7283           }
7284         }
7285       default: break;
7286       }
7287     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7288       // Handle icmp {eq|ne} <intrinsic>, intcst.
7289       if (II->getIntrinsicID() == Intrinsic::bswap) {
7290         Worklist.Add(II);
7291         ICI.setOperand(0, II->getOperand(1));
7292         ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7293         return &ICI;
7294       }
7295     }
7296   }
7297   return 0;
7298 }
7299
7300 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7301 /// We only handle extending casts so far.
7302 ///
7303 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7304   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7305   Value *LHSCIOp        = LHSCI->getOperand(0);
7306   const Type *SrcTy     = LHSCIOp->getType();
7307   const Type *DestTy    = LHSCI->getType();
7308   Value *RHSCIOp;
7309
7310   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7311   // integer type is the same size as the pointer type.
7312   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7313       TD->getPointerSizeInBits() ==
7314          cast<IntegerType>(DestTy)->getBitWidth()) {
7315     Value *RHSOp = 0;
7316     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7317       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7318     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7319       RHSOp = RHSC->getOperand(0);
7320       // If the pointer types don't match, insert a bitcast.
7321       if (LHSCIOp->getType() != RHSOp->getType())
7322         RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
7323     }
7324
7325     if (RHSOp)
7326       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7327   }
7328   
7329   // The code below only handles extension cast instructions, so far.
7330   // Enforce this.
7331   if (LHSCI->getOpcode() != Instruction::ZExt &&
7332       LHSCI->getOpcode() != Instruction::SExt)
7333     return 0;
7334
7335   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7336   bool isSignedCmp = ICI.isSigned();
7337
7338   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7339     // Not an extension from the same type?
7340     RHSCIOp = CI->getOperand(0);
7341     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7342       return 0;
7343     
7344     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7345     // and the other is a zext), then we can't handle this.
7346     if (CI->getOpcode() != LHSCI->getOpcode())
7347       return 0;
7348
7349     // Deal with equality cases early.
7350     if (ICI.isEquality())
7351       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7352
7353     // A signed comparison of sign extended values simplifies into a
7354     // signed comparison.
7355     if (isSignedCmp && isSignedExt)
7356       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7357
7358     // The other three cases all fold into an unsigned comparison.
7359     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7360   }
7361
7362   // If we aren't dealing with a constant on the RHS, exit early
7363   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7364   if (!CI)
7365     return 0;
7366
7367   // Compute the constant that would happen if we truncated to SrcTy then
7368   // reextended to DestTy.
7369   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7370   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7371                                                 Res1, DestTy);
7372
7373   // If the re-extended constant didn't change...
7374   if (Res2 == CI) {
7375     // Deal with equality cases early.
7376     if (ICI.isEquality())
7377       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7378
7379     // A signed comparison of sign extended values simplifies into a
7380     // signed comparison.
7381     if (isSignedExt && isSignedCmp)
7382       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7383
7384     // The other three cases all fold into an unsigned comparison.
7385     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
7386   }
7387
7388   // The re-extended constant changed so the constant cannot be represented 
7389   // in the shorter type. Consequently, we cannot emit a simple comparison.
7390
7391   // First, handle some easy cases. We know the result cannot be equal at this
7392   // point so handle the ICI.isEquality() cases
7393   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7394     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7395   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7396     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7397
7398   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7399   // should have been folded away previously and not enter in here.
7400   Value *Result;
7401   if (isSignedCmp) {
7402     // We're performing a signed comparison.
7403     if (cast<ConstantInt>(CI)->getValue().isNegative())
7404       Result = ConstantInt::getFalse(*Context);          // X < (small) --> false
7405     else
7406       Result = ConstantInt::getTrue(*Context);           // X < (large) --> true
7407   } else {
7408     // We're performing an unsigned comparison.
7409     if (isSignedExt) {
7410       // We're performing an unsigned comp with a sign extended value.
7411       // This is true if the input is >= 0. [aka >s -1]
7412       Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7413       Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
7414     } else {
7415       // Unsigned extend & unsigned compare -> always true.
7416       Result = ConstantInt::getTrue(*Context);
7417     }
7418   }
7419
7420   // Finally, return the value computed.
7421   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7422       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7423     return ReplaceInstUsesWith(ICI, Result);
7424
7425   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7426           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7427          "ICmp should be folded!");
7428   if (Constant *CI = dyn_cast<Constant>(Result))
7429     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7430   return BinaryOperator::CreateNot(Result);
7431 }
7432
7433 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7434   return commonShiftTransforms(I);
7435 }
7436
7437 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7438   return commonShiftTransforms(I);
7439 }
7440
7441 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7442   if (Instruction *R = commonShiftTransforms(I))
7443     return R;
7444   
7445   Value *Op0 = I.getOperand(0);
7446   
7447   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7448   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7449     if (CSI->isAllOnesValue())
7450       return ReplaceInstUsesWith(I, CSI);
7451
7452   // See if we can turn a signed shr into an unsigned shr.
7453   if (MaskedValueIsZero(Op0,
7454                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7455     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7456
7457   // Arithmetic shifting an all-sign-bit value is a no-op.
7458   unsigned NumSignBits = ComputeNumSignBits(Op0);
7459   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7460     return ReplaceInstUsesWith(I, Op0);
7461
7462   return 0;
7463 }
7464
7465 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7466   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7467   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7468
7469   // shl X, 0 == X and shr X, 0 == X
7470   // shl 0, X == 0 and shr 0, X == 0
7471   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7472       Op0 == Constant::getNullValue(Op0->getType()))
7473     return ReplaceInstUsesWith(I, Op0);
7474   
7475   if (isa<UndefValue>(Op0)) {            
7476     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7477       return ReplaceInstUsesWith(I, Op0);
7478     else                                    // undef << X -> 0, undef >>u X -> 0
7479       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7480   }
7481   if (isa<UndefValue>(Op1)) {
7482     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7483       return ReplaceInstUsesWith(I, Op0);          
7484     else                                     // X << undef, X >>u undef -> 0
7485       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7486   }
7487
7488   // See if we can fold away this shift.
7489   if (SimplifyDemandedInstructionBits(I))
7490     return &I;
7491
7492   // Try to fold constant and into select arguments.
7493   if (isa<Constant>(Op0))
7494     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7495       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7496         return R;
7497
7498   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7499     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7500       return Res;
7501   return 0;
7502 }
7503
7504 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7505                                                BinaryOperator &I) {
7506   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7507
7508   // See if we can simplify any instructions used by the instruction whose sole 
7509   // purpose is to compute bits we don't care about.
7510   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7511   
7512   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7513   // a signed shift.
7514   //
7515   if (Op1->uge(TypeBits)) {
7516     if (I.getOpcode() != Instruction::AShr)
7517       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7518     else {
7519       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7520       return &I;
7521     }
7522   }
7523   
7524   // ((X*C1) << C2) == (X * (C1 << C2))
7525   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7526     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7527       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7528         return BinaryOperator::CreateMul(BO->getOperand(0),
7529                                         ConstantExpr::getShl(BOOp, Op1));
7530   
7531   // Try to fold constant and into select arguments.
7532   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7533     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7534       return R;
7535   if (isa<PHINode>(Op0))
7536     if (Instruction *NV = FoldOpIntoPhi(I))
7537       return NV;
7538   
7539   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7540   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7541     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7542     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7543     // place.  Don't try to do this transformation in this case.  Also, we
7544     // require that the input operand is a shift-by-constant so that we have
7545     // confidence that the shifts will get folded together.  We could do this
7546     // xform in more cases, but it is unlikely to be profitable.
7547     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7548         isa<ConstantInt>(TrOp->getOperand(1))) {
7549       // Okay, we'll do this xform.  Make the shift of shift.
7550       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7551       // (shift2 (shift1 & 0x00FF), c2)
7552       Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
7553
7554       // For logical shifts, the truncation has the effect of making the high
7555       // part of the register be zeros.  Emulate this by inserting an AND to
7556       // clear the top bits as needed.  This 'and' will usually be zapped by
7557       // other xforms later if dead.
7558       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7559       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7560       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7561       
7562       // The mask we constructed says what the trunc would do if occurring
7563       // between the shifts.  We want to know the effect *after* the second
7564       // shift.  We know that it is a logical shift by a constant, so adjust the
7565       // mask as appropriate.
7566       if (I.getOpcode() == Instruction::Shl)
7567         MaskV <<= Op1->getZExtValue();
7568       else {
7569         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7570         MaskV = MaskV.lshr(Op1->getZExtValue());
7571       }
7572
7573       // shift1 & 0x00FF
7574       Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7575                                       TI->getName());
7576
7577       // Return the value truncated to the interesting size.
7578       return new TruncInst(And, I.getType());
7579     }
7580   }
7581   
7582   if (Op0->hasOneUse()) {
7583     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7584       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7585       Value *V1, *V2;
7586       ConstantInt *CC;
7587       switch (Op0BO->getOpcode()) {
7588         default: break;
7589         case Instruction::Add:
7590         case Instruction::And:
7591         case Instruction::Or:
7592         case Instruction::Xor: {
7593           // These operators commute.
7594           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7595           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7596               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7597                     m_Specific(Op1)))) {
7598             Value *YS =         // (Y << C)
7599               Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7600             // (X + (Y << C))
7601             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7602                                             Op0BO->getOperand(1)->getName());
7603             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7604             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7605                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7606           }
7607           
7608           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7609           Value *Op0BOOp1 = Op0BO->getOperand(1);
7610           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7611               match(Op0BOOp1, 
7612                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7613                           m_ConstantInt(CC))) &&
7614               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7615             Value *YS =   // (Y << C)
7616               Builder->CreateShl(Op0BO->getOperand(0), Op1,
7617                                            Op0BO->getName());
7618             // X & (CC << C)
7619             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7620                                            V1->getName()+".mask");
7621             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7622           }
7623         }
7624           
7625         // FALL THROUGH.
7626         case Instruction::Sub: {
7627           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7628           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7629               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7630                     m_Specific(Op1)))) {
7631             Value *YS =  // (Y << C)
7632               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7633             // (X + (Y << C))
7634             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7635                                             Op0BO->getOperand(0)->getName());
7636             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7637             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7638                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7639           }
7640           
7641           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7642           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7643               match(Op0BO->getOperand(0),
7644                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7645                           m_ConstantInt(CC))) && V2 == Op1 &&
7646               cast<BinaryOperator>(Op0BO->getOperand(0))
7647                   ->getOperand(0)->hasOneUse()) {
7648             Value *YS = // (Y << C)
7649               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7650             // X & (CC << C)
7651             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7652                                            V1->getName()+".mask");
7653             
7654             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7655           }
7656           
7657           break;
7658         }
7659       }
7660       
7661       
7662       // If the operand is an bitwise operator with a constant RHS, and the
7663       // shift is the only use, we can pull it out of the shift.
7664       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7665         bool isValid = true;     // Valid only for And, Or, Xor
7666         bool highBitSet = false; // Transform if high bit of constant set?
7667         
7668         switch (Op0BO->getOpcode()) {
7669           default: isValid = false; break;   // Do not perform transform!
7670           case Instruction::Add:
7671             isValid = isLeftShift;
7672             break;
7673           case Instruction::Or:
7674           case Instruction::Xor:
7675             highBitSet = false;
7676             break;
7677           case Instruction::And:
7678             highBitSet = true;
7679             break;
7680         }
7681         
7682         // If this is a signed shift right, and the high bit is modified
7683         // by the logical operation, do not perform the transformation.
7684         // The highBitSet boolean indicates the value of the high bit of
7685         // the constant which would cause it to be modified for this
7686         // operation.
7687         //
7688         if (isValid && I.getOpcode() == Instruction::AShr)
7689           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7690         
7691         if (isValid) {
7692           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7693           
7694           Value *NewShift =
7695             Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
7696           NewShift->takeName(Op0BO);
7697           
7698           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7699                                         NewRHS);
7700         }
7701       }
7702     }
7703   }
7704   
7705   // Find out if this is a shift of a shift by a constant.
7706   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7707   if (ShiftOp && !ShiftOp->isShift())
7708     ShiftOp = 0;
7709   
7710   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7711     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7712     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7713     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7714     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7715     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7716     Value *X = ShiftOp->getOperand(0);
7717     
7718     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7719     
7720     const IntegerType *Ty = cast<IntegerType>(I.getType());
7721     
7722     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7723     if (I.getOpcode() == ShiftOp->getOpcode()) {
7724       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7725       // saturates.
7726       if (AmtSum >= TypeBits) {
7727         if (I.getOpcode() != Instruction::AShr)
7728           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7729         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7730       }
7731       
7732       return BinaryOperator::Create(I.getOpcode(), X,
7733                                     ConstantInt::get(Ty, AmtSum));
7734     }
7735     
7736     if (ShiftOp->getOpcode() == Instruction::LShr &&
7737         I.getOpcode() == Instruction::AShr) {
7738       if (AmtSum >= TypeBits)
7739         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7740       
7741       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7742       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7743     }
7744     
7745     if (ShiftOp->getOpcode() == Instruction::AShr &&
7746         I.getOpcode() == Instruction::LShr) {
7747       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7748       if (AmtSum >= TypeBits)
7749         AmtSum = TypeBits-1;
7750       
7751       Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7752
7753       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7754       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7755     }
7756     
7757     // Okay, if we get here, one shift must be left, and the other shift must be
7758     // right.  See if the amounts are equal.
7759     if (ShiftAmt1 == ShiftAmt2) {
7760       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7761       if (I.getOpcode() == Instruction::Shl) {
7762         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7763         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7764       }
7765       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7766       if (I.getOpcode() == Instruction::LShr) {
7767         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7768         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7769       }
7770       // We can simplify ((X << C) >>s C) into a trunc + sext.
7771       // NOTE: we could do this for any C, but that would make 'unusual' integer
7772       // types.  For now, just stick to ones well-supported by the code
7773       // generators.
7774       const Type *SExtType = 0;
7775       switch (Ty->getBitWidth() - ShiftAmt1) {
7776       case 1  :
7777       case 8  :
7778       case 16 :
7779       case 32 :
7780       case 64 :
7781       case 128:
7782         SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
7783         break;
7784       default: break;
7785       }
7786       if (SExtType)
7787         return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
7788       // Otherwise, we can't handle it yet.
7789     } else if (ShiftAmt1 < ShiftAmt2) {
7790       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7791       
7792       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7793       if (I.getOpcode() == Instruction::Shl) {
7794         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7795                ShiftOp->getOpcode() == Instruction::AShr);
7796         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7797         
7798         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7799         return BinaryOperator::CreateAnd(Shift,
7800                                          ConstantInt::get(*Context, Mask));
7801       }
7802       
7803       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7804       if (I.getOpcode() == Instruction::LShr) {
7805         assert(ShiftOp->getOpcode() == Instruction::Shl);
7806         Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7807         
7808         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7809         return BinaryOperator::CreateAnd(Shift,
7810                                          ConstantInt::get(*Context, Mask));
7811       }
7812       
7813       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7814     } else {
7815       assert(ShiftAmt2 < ShiftAmt1);
7816       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7817
7818       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7819       if (I.getOpcode() == Instruction::Shl) {
7820         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7821                ShiftOp->getOpcode() == Instruction::AShr);
7822         Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7823                                             ConstantInt::get(Ty, ShiftDiff));
7824         
7825         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7826         return BinaryOperator::CreateAnd(Shift,
7827                                          ConstantInt::get(*Context, Mask));
7828       }
7829       
7830       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7831       if (I.getOpcode() == Instruction::LShr) {
7832         assert(ShiftOp->getOpcode() == Instruction::Shl);
7833         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7834         
7835         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7836         return BinaryOperator::CreateAnd(Shift,
7837                                          ConstantInt::get(*Context, Mask));
7838       }
7839       
7840       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7841     }
7842   }
7843   return 0;
7844 }
7845
7846
7847 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7848 /// expression.  If so, decompose it, returning some value X, such that Val is
7849 /// X*Scale+Offset.
7850 ///
7851 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7852                                         int &Offset, LLVMContext *Context) {
7853   assert(Val->getType() == Type::getInt32Ty(*Context) && 
7854          "Unexpected allocation size type!");
7855   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7856     Offset = CI->getZExtValue();
7857     Scale  = 0;
7858     return ConstantInt::get(Type::getInt32Ty(*Context), 0);
7859   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7860     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7861       if (I->getOpcode() == Instruction::Shl) {
7862         // This is a value scaled by '1 << the shift amt'.
7863         Scale = 1U << RHS->getZExtValue();
7864         Offset = 0;
7865         return I->getOperand(0);
7866       } else if (I->getOpcode() == Instruction::Mul) {
7867         // This value is scaled by 'RHS'.
7868         Scale = RHS->getZExtValue();
7869         Offset = 0;
7870         return I->getOperand(0);
7871       } else if (I->getOpcode() == Instruction::Add) {
7872         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7873         // where C1 is divisible by C2.
7874         unsigned SubScale;
7875         Value *SubVal = 
7876           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7877                                     Offset, Context);
7878         Offset += RHS->getZExtValue();
7879         Scale = SubScale;
7880         return SubVal;
7881       }
7882     }
7883   }
7884
7885   // Otherwise, we can't look past this.
7886   Scale = 1;
7887   Offset = 0;
7888   return Val;
7889 }
7890
7891
7892 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7893 /// try to eliminate the cast by moving the type information into the alloc.
7894 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7895                                                    AllocaInst &AI) {
7896   const PointerType *PTy = cast<PointerType>(CI.getType());
7897   
7898   BuilderTy AllocaBuilder(*Builder);
7899   AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7900   
7901   // Remove any uses of AI that are dead.
7902   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7903   
7904   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7905     Instruction *User = cast<Instruction>(*UI++);
7906     if (isInstructionTriviallyDead(User)) {
7907       while (UI != E && *UI == User)
7908         ++UI; // If this instruction uses AI more than once, don't break UI.
7909       
7910       ++NumDeadInst;
7911       DEBUG(errs() << "IC: DCE: " << *User << '\n');
7912       EraseInstFromFunction(*User);
7913     }
7914   }
7915
7916   // This requires TargetData to get the alloca alignment and size information.
7917   if (!TD) return 0;
7918
7919   // Get the type really allocated and the type casted to.
7920   const Type *AllocElTy = AI.getAllocatedType();
7921   const Type *CastElTy = PTy->getElementType();
7922   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7923
7924   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7925   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7926   if (CastElTyAlign < AllocElTyAlign) return 0;
7927
7928   // If the allocation has multiple uses, only promote it if we are strictly
7929   // increasing the alignment of the resultant allocation.  If we keep it the
7930   // same, we open the door to infinite loops of various kinds.  (A reference
7931   // from a dbg.declare doesn't count as a use for this purpose.)
7932   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7933       CastElTyAlign == AllocElTyAlign) return 0;
7934
7935   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7936   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7937   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7938
7939   // See if we can satisfy the modulus by pulling a scale out of the array
7940   // size argument.
7941   unsigned ArraySizeScale;
7942   int ArrayOffset;
7943   Value *NumElements = // See if the array size is a decomposable linear expr.
7944     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7945                               ArrayOffset, Context);
7946  
7947   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7948   // do the xform.
7949   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7950       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7951
7952   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7953   Value *Amt = 0;
7954   if (Scale == 1) {
7955     Amt = NumElements;
7956   } else {
7957     Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
7958     // Insert before the alloca, not before the cast.
7959     Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
7960   }
7961   
7962   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7963     Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
7964     Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
7965   }
7966   
7967   AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7968   New->setAlignment(AI.getAlignment());
7969   New->takeName(&AI);
7970   
7971   // If the allocation has one real use plus a dbg.declare, just remove the
7972   // declare.
7973   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7974     EraseInstFromFunction(*DI);
7975   }
7976   // If the allocation has multiple real uses, insert a cast and change all
7977   // things that used it to use the new cast.  This will also hack on CI, but it
7978   // will die soon.
7979   else if (!AI.hasOneUse()) {
7980     // New is the allocation instruction, pointer typed. AI is the original
7981     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7982     Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
7983     AI.replaceAllUsesWith(NewCast);
7984   }
7985   return ReplaceInstUsesWith(CI, New);
7986 }
7987
7988 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7989 /// and return it as type Ty without inserting any new casts and without
7990 /// changing the computed value.  This is used by code that tries to decide
7991 /// whether promoting or shrinking integer operations to wider or smaller types
7992 /// will allow us to eliminate a truncate or extend.
7993 ///
7994 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7995 /// extension operation if Ty is larger.
7996 ///
7997 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7998 /// should return true if trunc(V) can be computed by computing V in the smaller
7999 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
8000 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
8001 /// efficiently truncated.
8002 ///
8003 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
8004 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
8005 /// the final result.
8006 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
8007                                               unsigned CastOpc,
8008                                               int &NumCastsRemoved){
8009   // We can always evaluate constants in another type.
8010   if (isa<Constant>(V))
8011     return true;
8012   
8013   Instruction *I = dyn_cast<Instruction>(V);
8014   if (!I) return false;
8015   
8016   const Type *OrigTy = V->getType();
8017   
8018   // If this is an extension or truncate, we can often eliminate it.
8019   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
8020     // If this is a cast from the destination type, we can trivially eliminate
8021     // it, and this will remove a cast overall.
8022     if (I->getOperand(0)->getType() == Ty) {
8023       // If the first operand is itself a cast, and is eliminable, do not count
8024       // this as an eliminable cast.  We would prefer to eliminate those two
8025       // casts first.
8026       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
8027         ++NumCastsRemoved;
8028       return true;
8029     }
8030   }
8031
8032   // We can't extend or shrink something that has multiple uses: doing so would
8033   // require duplicating the instruction in general, which isn't profitable.
8034   if (!I->hasOneUse()) return false;
8035
8036   unsigned Opc = I->getOpcode();
8037   switch (Opc) {
8038   case Instruction::Add:
8039   case Instruction::Sub:
8040   case Instruction::Mul:
8041   case Instruction::And:
8042   case Instruction::Or:
8043   case Instruction::Xor:
8044     // These operators can all arbitrarily be extended or truncated.
8045     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8046                                       NumCastsRemoved) &&
8047            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8048                                       NumCastsRemoved);
8049
8050   case Instruction::UDiv:
8051   case Instruction::URem: {
8052     // UDiv and URem can be truncated if all the truncated bits are zero.
8053     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8054     uint32_t BitWidth = Ty->getScalarSizeInBits();
8055     if (BitWidth < OrigBitWidth) {
8056       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
8057       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
8058           MaskedValueIsZero(I->getOperand(1), Mask)) {
8059         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8060                                           NumCastsRemoved) &&
8061                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8062                                           NumCastsRemoved);
8063       }
8064     }
8065     break;
8066   }
8067   case Instruction::Shl:
8068     // If we are truncating the result of this SHL, and if it's a shift of a
8069     // constant amount, we can always perform a SHL in a smaller type.
8070     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8071       uint32_t BitWidth = Ty->getScalarSizeInBits();
8072       if (BitWidth < OrigTy->getScalarSizeInBits() &&
8073           CI->getLimitedValue(BitWidth) < BitWidth)
8074         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8075                                           NumCastsRemoved);
8076     }
8077     break;
8078   case Instruction::LShr:
8079     // If this is a truncate of a logical shr, we can truncate it to a smaller
8080     // lshr iff we know that the bits we would otherwise be shifting in are
8081     // already zeros.
8082     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8083       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8084       uint32_t BitWidth = Ty->getScalarSizeInBits();
8085       if (BitWidth < OrigBitWidth &&
8086           MaskedValueIsZero(I->getOperand(0),
8087             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8088           CI->getLimitedValue(BitWidth) < BitWidth) {
8089         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8090                                           NumCastsRemoved);
8091       }
8092     }
8093     break;
8094   case Instruction::ZExt:
8095   case Instruction::SExt:
8096   case Instruction::Trunc:
8097     // If this is the same kind of case as our original (e.g. zext+zext), we
8098     // can safely replace it.  Note that replacing it does not reduce the number
8099     // of casts in the input.
8100     if (Opc == CastOpc)
8101       return true;
8102
8103     // sext (zext ty1), ty2 -> zext ty2
8104     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8105       return true;
8106     break;
8107   case Instruction::Select: {
8108     SelectInst *SI = cast<SelectInst>(I);
8109     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8110                                       NumCastsRemoved) &&
8111            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8112                                       NumCastsRemoved);
8113   }
8114   case Instruction::PHI: {
8115     // We can change a phi if we can change all operands.
8116     PHINode *PN = cast<PHINode>(I);
8117     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8118       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8119                                       NumCastsRemoved))
8120         return false;
8121     return true;
8122   }
8123   default:
8124     // TODO: Can handle more cases here.
8125     break;
8126   }
8127   
8128   return false;
8129 }
8130
8131 /// EvaluateInDifferentType - Given an expression that 
8132 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8133 /// evaluate the expression.
8134 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
8135                                              bool isSigned) {
8136   if (Constant *C = dyn_cast<Constant>(V))
8137     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
8138
8139   // Otherwise, it must be an instruction.
8140   Instruction *I = cast<Instruction>(V);
8141   Instruction *Res = 0;
8142   unsigned Opc = I->getOpcode();
8143   switch (Opc) {
8144   case Instruction::Add:
8145   case Instruction::Sub:
8146   case Instruction::Mul:
8147   case Instruction::And:
8148   case Instruction::Or:
8149   case Instruction::Xor:
8150   case Instruction::AShr:
8151   case Instruction::LShr:
8152   case Instruction::Shl:
8153   case Instruction::UDiv:
8154   case Instruction::URem: {
8155     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8156     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8157     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8158     break;
8159   }    
8160   case Instruction::Trunc:
8161   case Instruction::ZExt:
8162   case Instruction::SExt:
8163     // If the source type of the cast is the type we're trying for then we can
8164     // just return the source.  There's no need to insert it because it is not
8165     // new.
8166     if (I->getOperand(0)->getType() == Ty)
8167       return I->getOperand(0);
8168     
8169     // Otherwise, must be the same type of cast, so just reinsert a new one.
8170     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
8171     break;
8172   case Instruction::Select: {
8173     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8174     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8175     Res = SelectInst::Create(I->getOperand(0), True, False);
8176     break;
8177   }
8178   case Instruction::PHI: {
8179     PHINode *OPN = cast<PHINode>(I);
8180     PHINode *NPN = PHINode::Create(Ty);
8181     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8182       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8183       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8184     }
8185     Res = NPN;
8186     break;
8187   }
8188   default: 
8189     // TODO: Can handle more cases here.
8190     llvm_unreachable("Unreachable!");
8191     break;
8192   }
8193   
8194   Res->takeName(I);
8195   return InsertNewInstBefore(Res, *I);
8196 }
8197
8198 /// @brief Implement the transforms common to all CastInst visitors.
8199 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8200   Value *Src = CI.getOperand(0);
8201
8202   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8203   // eliminate it now.
8204   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8205     if (Instruction::CastOps opc = 
8206         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8207       // The first cast (CSrc) is eliminable so we need to fix up or replace
8208       // the second cast (CI). CSrc will then have a good chance of being dead.
8209       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8210     }
8211   }
8212
8213   // If we are casting a select then fold the cast into the select
8214   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8215     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8216       return NV;
8217
8218   // If we are casting a PHI then fold the cast into the PHI
8219   if (isa<PHINode>(Src)) {
8220     // We don't do this if this would create a PHI node with an illegal type if
8221     // it is currently legal.
8222     if (!isa<IntegerType>(Src->getType()) ||
8223         !isa<IntegerType>(CI.getType()) ||
8224         ShouldChangeType(CI.getType(), Src->getType(), TD))
8225       if (Instruction *NV = FoldOpIntoPhi(CI))
8226         return NV;
8227   }
8228   
8229   return 0;
8230 }
8231
8232 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8233 /// or not there is a sequence of GEP indices into the type that will land us at
8234 /// the specified offset.  If so, fill them into NewIndices and return the
8235 /// resultant element type, otherwise return null.
8236 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8237                                        SmallVectorImpl<Value*> &NewIndices,
8238                                        const TargetData *TD,
8239                                        LLVMContext *Context) {
8240   if (!TD) return 0;
8241   if (!Ty->isSized()) return 0;
8242   
8243   // Start with the index over the outer type.  Note that the type size
8244   // might be zero (even if the offset isn't zero) if the indexed type
8245   // is something like [0 x {int, int}]
8246   const Type *IntPtrTy = TD->getIntPtrType(*Context);
8247   int64_t FirstIdx = 0;
8248   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8249     FirstIdx = Offset/TySize;
8250     Offset -= FirstIdx*TySize;
8251     
8252     // Handle hosts where % returns negative instead of values [0..TySize).
8253     if (Offset < 0) {
8254       --FirstIdx;
8255       Offset += TySize;
8256       assert(Offset >= 0);
8257     }
8258     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8259   }
8260   
8261   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8262     
8263   // Index into the types.  If we fail, set OrigBase to null.
8264   while (Offset) {
8265     // Indexing into tail padding between struct/array elements.
8266     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8267       return 0;
8268     
8269     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8270       const StructLayout *SL = TD->getStructLayout(STy);
8271       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8272              "Offset must stay within the indexed type");
8273       
8274       unsigned Elt = SL->getElementContainingOffset(Offset);
8275       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8276       
8277       Offset -= SL->getElementOffset(Elt);
8278       Ty = STy->getElementType(Elt);
8279     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8280       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8281       assert(EltSize && "Cannot index into a zero-sized array");
8282       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8283       Offset %= EltSize;
8284       Ty = AT->getElementType();
8285     } else {
8286       // Otherwise, we can't index into the middle of this atomic type, bail.
8287       return 0;
8288     }
8289   }
8290   
8291   return Ty;
8292 }
8293
8294 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8295 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8296   Value *Src = CI.getOperand(0);
8297   
8298   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8299     // If casting the result of a getelementptr instruction with no offset, turn
8300     // this into a cast of the original pointer!
8301     if (GEP->hasAllZeroIndices()) {
8302       // Changing the cast operand is usually not a good idea but it is safe
8303       // here because the pointer operand is being replaced with another 
8304       // pointer operand so the opcode doesn't need to change.
8305       Worklist.Add(GEP);
8306       CI.setOperand(0, GEP->getOperand(0));
8307       return &CI;
8308     }
8309     
8310     // If the GEP has a single use, and the base pointer is a bitcast, and the
8311     // GEP computes a constant offset, see if we can convert these three
8312     // instructions into fewer.  This typically happens with unions and other
8313     // non-type-safe code.
8314     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8315       if (GEP->hasAllConstantIndices()) {
8316         // We are guaranteed to get a constant from EmitGEPOffset.
8317         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, *this));
8318         int64_t Offset = OffsetV->getSExtValue();
8319         
8320         // Get the base pointer input of the bitcast, and the type it points to.
8321         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8322         const Type *GEPIdxTy =
8323           cast<PointerType>(OrigBase->getType())->getElementType();
8324         SmallVector<Value*, 8> NewIndices;
8325         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8326           // If we were able to index down into an element, create the GEP
8327           // and bitcast the result.  This eliminates one bitcast, potentially
8328           // two.
8329           Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8330             Builder->CreateInBoundsGEP(OrigBase,
8331                                        NewIndices.begin(), NewIndices.end()) :
8332             Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
8333           NGEP->takeName(GEP);
8334           
8335           if (isa<BitCastInst>(CI))
8336             return new BitCastInst(NGEP, CI.getType());
8337           assert(isa<PtrToIntInst>(CI));
8338           return new PtrToIntInst(NGEP, CI.getType());
8339         }
8340       }      
8341     }
8342   }
8343     
8344   return commonCastTransforms(CI);
8345 }
8346
8347 /// commonIntCastTransforms - This function implements the common transforms
8348 /// for trunc, zext, and sext.
8349 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8350   if (Instruction *Result = commonCastTransforms(CI))
8351     return Result;
8352
8353   Value *Src = CI.getOperand(0);
8354   const Type *SrcTy = Src->getType();
8355   const Type *DestTy = CI.getType();
8356   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8357   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8358
8359   // See if we can simplify any instructions used by the LHS whose sole 
8360   // purpose is to compute bits we don't care about.
8361   if (SimplifyDemandedInstructionBits(CI))
8362     return &CI;
8363
8364   // If the source isn't an instruction or has more than one use then we
8365   // can't do anything more. 
8366   Instruction *SrcI = dyn_cast<Instruction>(Src);
8367   if (!SrcI || !Src->hasOneUse())
8368     return 0;
8369
8370   // Attempt to propagate the cast into the instruction for int->int casts.
8371   int NumCastsRemoved = 0;
8372   // Only do this if the dest type is a simple type, don't convert the
8373   // expression tree to something weird like i93 unless the source is also
8374   // strange.
8375   if ((isa<VectorType>(DestTy) ||
8376        ShouldChangeType(SrcI->getType(), DestTy, TD)) &&
8377       CanEvaluateInDifferentType(SrcI, DestTy,
8378                                  CI.getOpcode(), NumCastsRemoved)) {
8379     // If this cast is a truncate, evaluting in a different type always
8380     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8381     // we need to do an AND to maintain the clear top-part of the computation,
8382     // so we require that the input have eliminated at least one cast.  If this
8383     // is a sign extension, we insert two new casts (to do the extension) so we
8384     // require that two casts have been eliminated.
8385     bool DoXForm = false;
8386     bool JustReplace = false;
8387     switch (CI.getOpcode()) {
8388     default:
8389       // All the others use floating point so we shouldn't actually 
8390       // get here because of the check above.
8391       llvm_unreachable("Unknown cast type");
8392     case Instruction::Trunc:
8393       DoXForm = true;
8394       break;
8395     case Instruction::ZExt: {
8396       DoXForm = NumCastsRemoved >= 1;
8397       
8398       if (!DoXForm && 0) {
8399         // If it's unnecessary to issue an AND to clear the high bits, it's
8400         // always profitable to do this xform.
8401         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8402         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8403         if (MaskedValueIsZero(TryRes, Mask))
8404           return ReplaceInstUsesWith(CI, TryRes);
8405         
8406         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8407           if (TryI->use_empty())
8408             EraseInstFromFunction(*TryI);
8409       }
8410       break;
8411     }
8412     case Instruction::SExt: {
8413       DoXForm = NumCastsRemoved >= 2;
8414       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8415         // If we do not have to emit the truncate + sext pair, then it's always
8416         // profitable to do this xform.
8417         //
8418         // It's not safe to eliminate the trunc + sext pair if one of the
8419         // eliminated cast is a truncate. e.g.
8420         // t2 = trunc i32 t1 to i16
8421         // t3 = sext i16 t2 to i32
8422         // !=
8423         // i32 t1
8424         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8425         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8426         if (NumSignBits > (DestBitSize - SrcBitSize))
8427           return ReplaceInstUsesWith(CI, TryRes);
8428         
8429         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8430           if (TryI->use_empty())
8431             EraseInstFromFunction(*TryI);
8432       }
8433       break;
8434     }
8435     }
8436     
8437     if (DoXForm) {
8438       DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8439             " to avoid cast: " << CI);
8440       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8441                                            CI.getOpcode() == Instruction::SExt);
8442       if (JustReplace)
8443         // Just replace this cast with the result.
8444         return ReplaceInstUsesWith(CI, Res);
8445
8446       assert(Res->getType() == DestTy);
8447       switch (CI.getOpcode()) {
8448       default: llvm_unreachable("Unknown cast type!");
8449       case Instruction::Trunc:
8450         // Just replace this cast with the result.
8451         return ReplaceInstUsesWith(CI, Res);
8452       case Instruction::ZExt: {
8453         assert(SrcBitSize < DestBitSize && "Not a zext?");
8454
8455         // If the high bits are already zero, just replace this cast with the
8456         // result.
8457         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8458         if (MaskedValueIsZero(Res, Mask))
8459           return ReplaceInstUsesWith(CI, Res);
8460
8461         // We need to emit an AND to clear the high bits.
8462         Constant *C = ConstantInt::get(*Context, 
8463                                  APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8464         return BinaryOperator::CreateAnd(Res, C);
8465       }
8466       case Instruction::SExt: {
8467         // If the high bits are already filled with sign bit, just replace this
8468         // cast with the result.
8469         unsigned NumSignBits = ComputeNumSignBits(Res);
8470         if (NumSignBits > (DestBitSize - SrcBitSize))
8471           return ReplaceInstUsesWith(CI, Res);
8472
8473         // We need to emit a cast to truncate, then a cast to sext.
8474         return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
8475       }
8476       }
8477     }
8478   }
8479   
8480   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8481   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8482
8483   switch (SrcI->getOpcode()) {
8484   case Instruction::Add:
8485   case Instruction::Mul:
8486   case Instruction::And:
8487   case Instruction::Or:
8488   case Instruction::Xor:
8489     // If we are discarding information, rewrite.
8490     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8491       // Don't insert two casts unless at least one can be eliminated.
8492       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8493           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8494         Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8495         Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8496         return BinaryOperator::Create(
8497             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8498       }
8499     }
8500
8501     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8502     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8503         SrcI->getOpcode() == Instruction::Xor &&
8504         Op1 == ConstantInt::getTrue(*Context) &&
8505         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8506       Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
8507       return BinaryOperator::CreateXor(New,
8508                                       ConstantInt::get(CI.getType(), 1));
8509     }
8510     break;
8511
8512   case Instruction::Shl: {
8513     // Canonicalize trunc inside shl, if we can.
8514     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8515     if (CI && DestBitSize < SrcBitSize &&
8516         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8517       Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8518       Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8519       return BinaryOperator::CreateShl(Op0c, Op1c);
8520     }
8521     break;
8522   }
8523   }
8524   return 0;
8525 }
8526
8527 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8528   if (Instruction *Result = commonIntCastTransforms(CI))
8529     return Result;
8530   
8531   Value *Src = CI.getOperand(0);
8532   const Type *Ty = CI.getType();
8533   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8534   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8535
8536   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8537   if (DestBitWidth == 1) {
8538     Constant *One = ConstantInt::get(Src->getType(), 1);
8539     Src = Builder->CreateAnd(Src, One, "tmp");
8540     Value *Zero = Constant::getNullValue(Src->getType());
8541     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8542   }
8543
8544   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8545   ConstantInt *ShAmtV = 0;
8546   Value *ShiftOp = 0;
8547   if (Src->hasOneUse() &&
8548       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8549     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8550     
8551     // Get a mask for the bits shifting in.
8552     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8553     if (MaskedValueIsZero(ShiftOp, Mask)) {
8554       if (ShAmt >= DestBitWidth)        // All zeros.
8555         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8556       
8557       // Okay, we can shrink this.  Truncate the input, then return a new
8558       // shift.
8559       Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
8560       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8561       return BinaryOperator::CreateLShr(V1, V2);
8562     }
8563   }
8564  
8565   return 0;
8566 }
8567
8568 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8569 /// in order to eliminate the icmp.
8570 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8571                                              bool DoXform) {
8572   // If we are just checking for a icmp eq of a single bit and zext'ing it
8573   // to an integer, then shift the bit to the appropriate place and then
8574   // cast to integer to avoid the comparison.
8575   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8576     const APInt &Op1CV = Op1C->getValue();
8577       
8578     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8579     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8580     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8581         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8582       if (!DoXform) return ICI;
8583
8584       Value *In = ICI->getOperand(0);
8585       Value *Sh = ConstantInt::get(In->getType(),
8586                                    In->getType()->getScalarSizeInBits()-1);
8587       In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
8588       if (In->getType() != CI.getType())
8589         In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
8590
8591       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8592         Constant *One = ConstantInt::get(In->getType(), 1);
8593         In = Builder->CreateXor(In, One, In->getName()+".not");
8594       }
8595
8596       return ReplaceInstUsesWith(CI, In);
8597     }
8598       
8599       
8600       
8601     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8602     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8603     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8604     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8605     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8606     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8607     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8608     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8609     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8610         // This only works for EQ and NE
8611         ICI->isEquality()) {
8612       // If Op1C some other power of two, convert:
8613       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8614       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8615       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8616       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8617         
8618       APInt KnownZeroMask(~KnownZero);
8619       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8620         if (!DoXform) return ICI;
8621
8622         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8623         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8624           // (X&4) == 2 --> false
8625           // (X&4) != 2 --> true
8626           Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8627           Res = ConstantExpr::getZExt(Res, CI.getType());
8628           return ReplaceInstUsesWith(CI, Res);
8629         }
8630           
8631         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8632         Value *In = ICI->getOperand(0);
8633         if (ShiftAmt) {
8634           // Perform a logical shr by shiftamt.
8635           // Insert the shift to put the result in the low bit.
8636           In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8637                                    In->getName()+".lobit");
8638         }
8639           
8640         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8641           Constant *One = ConstantInt::get(In->getType(), 1);
8642           In = Builder->CreateXor(In, One, "tmp");
8643         }
8644           
8645         if (CI.getType() == In->getType())
8646           return ReplaceInstUsesWith(CI, In);
8647         else
8648           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8649       }
8650     }
8651   }
8652
8653   // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
8654   // It is also profitable to transform icmp eq into not(xor(A, B)) because that
8655   // may lead to additional simplifications.
8656   if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
8657     if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
8658       uint32_t BitWidth = ITy->getBitWidth();
8659       Value *LHS = ICI->getOperand(0);
8660       Value *RHS = ICI->getOperand(1);
8661
8662       APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
8663       APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
8664       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8665       ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
8666       ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
8667
8668       if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
8669         APInt KnownBits = KnownZeroLHS | KnownOneLHS;
8670         APInt UnknownBit = ~KnownBits;
8671         if (UnknownBit.countPopulation() == 1) {
8672           if (!DoXform) return ICI;
8673
8674           Value *Result = Builder->CreateXor(LHS, RHS);
8675
8676           // Mask off any bits that are set and won't be shifted away.
8677           if (KnownOneLHS.uge(UnknownBit))
8678             Result = Builder->CreateAnd(Result,
8679                                         ConstantInt::get(ITy, UnknownBit));
8680
8681           // Shift the bit we're testing down to the lsb.
8682           Result = Builder->CreateLShr(
8683                Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
8684
8685           if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8686             Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
8687           Result->takeName(ICI);
8688           return ReplaceInstUsesWith(CI, Result);
8689         }
8690       }
8691     }
8692   }
8693
8694   return 0;
8695 }
8696
8697 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8698   // If one of the common conversion will work ..
8699   if (Instruction *Result = commonIntCastTransforms(CI))
8700     return Result;
8701
8702   Value *Src = CI.getOperand(0);
8703
8704   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8705   // types and if the sizes are just right we can convert this into a logical
8706   // 'and' which will be much cheaper than the pair of casts.
8707   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8708     // Get the sizes of the types involved.  We know that the intermediate type
8709     // will be smaller than A or C, but don't know the relation between A and C.
8710     Value *A = CSrc->getOperand(0);
8711     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8712     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8713     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8714     // If we're actually extending zero bits, then if
8715     // SrcSize <  DstSize: zext(a & mask)
8716     // SrcSize == DstSize: a & mask
8717     // SrcSize  > DstSize: trunc(a) & mask
8718     if (SrcSize < DstSize) {
8719       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8720       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8721       Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
8722       return new ZExtInst(And, CI.getType());
8723     }
8724     
8725     if (SrcSize == DstSize) {
8726       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8727       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8728                                                            AndValue));
8729     }
8730     if (SrcSize > DstSize) {
8731       Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
8732       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8733       return BinaryOperator::CreateAnd(Trunc, 
8734                                        ConstantInt::get(Trunc->getType(),
8735                                                                AndValue));
8736     }
8737   }
8738
8739   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8740     return transformZExtICmp(ICI, CI);
8741
8742   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8743   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8744     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8745     // of the (zext icmp) will be transformed.
8746     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8747     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8748     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8749         (transformZExtICmp(LHS, CI, false) ||
8750          transformZExtICmp(RHS, CI, false))) {
8751       Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8752       Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
8753       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8754     }
8755   }
8756
8757   // zext(trunc(t) & C) -> (t & zext(C)).
8758   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8759     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8760       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8761         Value *TI0 = TI->getOperand(0);
8762         if (TI0->getType() == CI.getType())
8763           return
8764             BinaryOperator::CreateAnd(TI0,
8765                                 ConstantExpr::getZExt(C, CI.getType()));
8766       }
8767
8768   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8769   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8770     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8771       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8772         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8773             And->getOperand(1) == C)
8774           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8775             Value *TI0 = TI->getOperand(0);
8776             if (TI0->getType() == CI.getType()) {
8777               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8778               Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
8779               return BinaryOperator::CreateXor(NewAnd, ZC);
8780             }
8781           }
8782
8783   return 0;
8784 }
8785
8786 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8787   if (Instruction *I = commonIntCastTransforms(CI))
8788     return I;
8789   
8790   Value *Src = CI.getOperand(0);
8791   
8792   // Canonicalize sign-extend from i1 to a select.
8793   if (Src->getType() == Type::getInt1Ty(*Context))
8794     return SelectInst::Create(Src,
8795                               Constant::getAllOnesValue(CI.getType()),
8796                               Constant::getNullValue(CI.getType()));
8797
8798   // See if the value being truncated is already sign extended.  If so, just
8799   // eliminate the trunc/sext pair.
8800   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8801     Value *Op = cast<User>(Src)->getOperand(0);
8802     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8803     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8804     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8805     unsigned NumSignBits = ComputeNumSignBits(Op);
8806
8807     if (OpBits == DestBits) {
8808       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8809       // bits, it is already ready.
8810       if (NumSignBits > DestBits-MidBits)
8811         return ReplaceInstUsesWith(CI, Op);
8812     } else if (OpBits < DestBits) {
8813       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8814       // bits, just sext from i32.
8815       if (NumSignBits > OpBits-MidBits)
8816         return new SExtInst(Op, CI.getType(), "tmp");
8817     } else {
8818       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8819       // bits, just truncate to i32.
8820       if (NumSignBits > OpBits-MidBits)
8821         return new TruncInst(Op, CI.getType(), "tmp");
8822     }
8823   }
8824
8825   // If the input is a shl/ashr pair of a same constant, then this is a sign
8826   // extension from a smaller value.  If we could trust arbitrary bitwidth
8827   // integers, we could turn this into a truncate to the smaller bit and then
8828   // use a sext for the whole extension.  Since we don't, look deeper and check
8829   // for a truncate.  If the source and dest are the same type, eliminate the
8830   // trunc and extend and just do shifts.  For example, turn:
8831   //   %a = trunc i32 %i to i8
8832   //   %b = shl i8 %a, 6
8833   //   %c = ashr i8 %b, 6
8834   //   %d = sext i8 %c to i32
8835   // into:
8836   //   %a = shl i32 %i, 30
8837   //   %d = ashr i32 %a, 30
8838   Value *A = 0;
8839   ConstantInt *BA = 0, *CA = 0;
8840   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8841                         m_ConstantInt(CA))) &&
8842       BA == CA && isa<TruncInst>(A)) {
8843     Value *I = cast<TruncInst>(A)->getOperand(0);
8844     if (I->getType() == CI.getType()) {
8845       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8846       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8847       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8848       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8849       I = Builder->CreateShl(I, ShAmtV, CI.getName());
8850       return BinaryOperator::CreateAShr(I, ShAmtV);
8851     }
8852   }
8853   
8854   return 0;
8855 }
8856
8857 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8858 /// in the specified FP type without changing its value.
8859 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8860                               LLVMContext *Context) {
8861   bool losesInfo;
8862   APFloat F = CFP->getValueAPF();
8863   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8864   if (!losesInfo)
8865     return ConstantFP::get(*Context, F);
8866   return 0;
8867 }
8868
8869 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8870 /// through it until we get the source value.
8871 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8872   if (Instruction *I = dyn_cast<Instruction>(V))
8873     if (I->getOpcode() == Instruction::FPExt)
8874       return LookThroughFPExtensions(I->getOperand(0), Context);
8875   
8876   // If this value is a constant, return the constant in the smallest FP type
8877   // that can accurately represent it.  This allows us to turn
8878   // (float)((double)X+2.0) into x+2.0f.
8879   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8880     if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
8881       return V;  // No constant folding of this.
8882     // See if the value can be truncated to float and then reextended.
8883     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8884       return V;
8885     if (CFP->getType() == Type::getDoubleTy(*Context))
8886       return V;  // Won't shrink.
8887     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8888       return V;
8889     // Don't try to shrink to various long double types.
8890   }
8891   
8892   return V;
8893 }
8894
8895 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8896   if (Instruction *I = commonCastTransforms(CI))
8897     return I;
8898   
8899   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8900   // smaller than the destination type, we can eliminate the truncate by doing
8901   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8902   // many builtins (sqrt, etc).
8903   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8904   if (OpI && OpI->hasOneUse()) {
8905     switch (OpI->getOpcode()) {
8906     default: break;
8907     case Instruction::FAdd:
8908     case Instruction::FSub:
8909     case Instruction::FMul:
8910     case Instruction::FDiv:
8911     case Instruction::FRem:
8912       const Type *SrcTy = OpI->getType();
8913       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8914       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8915       if (LHSTrunc->getType() != SrcTy && 
8916           RHSTrunc->getType() != SrcTy) {
8917         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8918         // If the source types were both smaller than the destination type of
8919         // the cast, do this xform.
8920         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8921             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8922           LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8923           RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
8924           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8925         }
8926       }
8927       break;  
8928     }
8929   }
8930   return 0;
8931 }
8932
8933 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8934   return commonCastTransforms(CI);
8935 }
8936
8937 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8938   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8939   if (OpI == 0)
8940     return commonCastTransforms(FI);
8941
8942   // fptoui(uitofp(X)) --> X
8943   // fptoui(sitofp(X)) --> X
8944   // This is safe if the intermediate type has enough bits in its mantissa to
8945   // accurately represent all values of X.  For example, do not do this with
8946   // i64->float->i64.  This is also safe for sitofp case, because any negative
8947   // 'X' value would cause an undefined result for the fptoui. 
8948   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8949       OpI->getOperand(0)->getType() == FI.getType() &&
8950       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8951                     OpI->getType()->getFPMantissaWidth())
8952     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8953
8954   return commonCastTransforms(FI);
8955 }
8956
8957 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8958   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8959   if (OpI == 0)
8960     return commonCastTransforms(FI);
8961   
8962   // fptosi(sitofp(X)) --> X
8963   // fptosi(uitofp(X)) --> X
8964   // This is safe if the intermediate type has enough bits in its mantissa to
8965   // accurately represent all values of X.  For example, do not do this with
8966   // i64->float->i64.  This is also safe for sitofp case, because any negative
8967   // 'X' value would cause an undefined result for the fptoui. 
8968   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8969       OpI->getOperand(0)->getType() == FI.getType() &&
8970       (int)FI.getType()->getScalarSizeInBits() <=
8971                     OpI->getType()->getFPMantissaWidth())
8972     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8973   
8974   return commonCastTransforms(FI);
8975 }
8976
8977 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8978   return commonCastTransforms(CI);
8979 }
8980
8981 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8982   return commonCastTransforms(CI);
8983 }
8984
8985 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8986   // If the destination integer type is smaller than the intptr_t type for
8987   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8988   // trunc to be exposed to other transforms.  Don't do this for extending
8989   // ptrtoint's, because we don't know if the target sign or zero extends its
8990   // pointers.
8991   if (TD &&
8992       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8993     Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8994                                        TD->getIntPtrType(CI.getContext()),
8995                                        "tmp");
8996     return new TruncInst(P, CI.getType());
8997   }
8998   
8999   return commonPointerCastTransforms(CI);
9000 }
9001
9002 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
9003   // If the source integer type is larger than the intptr_t type for
9004   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
9005   // allows the trunc to be exposed to other transforms.  Don't do this for
9006   // extending inttoptr's, because we don't know if the target sign or zero
9007   // extends to pointers.
9008   if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
9009       TD->getPointerSizeInBits()) {
9010     Value *P = Builder->CreateTrunc(CI.getOperand(0),
9011                                     TD->getIntPtrType(CI.getContext()), "tmp");
9012     return new IntToPtrInst(P, CI.getType());
9013   }
9014   
9015   if (Instruction *I = commonCastTransforms(CI))
9016     return I;
9017
9018   return 0;
9019 }
9020
9021 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
9022   // If the operands are integer typed then apply the integer transforms,
9023   // otherwise just apply the common ones.
9024   Value *Src = CI.getOperand(0);
9025   const Type *SrcTy = Src->getType();
9026   const Type *DestTy = CI.getType();
9027
9028   if (isa<PointerType>(SrcTy)) {
9029     if (Instruction *I = commonPointerCastTransforms(CI))
9030       return I;
9031   } else {
9032     if (Instruction *Result = commonCastTransforms(CI))
9033       return Result;
9034   }
9035
9036
9037   // Get rid of casts from one type to the same type. These are useless and can
9038   // be replaced by the operand.
9039   if (DestTy == Src->getType())
9040     return ReplaceInstUsesWith(CI, Src);
9041
9042   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
9043     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
9044     const Type *DstElTy = DstPTy->getElementType();
9045     const Type *SrcElTy = SrcPTy->getElementType();
9046     
9047     // If the address spaces don't match, don't eliminate the bitcast, which is
9048     // required for changing types.
9049     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9050       return 0;
9051     
9052     // If we are casting a alloca to a pointer to a type of the same
9053     // size, rewrite the allocation instruction to allocate the "right" type.
9054     // There is no need to modify malloc calls because it is their bitcast that
9055     // needs to be cleaned up.
9056     if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
9057       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9058         return V;
9059     
9060     // If the source and destination are pointers, and this cast is equivalent
9061     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
9062     // This can enhance SROA and other transforms that want type-safe pointers.
9063     Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
9064     unsigned NumZeros = 0;
9065     while (SrcElTy != DstElTy && 
9066            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9067            SrcElTy->getNumContainedTypes() /* not "{}" */) {
9068       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9069       ++NumZeros;
9070     }
9071
9072     // If we found a path from the src to dest, create the getelementptr now.
9073     if (SrcElTy == DstElTy) {
9074       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
9075       return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
9076                                                ((Instruction*) NULL));
9077     }
9078   }
9079
9080   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9081     if (DestVTy->getNumElements() == 1) {
9082       if (!isa<VectorType>(SrcTy)) {
9083         Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
9084         return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
9085                             Constant::getNullValue(Type::getInt32Ty(*Context)));
9086       }
9087       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9088     }
9089   }
9090
9091   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9092     if (SrcVTy->getNumElements() == 1) {
9093       if (!isa<VectorType>(DestTy)) {
9094         Value *Elem = 
9095           Builder->CreateExtractElement(Src,
9096                             Constant::getNullValue(Type::getInt32Ty(*Context)));
9097         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9098       }
9099     }
9100   }
9101
9102   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9103     if (SVI->hasOneUse()) {
9104       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
9105       // a bitconvert to a vector with the same # elts.
9106       if (isa<VectorType>(DestTy) && 
9107           cast<VectorType>(DestTy)->getNumElements() ==
9108                 SVI->getType()->getNumElements() &&
9109           SVI->getType()->getNumElements() ==
9110             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9111         CastInst *Tmp;
9112         // If either of the operands is a cast from CI.getType(), then
9113         // evaluating the shuffle in the casted destination's type will allow
9114         // us to eliminate at least one cast.
9115         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
9116              Tmp->getOperand(0)->getType() == DestTy) ||
9117             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
9118              Tmp->getOperand(0)->getType() == DestTy)) {
9119           Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
9120           Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
9121           // Return a new shuffle vector.  Use the same element ID's, as we
9122           // know the vector types match #elts.
9123           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9124         }
9125       }
9126     }
9127   }
9128   return 0;
9129 }
9130
9131 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9132 ///   %C = or %A, %B
9133 ///   %D = select %cond, %C, %A
9134 /// into:
9135 ///   %C = select %cond, %B, 0
9136 ///   %D = or %A, %C
9137 ///
9138 /// Assuming that the specified instruction is an operand to the select, return
9139 /// a bitmask indicating which operands of this instruction are foldable if they
9140 /// equal the other incoming value of the select.
9141 ///
9142 static unsigned GetSelectFoldableOperands(Instruction *I) {
9143   switch (I->getOpcode()) {
9144   case Instruction::Add:
9145   case Instruction::Mul:
9146   case Instruction::And:
9147   case Instruction::Or:
9148   case Instruction::Xor:
9149     return 3;              // Can fold through either operand.
9150   case Instruction::Sub:   // Can only fold on the amount subtracted.
9151   case Instruction::Shl:   // Can only fold on the shift amount.
9152   case Instruction::LShr:
9153   case Instruction::AShr:
9154     return 1;
9155   default:
9156     return 0;              // Cannot fold
9157   }
9158 }
9159
9160 /// GetSelectFoldableConstant - For the same transformation as the previous
9161 /// function, return the identity constant that goes into the select.
9162 static Constant *GetSelectFoldableConstant(Instruction *I,
9163                                            LLVMContext *Context) {
9164   switch (I->getOpcode()) {
9165   default: llvm_unreachable("This cannot happen!");
9166   case Instruction::Add:
9167   case Instruction::Sub:
9168   case Instruction::Or:
9169   case Instruction::Xor:
9170   case Instruction::Shl:
9171   case Instruction::LShr:
9172   case Instruction::AShr:
9173     return Constant::getNullValue(I->getType());
9174   case Instruction::And:
9175     return Constant::getAllOnesValue(I->getType());
9176   case Instruction::Mul:
9177     return ConstantInt::get(I->getType(), 1);
9178   }
9179 }
9180
9181 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9182 /// have the same opcode and only one use each.  Try to simplify this.
9183 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9184                                           Instruction *FI) {
9185   if (TI->getNumOperands() == 1) {
9186     // If this is a non-volatile load or a cast from the same type,
9187     // merge.
9188     if (TI->isCast()) {
9189       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9190         return 0;
9191     } else {
9192       return 0;  // unknown unary op.
9193     }
9194
9195     // Fold this by inserting a select from the input values.
9196     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9197                                           FI->getOperand(0), SI.getName()+".v");
9198     InsertNewInstBefore(NewSI, SI);
9199     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9200                             TI->getType());
9201   }
9202
9203   // Only handle binary operators here.
9204   if (!isa<BinaryOperator>(TI))
9205     return 0;
9206
9207   // Figure out if the operations have any operands in common.
9208   Value *MatchOp, *OtherOpT, *OtherOpF;
9209   bool MatchIsOpZero;
9210   if (TI->getOperand(0) == FI->getOperand(0)) {
9211     MatchOp  = TI->getOperand(0);
9212     OtherOpT = TI->getOperand(1);
9213     OtherOpF = FI->getOperand(1);
9214     MatchIsOpZero = true;
9215   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9216     MatchOp  = TI->getOperand(1);
9217     OtherOpT = TI->getOperand(0);
9218     OtherOpF = FI->getOperand(0);
9219     MatchIsOpZero = false;
9220   } else if (!TI->isCommutative()) {
9221     return 0;
9222   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9223     MatchOp  = TI->getOperand(0);
9224     OtherOpT = TI->getOperand(1);
9225     OtherOpF = FI->getOperand(0);
9226     MatchIsOpZero = true;
9227   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9228     MatchOp  = TI->getOperand(1);
9229     OtherOpT = TI->getOperand(0);
9230     OtherOpF = FI->getOperand(1);
9231     MatchIsOpZero = true;
9232   } else {
9233     return 0;
9234   }
9235
9236   // If we reach here, they do have operations in common.
9237   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9238                                          OtherOpF, SI.getName()+".v");
9239   InsertNewInstBefore(NewSI, SI);
9240
9241   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9242     if (MatchIsOpZero)
9243       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9244     else
9245       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9246   }
9247   llvm_unreachable("Shouldn't get here");
9248   return 0;
9249 }
9250
9251 static bool isSelect01(Constant *C1, Constant *C2) {
9252   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9253   if (!C1I)
9254     return false;
9255   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9256   if (!C2I)
9257     return false;
9258   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9259 }
9260
9261 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9262 /// facilitate further optimization.
9263 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9264                                             Value *FalseVal) {
9265   // See the comment above GetSelectFoldableOperands for a description of the
9266   // transformation we are doing here.
9267   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9268     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9269         !isa<Constant>(FalseVal)) {
9270       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9271         unsigned OpToFold = 0;
9272         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9273           OpToFold = 1;
9274         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9275           OpToFold = 2;
9276         }
9277
9278         if (OpToFold) {
9279           Constant *C = GetSelectFoldableConstant(TVI, Context);
9280           Value *OOp = TVI->getOperand(2-OpToFold);
9281           // Avoid creating select between 2 constants unless it's selecting
9282           // between 0 and 1.
9283           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9284             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9285             InsertNewInstBefore(NewSel, SI);
9286             NewSel->takeName(TVI);
9287             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9288               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9289             llvm_unreachable("Unknown instruction!!");
9290           }
9291         }
9292       }
9293     }
9294   }
9295
9296   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9297     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9298         !isa<Constant>(TrueVal)) {
9299       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9300         unsigned OpToFold = 0;
9301         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9302           OpToFold = 1;
9303         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9304           OpToFold = 2;
9305         }
9306
9307         if (OpToFold) {
9308           Constant *C = GetSelectFoldableConstant(FVI, Context);
9309           Value *OOp = FVI->getOperand(2-OpToFold);
9310           // Avoid creating select between 2 constants unless it's selecting
9311           // between 0 and 1.
9312           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9313             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9314             InsertNewInstBefore(NewSel, SI);
9315             NewSel->takeName(FVI);
9316             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9317               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9318             llvm_unreachable("Unknown instruction!!");
9319           }
9320         }
9321       }
9322     }
9323   }
9324
9325   return 0;
9326 }
9327
9328 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9329 /// ICmpInst as its first operand.
9330 ///
9331 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9332                                                    ICmpInst *ICI) {
9333   bool Changed = false;
9334   ICmpInst::Predicate Pred = ICI->getPredicate();
9335   Value *CmpLHS = ICI->getOperand(0);
9336   Value *CmpRHS = ICI->getOperand(1);
9337   Value *TrueVal = SI.getTrueValue();
9338   Value *FalseVal = SI.getFalseValue();
9339
9340   // Check cases where the comparison is with a constant that
9341   // can be adjusted to fit the min/max idiom. We may edit ICI in
9342   // place here, so make sure the select is the only user.
9343   if (ICI->hasOneUse())
9344     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9345       switch (Pred) {
9346       default: break;
9347       case ICmpInst::ICMP_ULT:
9348       case ICmpInst::ICMP_SLT: {
9349         // X < MIN ? T : F  -->  F
9350         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9351           return ReplaceInstUsesWith(SI, FalseVal);
9352         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9353         Constant *AdjustedRHS = SubOne(CI);
9354         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9355             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9356           Pred = ICmpInst::getSwappedPredicate(Pred);
9357           CmpRHS = AdjustedRHS;
9358           std::swap(FalseVal, TrueVal);
9359           ICI->setPredicate(Pred);
9360           ICI->setOperand(1, CmpRHS);
9361           SI.setOperand(1, TrueVal);
9362           SI.setOperand(2, FalseVal);
9363           Changed = true;
9364         }
9365         break;
9366       }
9367       case ICmpInst::ICMP_UGT:
9368       case ICmpInst::ICMP_SGT: {
9369         // X > MAX ? T : F  -->  F
9370         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9371           return ReplaceInstUsesWith(SI, FalseVal);
9372         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9373         Constant *AdjustedRHS = AddOne(CI);
9374         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9375             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9376           Pred = ICmpInst::getSwappedPredicate(Pred);
9377           CmpRHS = AdjustedRHS;
9378           std::swap(FalseVal, TrueVal);
9379           ICI->setPredicate(Pred);
9380           ICI->setOperand(1, CmpRHS);
9381           SI.setOperand(1, TrueVal);
9382           SI.setOperand(2, FalseVal);
9383           Changed = true;
9384         }
9385         break;
9386       }
9387       }
9388
9389       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9390       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9391       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9392       if (match(TrueVal, m_ConstantInt<-1>()) &&
9393           match(FalseVal, m_ConstantInt<0>()))
9394         Pred = ICI->getPredicate();
9395       else if (match(TrueVal, m_ConstantInt<0>()) &&
9396                match(FalseVal, m_ConstantInt<-1>()))
9397         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9398       
9399       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9400         // If we are just checking for a icmp eq of a single bit and zext'ing it
9401         // to an integer, then shift the bit to the appropriate place and then
9402         // cast to integer to avoid the comparison.
9403         const APInt &Op1CV = CI->getValue();
9404     
9405         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9406         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9407         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9408             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9409           Value *In = ICI->getOperand(0);
9410           Value *Sh = ConstantInt::get(In->getType(),
9411                                        In->getType()->getScalarSizeInBits()-1);
9412           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9413                                                         In->getName()+".lobit"),
9414                                    *ICI);
9415           if (In->getType() != SI.getType())
9416             In = CastInst::CreateIntegerCast(In, SI.getType(),
9417                                              true/*SExt*/, "tmp", ICI);
9418     
9419           if (Pred == ICmpInst::ICMP_SGT)
9420             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9421                                        In->getName()+".not"), *ICI);
9422     
9423           return ReplaceInstUsesWith(SI, In);
9424         }
9425       }
9426     }
9427
9428   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9429     // Transform (X == Y) ? X : Y  -> Y
9430     if (Pred == ICmpInst::ICMP_EQ)
9431       return ReplaceInstUsesWith(SI, FalseVal);
9432     // Transform (X != Y) ? X : Y  -> X
9433     if (Pred == ICmpInst::ICMP_NE)
9434       return ReplaceInstUsesWith(SI, TrueVal);
9435     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9436
9437   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9438     // Transform (X == Y) ? Y : X  -> X
9439     if (Pred == ICmpInst::ICMP_EQ)
9440       return ReplaceInstUsesWith(SI, FalseVal);
9441     // Transform (X != Y) ? Y : X  -> Y
9442     if (Pred == ICmpInst::ICMP_NE)
9443       return ReplaceInstUsesWith(SI, TrueVal);
9444     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9445   }
9446
9447   /// NOTE: if we wanted to, this is where to detect integer ABS
9448
9449   return Changed ? &SI : 0;
9450 }
9451
9452
9453 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9454 /// PHI node (but the two may be in different blocks).  See if the true/false
9455 /// values (V) are live in all of the predecessor blocks of the PHI.  For
9456 /// example, cases like this cannot be mapped:
9457 ///
9458 ///   X = phi [ C1, BB1], [C2, BB2]
9459 ///   Y = add
9460 ///   Z = select X, Y, 0
9461 ///
9462 /// because Y is not live in BB1/BB2.
9463 ///
9464 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9465                                                    const SelectInst &SI) {
9466   // If the value is a non-instruction value like a constant or argument, it
9467   // can always be mapped.
9468   const Instruction *I = dyn_cast<Instruction>(V);
9469   if (I == 0) return true;
9470   
9471   // If V is a PHI node defined in the same block as the condition PHI, we can
9472   // map the arguments.
9473   const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9474   
9475   if (const PHINode *VP = dyn_cast<PHINode>(I))
9476     if (VP->getParent() == CondPHI->getParent())
9477       return true;
9478   
9479   // Otherwise, if the PHI and select are defined in the same block and if V is
9480   // defined in a different block, then we can transform it.
9481   if (SI.getParent() == CondPHI->getParent() &&
9482       I->getParent() != CondPHI->getParent())
9483     return true;
9484   
9485   // Otherwise we have a 'hard' case and we can't tell without doing more
9486   // detailed dominator based analysis, punt.
9487   return false;
9488 }
9489
9490 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9491   Value *CondVal = SI.getCondition();
9492   Value *TrueVal = SI.getTrueValue();
9493   Value *FalseVal = SI.getFalseValue();
9494
9495   // select true, X, Y  -> X
9496   // select false, X, Y -> Y
9497   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9498     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9499
9500   // select C, X, X -> X
9501   if (TrueVal == FalseVal)
9502     return ReplaceInstUsesWith(SI, TrueVal);
9503
9504   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9505     return ReplaceInstUsesWith(SI, FalseVal);
9506   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9507     return ReplaceInstUsesWith(SI, TrueVal);
9508   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9509     if (isa<Constant>(TrueVal))
9510       return ReplaceInstUsesWith(SI, TrueVal);
9511     else
9512       return ReplaceInstUsesWith(SI, FalseVal);
9513   }
9514
9515   if (SI.getType() == Type::getInt1Ty(*Context)) {
9516     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9517       if (C->getZExtValue()) {
9518         // Change: A = select B, true, C --> A = or B, C
9519         return BinaryOperator::CreateOr(CondVal, FalseVal);
9520       } else {
9521         // Change: A = select B, false, C --> A = and !B, C
9522         Value *NotCond =
9523           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9524                                              "not."+CondVal->getName()), SI);
9525         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9526       }
9527     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9528       if (C->getZExtValue() == false) {
9529         // Change: A = select B, C, false --> A = and B, C
9530         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9531       } else {
9532         // Change: A = select B, C, true --> A = or !B, C
9533         Value *NotCond =
9534           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9535                                              "not."+CondVal->getName()), SI);
9536         return BinaryOperator::CreateOr(NotCond, TrueVal);
9537       }
9538     }
9539     
9540     // select a, b, a  -> a&b
9541     // select a, a, b  -> a|b
9542     if (CondVal == TrueVal)
9543       return BinaryOperator::CreateOr(CondVal, FalseVal);
9544     else if (CondVal == FalseVal)
9545       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9546   }
9547
9548   // Selecting between two integer constants?
9549   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9550     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9551       // select C, 1, 0 -> zext C to int
9552       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9553         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9554       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9555         // select C, 0, 1 -> zext !C to int
9556         Value *NotCond =
9557           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9558                                                "not."+CondVal->getName()), SI);
9559         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9560       }
9561
9562       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9563         // If one of the constants is zero (we know they can't both be) and we
9564         // have an icmp instruction with zero, and we have an 'and' with the
9565         // non-constant value, eliminate this whole mess.  This corresponds to
9566         // cases like this: ((X & 27) ? 27 : 0)
9567         if (TrueValC->isZero() || FalseValC->isZero())
9568           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9569               cast<Constant>(IC->getOperand(1))->isNullValue())
9570             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9571               if (ICA->getOpcode() == Instruction::And &&
9572                   isa<ConstantInt>(ICA->getOperand(1)) &&
9573                   (ICA->getOperand(1) == TrueValC ||
9574                    ICA->getOperand(1) == FalseValC) &&
9575                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9576                 // Okay, now we know that everything is set up, we just don't
9577                 // know whether we have a icmp_ne or icmp_eq and whether the 
9578                 // true or false val is the zero.
9579                 bool ShouldNotVal = !TrueValC->isZero();
9580                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9581                 Value *V = ICA;
9582                 if (ShouldNotVal)
9583                   V = InsertNewInstBefore(BinaryOperator::Create(
9584                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9585                 return ReplaceInstUsesWith(SI, V);
9586               }
9587       }
9588     }
9589
9590   // See if we are selecting two values based on a comparison of the two values.
9591   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9592     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9593       // Transform (X == Y) ? X : Y  -> Y
9594       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9595         // This is not safe in general for floating point:  
9596         // consider X== -0, Y== +0.
9597         // It becomes safe if either operand is a nonzero constant.
9598         ConstantFP *CFPt, *CFPf;
9599         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9600               !CFPt->getValueAPF().isZero()) ||
9601             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9602              !CFPf->getValueAPF().isZero()))
9603         return ReplaceInstUsesWith(SI, FalseVal);
9604       }
9605       // Transform (X != Y) ? X : Y  -> X
9606       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9607         return ReplaceInstUsesWith(SI, TrueVal);
9608       // NOTE: if we wanted to, this is where to detect MIN/MAX
9609
9610     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9611       // Transform (X == Y) ? Y : X  -> X
9612       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9613         // This is not safe in general for floating point:  
9614         // consider X== -0, Y== +0.
9615         // It becomes safe if either operand is a nonzero constant.
9616         ConstantFP *CFPt, *CFPf;
9617         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9618               !CFPt->getValueAPF().isZero()) ||
9619             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9620              !CFPf->getValueAPF().isZero()))
9621           return ReplaceInstUsesWith(SI, FalseVal);
9622       }
9623       // Transform (X != Y) ? Y : X  -> Y
9624       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9625         return ReplaceInstUsesWith(SI, TrueVal);
9626       // NOTE: if we wanted to, this is where to detect MIN/MAX
9627     }
9628     // NOTE: if we wanted to, this is where to detect ABS
9629   }
9630
9631   // See if we are selecting two values based on a comparison of the two values.
9632   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9633     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9634       return Result;
9635
9636   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9637     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9638       if (TI->hasOneUse() && FI->hasOneUse()) {
9639         Instruction *AddOp = 0, *SubOp = 0;
9640
9641         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9642         if (TI->getOpcode() == FI->getOpcode())
9643           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9644             return IV;
9645
9646         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9647         // even legal for FP.
9648         if ((TI->getOpcode() == Instruction::Sub &&
9649              FI->getOpcode() == Instruction::Add) ||
9650             (TI->getOpcode() == Instruction::FSub &&
9651              FI->getOpcode() == Instruction::FAdd)) {
9652           AddOp = FI; SubOp = TI;
9653         } else if ((FI->getOpcode() == Instruction::Sub &&
9654                     TI->getOpcode() == Instruction::Add) ||
9655                    (FI->getOpcode() == Instruction::FSub &&
9656                     TI->getOpcode() == Instruction::FAdd)) {
9657           AddOp = TI; SubOp = FI;
9658         }
9659
9660         if (AddOp) {
9661           Value *OtherAddOp = 0;
9662           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9663             OtherAddOp = AddOp->getOperand(1);
9664           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9665             OtherAddOp = AddOp->getOperand(0);
9666           }
9667
9668           if (OtherAddOp) {
9669             // So at this point we know we have (Y -> OtherAddOp):
9670             //        select C, (add X, Y), (sub X, Z)
9671             Value *NegVal;  // Compute -Z
9672             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9673               NegVal = ConstantExpr::getNeg(C);
9674             } else {
9675               NegVal = InsertNewInstBefore(
9676                     BinaryOperator::CreateNeg(SubOp->getOperand(1),
9677                                               "tmp"), SI);
9678             }
9679
9680             Value *NewTrueOp = OtherAddOp;
9681             Value *NewFalseOp = NegVal;
9682             if (AddOp != TI)
9683               std::swap(NewTrueOp, NewFalseOp);
9684             Instruction *NewSel =
9685               SelectInst::Create(CondVal, NewTrueOp,
9686                                  NewFalseOp, SI.getName() + ".p");
9687
9688             NewSel = InsertNewInstBefore(NewSel, SI);
9689             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9690           }
9691         }
9692       }
9693
9694   // See if we can fold the select into one of our operands.
9695   if (SI.getType()->isInteger()) {
9696     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9697     if (FoldI)
9698       return FoldI;
9699   }
9700
9701   // See if we can fold the select into a phi node if the condition is a select.
9702   if (isa<PHINode>(SI.getCondition())) 
9703     // The true/false values have to be live in the PHI predecessor's blocks.
9704     if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
9705         CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
9706       if (Instruction *NV = FoldOpIntoPhi(SI))
9707         return NV;
9708
9709   if (BinaryOperator::isNot(CondVal)) {
9710     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9711     SI.setOperand(1, FalseVal);
9712     SI.setOperand(2, TrueVal);
9713     return &SI;
9714   }
9715
9716   return 0;
9717 }
9718
9719 /// EnforceKnownAlignment - If the specified pointer points to an object that
9720 /// we control, modify the object's alignment to PrefAlign. This isn't
9721 /// often possible though. If alignment is important, a more reliable approach
9722 /// is to simply align all global variables and allocation instructions to
9723 /// their preferred alignment from the beginning.
9724 ///
9725 static unsigned EnforceKnownAlignment(Value *V,
9726                                       unsigned Align, unsigned PrefAlign) {
9727
9728   User *U = dyn_cast<User>(V);
9729   if (!U) return Align;
9730
9731   switch (Operator::getOpcode(U)) {
9732   default: break;
9733   case Instruction::BitCast:
9734     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9735   case Instruction::GetElementPtr: {
9736     // If all indexes are zero, it is just the alignment of the base pointer.
9737     bool AllZeroOperands = true;
9738     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9739       if (!isa<Constant>(*i) ||
9740           !cast<Constant>(*i)->isNullValue()) {
9741         AllZeroOperands = false;
9742         break;
9743       }
9744
9745     if (AllZeroOperands) {
9746       // Treat this like a bitcast.
9747       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9748     }
9749     break;
9750   }
9751   }
9752
9753   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9754     // If there is a large requested alignment and we can, bump up the alignment
9755     // of the global.
9756     if (!GV->isDeclaration()) {
9757       if (GV->getAlignment() >= PrefAlign)
9758         Align = GV->getAlignment();
9759       else {
9760         GV->setAlignment(PrefAlign);
9761         Align = PrefAlign;
9762       }
9763     }
9764   } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9765     // If there is a requested alignment and if this is an alloca, round up.
9766     if (AI->getAlignment() >= PrefAlign)
9767       Align = AI->getAlignment();
9768     else {
9769       AI->setAlignment(PrefAlign);
9770       Align = PrefAlign;
9771     }
9772   }
9773
9774   return Align;
9775 }
9776
9777 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9778 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9779 /// and it is more than the alignment of the ultimate object, see if we can
9780 /// increase the alignment of the ultimate object, making this check succeed.
9781 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9782                                                   unsigned PrefAlign) {
9783   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9784                       sizeof(PrefAlign) * CHAR_BIT;
9785   APInt Mask = APInt::getAllOnesValue(BitWidth);
9786   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9787   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9788   unsigned TrailZ = KnownZero.countTrailingOnes();
9789   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9790
9791   if (PrefAlign > Align)
9792     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9793   
9794     // We don't need to make any adjustment.
9795   return Align;
9796 }
9797
9798 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9799   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9800   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9801   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9802   unsigned CopyAlign = MI->getAlignment();
9803
9804   if (CopyAlign < MinAlign) {
9805     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 
9806                                              MinAlign, false));
9807     return MI;
9808   }
9809   
9810   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9811   // load/store.
9812   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9813   if (MemOpLength == 0) return 0;
9814   
9815   // Source and destination pointer types are always "i8*" for intrinsic.  See
9816   // if the size is something we can handle with a single primitive load/store.
9817   // A single load+store correctly handles overlapping memory in the memmove
9818   // case.
9819   unsigned Size = MemOpLength->getZExtValue();
9820   if (Size == 0) return MI;  // Delete this mem transfer.
9821   
9822   if (Size > 8 || (Size&(Size-1)))
9823     return 0;  // If not 1/2/4/8 bytes, exit.
9824   
9825   // Use an integer load+store unless we can find something better.
9826   Type *NewPtrTy =
9827                 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
9828   
9829   // Memcpy forces the use of i8* for the source and destination.  That means
9830   // that if you're using memcpy to move one double around, you'll get a cast
9831   // from double* to i8*.  We'd much rather use a double load+store rather than
9832   // an i64 load+store, here because this improves the odds that the source or
9833   // dest address will be promotable.  See if we can find a better type than the
9834   // integer datatype.
9835   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9836     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9837     if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9838       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9839       // down through these levels if so.
9840       while (!SrcETy->isSingleValueType()) {
9841         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9842           if (STy->getNumElements() == 1)
9843             SrcETy = STy->getElementType(0);
9844           else
9845             break;
9846         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9847           if (ATy->getNumElements() == 1)
9848             SrcETy = ATy->getElementType();
9849           else
9850             break;
9851         } else
9852           break;
9853       }
9854       
9855       if (SrcETy->isSingleValueType())
9856         NewPtrTy = PointerType::getUnqual(SrcETy);
9857     }
9858   }
9859   
9860   
9861   // If the memcpy/memmove provides better alignment info than we can
9862   // infer, use it.
9863   SrcAlign = std::max(SrcAlign, CopyAlign);
9864   DstAlign = std::max(DstAlign, CopyAlign);
9865   
9866   Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9867   Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
9868   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9869   InsertNewInstBefore(L, *MI);
9870   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9871
9872   // Set the size of the copy to 0, it will be deleted on the next iteration.
9873   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9874   return MI;
9875 }
9876
9877 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9878   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9879   if (MI->getAlignment() < Alignment) {
9880     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9881                                              Alignment, false));
9882     return MI;
9883   }
9884   
9885   // Extract the length and alignment and fill if they are constant.
9886   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9887   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9888   if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
9889     return 0;
9890   uint64_t Len = LenC->getZExtValue();
9891   Alignment = MI->getAlignment();
9892   
9893   // If the length is zero, this is a no-op
9894   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9895   
9896   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9897   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9898     const Type *ITy = IntegerType::get(*Context, Len*8);  // n=1 -> i8.
9899     
9900     Value *Dest = MI->getDest();
9901     Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
9902
9903     // Alignment 0 is identity for alignment 1 for memset, but not store.
9904     if (Alignment == 0) Alignment = 1;
9905     
9906     // Extract the fill value and store.
9907     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9908     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9909                                       Dest, false, Alignment), *MI);
9910     
9911     // Set the size of the copy to 0, it will be deleted on the next iteration.
9912     MI->setLength(Constant::getNullValue(LenC->getType()));
9913     return MI;
9914   }
9915
9916   return 0;
9917 }
9918
9919
9920 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9921 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9922 /// the heavy lifting.
9923 ///
9924 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9925   if (isFreeCall(&CI))
9926     return visitFree(CI);
9927
9928   // If the caller function is nounwind, mark the call as nounwind, even if the
9929   // callee isn't.
9930   if (CI.getParent()->getParent()->doesNotThrow() &&
9931       !CI.doesNotThrow()) {
9932     CI.setDoesNotThrow();
9933     return &CI;
9934   }
9935   
9936   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9937   if (!II) return visitCallSite(&CI);
9938   
9939   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9940   // visitCallSite.
9941   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9942     bool Changed = false;
9943
9944     // memmove/cpy/set of zero bytes is a noop.
9945     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9946       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9947
9948       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9949         if (CI->getZExtValue() == 1) {
9950           // Replace the instruction with just byte operations.  We would
9951           // transform other cases to loads/stores, but we don't know if
9952           // alignment is sufficient.
9953         }
9954     }
9955
9956     // If we have a memmove and the source operation is a constant global,
9957     // then the source and dest pointers can't alias, so we can change this
9958     // into a call to memcpy.
9959     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9960       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9961         if (GVSrc->isConstant()) {
9962           Module *M = CI.getParent()->getParent()->getParent();
9963           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9964           const Type *Tys[1];
9965           Tys[0] = CI.getOperand(3)->getType();
9966           CI.setOperand(0, 
9967                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9968           Changed = true;
9969         }
9970     }
9971
9972     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
9973       // memmove(x,x,size) -> noop.
9974       if (MTI->getSource() == MTI->getDest())
9975         return EraseInstFromFunction(CI);
9976     }
9977
9978     // If we can determine a pointer alignment that is bigger than currently
9979     // set, update the alignment.
9980     if (isa<MemTransferInst>(MI)) {
9981       if (Instruction *I = SimplifyMemTransfer(MI))
9982         return I;
9983     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9984       if (Instruction *I = SimplifyMemSet(MSI))
9985         return I;
9986     }
9987           
9988     if (Changed) return II;
9989   }
9990   
9991   switch (II->getIntrinsicID()) {
9992   default: break;
9993   case Intrinsic::bswap:
9994     // bswap(bswap(x)) -> x
9995     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9996       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9997         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9998     break;
9999   case Intrinsic::uadd_with_overflow: {
10000     Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
10001     const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
10002     uint32_t BitWidth = IT->getBitWidth();
10003     APInt Mask = APInt::getSignBit(BitWidth);
10004     APInt LHSKnownZero(BitWidth, 0);
10005     APInt LHSKnownOne(BitWidth, 0);
10006     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
10007     bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
10008     bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
10009
10010     if (LHSKnownNegative || LHSKnownPositive) {
10011       APInt RHSKnownZero(BitWidth, 0);
10012       APInt RHSKnownOne(BitWidth, 0);
10013       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
10014       bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
10015       bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
10016       if (LHSKnownNegative && RHSKnownNegative) {
10017         // The sign bit is set in both cases: this MUST overflow.
10018         // Create a simple add instruction, and insert it into the struct.
10019         Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
10020         Worklist.Add(Add);
10021         Constant *V[] = {
10022           UndefValue::get(LHS->getType()), ConstantInt::getTrue(*Context)
10023         };
10024         Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10025         return InsertValueInst::Create(Struct, Add, 0);
10026       }
10027       
10028       if (LHSKnownPositive && RHSKnownPositive) {
10029         // The sign bit is clear in both cases: this CANNOT overflow.
10030         // Create a simple add instruction, and insert it into the struct.
10031         Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
10032         Worklist.Add(Add);
10033         Constant *V[] = {
10034           UndefValue::get(LHS->getType()), ConstantInt::getFalse(*Context)
10035         };
10036         Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10037         return InsertValueInst::Create(Struct, Add, 0);
10038       }
10039     }
10040   }
10041   // FALL THROUGH uadd into sadd
10042   case Intrinsic::sadd_with_overflow:
10043     // Canonicalize constants into the RHS.
10044     if (isa<Constant>(II->getOperand(1)) &&
10045         !isa<Constant>(II->getOperand(2))) {
10046       Value *LHS = II->getOperand(1);
10047       II->setOperand(1, II->getOperand(2));
10048       II->setOperand(2, LHS);
10049       return II;
10050     }
10051
10052     // X + undef -> undef
10053     if (isa<UndefValue>(II->getOperand(2)))
10054       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10055       
10056     if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10057       // X + 0 -> {X, false}
10058       if (RHS->isZero()) {
10059         Constant *V[] = {
10060           UndefValue::get(II->getOperand(0)->getType()),
10061           ConstantInt::getFalse(*Context)
10062         };
10063         Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10064         return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10065       }
10066     }
10067     break;
10068   case Intrinsic::usub_with_overflow:
10069   case Intrinsic::ssub_with_overflow:
10070     // undef - X -> undef
10071     // X - undef -> undef
10072     if (isa<UndefValue>(II->getOperand(1)) ||
10073         isa<UndefValue>(II->getOperand(2)))
10074       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10075       
10076     if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10077       // X - 0 -> {X, false}
10078       if (RHS->isZero()) {
10079         Constant *V[] = {
10080           UndefValue::get(II->getOperand(1)->getType()),
10081           ConstantInt::getFalse(*Context)
10082         };
10083         Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10084         return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10085       }
10086     }
10087     break;
10088   case Intrinsic::umul_with_overflow:
10089   case Intrinsic::smul_with_overflow:
10090     // Canonicalize constants into the RHS.
10091     if (isa<Constant>(II->getOperand(1)) &&
10092         !isa<Constant>(II->getOperand(2))) {
10093       Value *LHS = II->getOperand(1);
10094       II->setOperand(1, II->getOperand(2));
10095       II->setOperand(2, LHS);
10096       return II;
10097     }
10098
10099     // X * undef -> undef
10100     if (isa<UndefValue>(II->getOperand(2)))
10101       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10102       
10103     if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
10104       // X*0 -> {0, false}
10105       if (RHSI->isZero())
10106         return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
10107       
10108       // X * 1 -> {X, false}
10109       if (RHSI->equalsInt(1)) {
10110         Constant *V[] = {
10111           UndefValue::get(II->getOperand(1)->getType()),
10112           ConstantInt::getFalse(*Context)
10113         };
10114         Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10115         return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10116       }
10117     }
10118     break;
10119   case Intrinsic::ppc_altivec_lvx:
10120   case Intrinsic::ppc_altivec_lvxl:
10121   case Intrinsic::x86_sse_loadu_ps:
10122   case Intrinsic::x86_sse2_loadu_pd:
10123   case Intrinsic::x86_sse2_loadu_dq:
10124     // Turn PPC lvx     -> load if the pointer is known aligned.
10125     // Turn X86 loadups -> load if the pointer is known aligned.
10126     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
10127       Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
10128                                          PointerType::getUnqual(II->getType()));
10129       return new LoadInst(Ptr);
10130     }
10131     break;
10132   case Intrinsic::ppc_altivec_stvx:
10133   case Intrinsic::ppc_altivec_stvxl:
10134     // Turn stvx -> store if the pointer is known aligned.
10135     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
10136       const Type *OpPtrTy = 
10137         PointerType::getUnqual(II->getOperand(1)->getType());
10138       Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
10139       return new StoreInst(II->getOperand(1), Ptr);
10140     }
10141     break;
10142   case Intrinsic::x86_sse_storeu_ps:
10143   case Intrinsic::x86_sse2_storeu_pd:
10144   case Intrinsic::x86_sse2_storeu_dq:
10145     // Turn X86 storeu -> store if the pointer is known aligned.
10146     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
10147       const Type *OpPtrTy = 
10148         PointerType::getUnqual(II->getOperand(2)->getType());
10149       Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
10150       return new StoreInst(II->getOperand(2), Ptr);
10151     }
10152     break;
10153     
10154   case Intrinsic::x86_sse_cvttss2si: {
10155     // These intrinsics only demands the 0th element of its input vector.  If
10156     // we can simplify the input based on that, do so now.
10157     unsigned VWidth =
10158       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
10159     APInt DemandedElts(VWidth, 1);
10160     APInt UndefElts(VWidth, 0);
10161     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
10162                                               UndefElts)) {
10163       II->setOperand(1, V);
10164       return II;
10165     }
10166     break;
10167   }
10168     
10169   case Intrinsic::ppc_altivec_vperm:
10170     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
10171     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
10172       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
10173       
10174       // Check that all of the elements are integer constants or undefs.
10175       bool AllEltsOk = true;
10176       for (unsigned i = 0; i != 16; ++i) {
10177         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
10178             !isa<UndefValue>(Mask->getOperand(i))) {
10179           AllEltsOk = false;
10180           break;
10181         }
10182       }
10183       
10184       if (AllEltsOk) {
10185         // Cast the input vectors to byte vectors.
10186         Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
10187         Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
10188         Value *Result = UndefValue::get(Op0->getType());
10189         
10190         // Only extract each element once.
10191         Value *ExtractedElts[32];
10192         memset(ExtractedElts, 0, sizeof(ExtractedElts));
10193         
10194         for (unsigned i = 0; i != 16; ++i) {
10195           if (isa<UndefValue>(Mask->getOperand(i)))
10196             continue;
10197           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
10198           Idx &= 31;  // Match the hardware behavior.
10199           
10200           if (ExtractedElts[Idx] == 0) {
10201             ExtractedElts[Idx] = 
10202               Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1, 
10203                   ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
10204                                             "tmp");
10205           }
10206         
10207           // Insert this value into the result vector.
10208           Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
10209                          ConstantInt::get(Type::getInt32Ty(*Context), i, false),
10210                                                 "tmp");
10211         }
10212         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
10213       }
10214     }
10215     break;
10216
10217   case Intrinsic::stackrestore: {
10218     // If the save is right next to the restore, remove the restore.  This can
10219     // happen when variable allocas are DCE'd.
10220     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10221       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10222         BasicBlock::iterator BI = SS;
10223         if (&*++BI == II)
10224           return EraseInstFromFunction(CI);
10225       }
10226     }
10227     
10228     // Scan down this block to see if there is another stack restore in the
10229     // same block without an intervening call/alloca.
10230     BasicBlock::iterator BI = II;
10231     TerminatorInst *TI = II->getParent()->getTerminator();
10232     bool CannotRemove = false;
10233     for (++BI; &*BI != TI; ++BI) {
10234       if (isa<AllocaInst>(BI) || isMalloc(BI)) {
10235         CannotRemove = true;
10236         break;
10237       }
10238       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10239         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10240           // If there is a stackrestore below this one, remove this one.
10241           if (II->getIntrinsicID() == Intrinsic::stackrestore)
10242             return EraseInstFromFunction(CI);
10243           // Otherwise, ignore the intrinsic.
10244         } else {
10245           // If we found a non-intrinsic call, we can't remove the stack
10246           // restore.
10247           CannotRemove = true;
10248           break;
10249         }
10250       }
10251     }
10252     
10253     // If the stack restore is in a return/unwind block and if there are no
10254     // allocas or calls between the restore and the return, nuke the restore.
10255     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10256       return EraseInstFromFunction(CI);
10257     break;
10258   }
10259   }
10260
10261   return visitCallSite(II);
10262 }
10263
10264 // InvokeInst simplification
10265 //
10266 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10267   return visitCallSite(&II);
10268 }
10269
10270 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
10271 /// passed through the varargs area, we can eliminate the use of the cast.
10272 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10273                                          const CastInst * const CI,
10274                                          const TargetData * const TD,
10275                                          const int ix) {
10276   if (!CI->isLosslessCast())
10277     return false;
10278
10279   // The size of ByVal arguments is derived from the type, so we
10280   // can't change to a type with a different size.  If the size were
10281   // passed explicitly we could avoid this check.
10282   if (!CS.paramHasAttr(ix, Attribute::ByVal))
10283     return true;
10284
10285   const Type* SrcTy = 
10286             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10287   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10288   if (!SrcTy->isSized() || !DstTy->isSized())
10289     return false;
10290   if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10291     return false;
10292   return true;
10293 }
10294
10295 // visitCallSite - Improvements for call and invoke instructions.
10296 //
10297 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10298   bool Changed = false;
10299
10300   // If the callee is a constexpr cast of a function, attempt to move the cast
10301   // to the arguments of the call/invoke.
10302   if (transformConstExprCastCall(CS)) return 0;
10303
10304   Value *Callee = CS.getCalledValue();
10305
10306   if (Function *CalleeF = dyn_cast<Function>(Callee))
10307     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10308       Instruction *OldCall = CS.getInstruction();
10309       // If the call and callee calling conventions don't match, this call must
10310       // be unreachable, as the call is undefined.
10311       new StoreInst(ConstantInt::getTrue(*Context),
10312                 UndefValue::get(Type::getInt1PtrTy(*Context)), 
10313                                   OldCall);
10314       // If OldCall dues not return void then replaceAllUsesWith undef.
10315       // This allows ValueHandlers and custom metadata to adjust itself.
10316       if (!OldCall->getType()->isVoidTy())
10317         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
10318       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10319         return EraseInstFromFunction(*OldCall);
10320       return 0;
10321     }
10322
10323   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10324     // This instruction is not reachable, just remove it.  We insert a store to
10325     // undef so that we know that this code is not reachable, despite the fact
10326     // that we can't modify the CFG here.
10327     new StoreInst(ConstantInt::getTrue(*Context),
10328                UndefValue::get(Type::getInt1PtrTy(*Context)),
10329                   CS.getInstruction());
10330
10331     // If CS dues not return void then replaceAllUsesWith undef.
10332     // This allows ValueHandlers and custom metadata to adjust itself.
10333     if (!CS.getInstruction()->getType()->isVoidTy())
10334       CS.getInstruction()->
10335         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
10336
10337     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10338       // Don't break the CFG, insert a dummy cond branch.
10339       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10340                          ConstantInt::getTrue(*Context), II);
10341     }
10342     return EraseInstFromFunction(*CS.getInstruction());
10343   }
10344
10345   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10346     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10347       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10348         return transformCallThroughTrampoline(CS);
10349
10350   const PointerType *PTy = cast<PointerType>(Callee->getType());
10351   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10352   if (FTy->isVarArg()) {
10353     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10354     // See if we can optimize any arguments passed through the varargs area of
10355     // the call.
10356     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10357            E = CS.arg_end(); I != E; ++I, ++ix) {
10358       CastInst *CI = dyn_cast<CastInst>(*I);
10359       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10360         *I = CI->getOperand(0);
10361         Changed = true;
10362       }
10363     }
10364   }
10365
10366   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10367     // Inline asm calls cannot throw - mark them 'nounwind'.
10368     CS.setDoesNotThrow();
10369     Changed = true;
10370   }
10371
10372   return Changed ? CS.getInstruction() : 0;
10373 }
10374
10375 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10376 // attempt to move the cast to the arguments of the call/invoke.
10377 //
10378 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10379   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10380   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10381   if (CE->getOpcode() != Instruction::BitCast || 
10382       !isa<Function>(CE->getOperand(0)))
10383     return false;
10384   Function *Callee = cast<Function>(CE->getOperand(0));
10385   Instruction *Caller = CS.getInstruction();
10386   const AttrListPtr &CallerPAL = CS.getAttributes();
10387
10388   // Okay, this is a cast from a function to a different type.  Unless doing so
10389   // would cause a type conversion of one of our arguments, change this call to
10390   // be a direct call with arguments casted to the appropriate types.
10391   //
10392   const FunctionType *FT = Callee->getFunctionType();
10393   const Type *OldRetTy = Caller->getType();
10394   const Type *NewRetTy = FT->getReturnType();
10395
10396   if (isa<StructType>(NewRetTy))
10397     return false; // TODO: Handle multiple return values.
10398
10399   // Check to see if we are changing the return type...
10400   if (OldRetTy != NewRetTy) {
10401     if (Callee->isDeclaration() &&
10402         // Conversion is ok if changing from one pointer type to another or from
10403         // a pointer to an integer of the same size.
10404         !((isa<PointerType>(OldRetTy) || !TD ||
10405            OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
10406           (isa<PointerType>(NewRetTy) || !TD ||
10407            NewRetTy == TD->getIntPtrType(Caller->getContext()))))
10408       return false;   // Cannot transform this return value.
10409
10410     if (!Caller->use_empty() &&
10411         // void -> non-void is handled specially
10412         !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
10413       return false;   // Cannot transform this return value.
10414
10415     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10416       Attributes RAttrs = CallerPAL.getRetAttributes();
10417       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10418         return false;   // Attribute not compatible with transformed value.
10419     }
10420
10421     // If the callsite is an invoke instruction, and the return value is used by
10422     // a PHI node in a successor, we cannot change the return type of the call
10423     // because there is no place to put the cast instruction (without breaking
10424     // the critical edge).  Bail out in this case.
10425     if (!Caller->use_empty())
10426       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10427         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10428              UI != E; ++UI)
10429           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10430             if (PN->getParent() == II->getNormalDest() ||
10431                 PN->getParent() == II->getUnwindDest())
10432               return false;
10433   }
10434
10435   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10436   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10437
10438   CallSite::arg_iterator AI = CS.arg_begin();
10439   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10440     const Type *ParamTy = FT->getParamType(i);
10441     const Type *ActTy = (*AI)->getType();
10442
10443     if (!CastInst::isCastable(ActTy, ParamTy))
10444       return false;   // Cannot transform this parameter value.
10445
10446     if (CallerPAL.getParamAttributes(i + 1) 
10447         & Attribute::typeIncompatible(ParamTy))
10448       return false;   // Attribute not compatible with transformed value.
10449
10450     // Converting from one pointer type to another or between a pointer and an
10451     // integer of the same size is safe even if we do not have a body.
10452     bool isConvertible = ActTy == ParamTy ||
10453       (TD && ((isa<PointerType>(ParamTy) ||
10454       ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10455               (isa<PointerType>(ActTy) ||
10456               ActTy == TD->getIntPtrType(Caller->getContext()))));
10457     if (Callee->isDeclaration() && !isConvertible) return false;
10458   }
10459
10460   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10461       Callee->isDeclaration())
10462     return false;   // Do not delete arguments unless we have a function body.
10463
10464   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10465       !CallerPAL.isEmpty())
10466     // In this case we have more arguments than the new function type, but we
10467     // won't be dropping them.  Check that these extra arguments have attributes
10468     // that are compatible with being a vararg call argument.
10469     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10470       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10471         break;
10472       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10473       if (PAttrs & Attribute::VarArgsIncompatible)
10474         return false;
10475     }
10476
10477   // Okay, we decided that this is a safe thing to do: go ahead and start
10478   // inserting cast instructions as necessary...
10479   std::vector<Value*> Args;
10480   Args.reserve(NumActualArgs);
10481   SmallVector<AttributeWithIndex, 8> attrVec;
10482   attrVec.reserve(NumCommonArgs);
10483
10484   // Get any return attributes.
10485   Attributes RAttrs = CallerPAL.getRetAttributes();
10486
10487   // If the return value is not being used, the type may not be compatible
10488   // with the existing attributes.  Wipe out any problematic attributes.
10489   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10490
10491   // Add the new return attributes.
10492   if (RAttrs)
10493     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10494
10495   AI = CS.arg_begin();
10496   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10497     const Type *ParamTy = FT->getParamType(i);
10498     if ((*AI)->getType() == ParamTy) {
10499       Args.push_back(*AI);
10500     } else {
10501       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10502           false, ParamTy, false);
10503       Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
10504     }
10505
10506     // Add any parameter attributes.
10507     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10508       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10509   }
10510
10511   // If the function takes more arguments than the call was taking, add them
10512   // now.
10513   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10514     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10515
10516   // If we are removing arguments to the function, emit an obnoxious warning.
10517   if (FT->getNumParams() < NumActualArgs) {
10518     if (!FT->isVarArg()) {
10519       errs() << "WARNING: While resolving call to function '"
10520              << Callee->getName() << "' arguments were dropped!\n";
10521     } else {
10522       // Add all of the arguments in their promoted form to the arg list.
10523       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10524         const Type *PTy = getPromotedType((*AI)->getType());
10525         if (PTy != (*AI)->getType()) {
10526           // Must promote to pass through va_arg area!
10527           Instruction::CastOps opcode =
10528             CastInst::getCastOpcode(*AI, false, PTy, false);
10529           Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
10530         } else {
10531           Args.push_back(*AI);
10532         }
10533
10534         // Add any parameter attributes.
10535         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10536           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10537       }
10538     }
10539   }
10540
10541   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10542     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10543
10544   if (NewRetTy->isVoidTy())
10545     Caller->setName("");   // Void type should not have a name.
10546
10547   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10548                                                      attrVec.end());
10549
10550   Instruction *NC;
10551   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10552     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10553                             Args.begin(), Args.end(),
10554                             Caller->getName(), Caller);
10555     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10556     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10557   } else {
10558     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10559                           Caller->getName(), Caller);
10560     CallInst *CI = cast<CallInst>(Caller);
10561     if (CI->isTailCall())
10562       cast<CallInst>(NC)->setTailCall();
10563     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10564     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10565   }
10566
10567   // Insert a cast of the return type as necessary.
10568   Value *NV = NC;
10569   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10570     if (!NV->getType()->isVoidTy()) {
10571       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10572                                                             OldRetTy, false);
10573       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10574
10575       // If this is an invoke instruction, we should insert it after the first
10576       // non-phi, instruction in the normal successor block.
10577       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10578         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10579         InsertNewInstBefore(NC, *I);
10580       } else {
10581         // Otherwise, it's a call, just insert cast right after the call instr
10582         InsertNewInstBefore(NC, *Caller);
10583       }
10584       Worklist.AddUsersToWorkList(*Caller);
10585     } else {
10586       NV = UndefValue::get(Caller->getType());
10587     }
10588   }
10589
10590
10591   if (!Caller->use_empty())
10592     Caller->replaceAllUsesWith(NV);
10593   
10594   EraseInstFromFunction(*Caller);
10595   return true;
10596 }
10597
10598 // transformCallThroughTrampoline - Turn a call to a function created by the
10599 // init_trampoline intrinsic into a direct call to the underlying function.
10600 //
10601 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10602   Value *Callee = CS.getCalledValue();
10603   const PointerType *PTy = cast<PointerType>(Callee->getType());
10604   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10605   const AttrListPtr &Attrs = CS.getAttributes();
10606
10607   // If the call already has the 'nest' attribute somewhere then give up -
10608   // otherwise 'nest' would occur twice after splicing in the chain.
10609   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10610     return 0;
10611
10612   IntrinsicInst *Tramp =
10613     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10614
10615   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10616   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10617   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10618
10619   const AttrListPtr &NestAttrs = NestF->getAttributes();
10620   if (!NestAttrs.isEmpty()) {
10621     unsigned NestIdx = 1;
10622     const Type *NestTy = 0;
10623     Attributes NestAttr = Attribute::None;
10624
10625     // Look for a parameter marked with the 'nest' attribute.
10626     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10627          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10628       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10629         // Record the parameter type and any other attributes.
10630         NestTy = *I;
10631         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10632         break;
10633       }
10634
10635     if (NestTy) {
10636       Instruction *Caller = CS.getInstruction();
10637       std::vector<Value*> NewArgs;
10638       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10639
10640       SmallVector<AttributeWithIndex, 8> NewAttrs;
10641       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10642
10643       // Insert the nest argument into the call argument list, which may
10644       // mean appending it.  Likewise for attributes.
10645
10646       // Add any result attributes.
10647       if (Attributes Attr = Attrs.getRetAttributes())
10648         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10649
10650       {
10651         unsigned Idx = 1;
10652         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10653         do {
10654           if (Idx == NestIdx) {
10655             // Add the chain argument and attributes.
10656             Value *NestVal = Tramp->getOperand(3);
10657             if (NestVal->getType() != NestTy)
10658               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10659             NewArgs.push_back(NestVal);
10660             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10661           }
10662
10663           if (I == E)
10664             break;
10665
10666           // Add the original argument and attributes.
10667           NewArgs.push_back(*I);
10668           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10669             NewAttrs.push_back
10670               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10671
10672           ++Idx, ++I;
10673         } while (1);
10674       }
10675
10676       // Add any function attributes.
10677       if (Attributes Attr = Attrs.getFnAttributes())
10678         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10679
10680       // The trampoline may have been bitcast to a bogus type (FTy).
10681       // Handle this by synthesizing a new function type, equal to FTy
10682       // with the chain parameter inserted.
10683
10684       std::vector<const Type*> NewTypes;
10685       NewTypes.reserve(FTy->getNumParams()+1);
10686
10687       // Insert the chain's type into the list of parameter types, which may
10688       // mean appending it.
10689       {
10690         unsigned Idx = 1;
10691         FunctionType::param_iterator I = FTy->param_begin(),
10692           E = FTy->param_end();
10693
10694         do {
10695           if (Idx == NestIdx)
10696             // Add the chain's type.
10697             NewTypes.push_back(NestTy);
10698
10699           if (I == E)
10700             break;
10701
10702           // Add the original type.
10703           NewTypes.push_back(*I);
10704
10705           ++Idx, ++I;
10706         } while (1);
10707       }
10708
10709       // Replace the trampoline call with a direct call.  Let the generic
10710       // code sort out any function type mismatches.
10711       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 
10712                                                 FTy->isVarArg());
10713       Constant *NewCallee =
10714         NestF->getType() == PointerType::getUnqual(NewFTy) ?
10715         NestF : ConstantExpr::getBitCast(NestF, 
10716                                          PointerType::getUnqual(NewFTy));
10717       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10718                                                    NewAttrs.end());
10719
10720       Instruction *NewCaller;
10721       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10722         NewCaller = InvokeInst::Create(NewCallee,
10723                                        II->getNormalDest(), II->getUnwindDest(),
10724                                        NewArgs.begin(), NewArgs.end(),
10725                                        Caller->getName(), Caller);
10726         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10727         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10728       } else {
10729         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10730                                      Caller->getName(), Caller);
10731         if (cast<CallInst>(Caller)->isTailCall())
10732           cast<CallInst>(NewCaller)->setTailCall();
10733         cast<CallInst>(NewCaller)->
10734           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10735         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10736       }
10737       if (!Caller->getType()->isVoidTy())
10738         Caller->replaceAllUsesWith(NewCaller);
10739       Caller->eraseFromParent();
10740       Worklist.Remove(Caller);
10741       return 0;
10742     }
10743   }
10744
10745   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10746   // parameter, there is no need to adjust the argument list.  Let the generic
10747   // code sort out any function type mismatches.
10748   Constant *NewCallee =
10749     NestF->getType() == PTy ? NestF : 
10750                               ConstantExpr::getBitCast(NestF, PTy);
10751   CS.setCalledFunction(NewCallee);
10752   return CS.getInstruction();
10753 }
10754
10755 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10756 /// and if a/b/c and the add's all have a single use, turn this into a phi
10757 /// and a single binop.
10758 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10759   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10760   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10761   unsigned Opc = FirstInst->getOpcode();
10762   Value *LHSVal = FirstInst->getOperand(0);
10763   Value *RHSVal = FirstInst->getOperand(1);
10764     
10765   const Type *LHSType = LHSVal->getType();
10766   const Type *RHSType = RHSVal->getType();
10767   
10768   // Scan to see if all operands are the same opcode, and all have one use.
10769   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10770     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10771     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10772         // Verify type of the LHS matches so we don't fold cmp's of different
10773         // types or GEP's with different index types.
10774         I->getOperand(0)->getType() != LHSType ||
10775         I->getOperand(1)->getType() != RHSType)
10776       return 0;
10777
10778     // If they are CmpInst instructions, check their predicates
10779     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10780       if (cast<CmpInst>(I)->getPredicate() !=
10781           cast<CmpInst>(FirstInst)->getPredicate())
10782         return 0;
10783     
10784     // Keep track of which operand needs a phi node.
10785     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10786     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10787   }
10788
10789   // If both LHS and RHS would need a PHI, don't do this transformation,
10790   // because it would increase the number of PHIs entering the block,
10791   // which leads to higher register pressure. This is especially
10792   // bad when the PHIs are in the header of a loop.
10793   if (!LHSVal && !RHSVal)
10794     return 0;
10795   
10796   // Otherwise, this is safe to transform!
10797   
10798   Value *InLHS = FirstInst->getOperand(0);
10799   Value *InRHS = FirstInst->getOperand(1);
10800   PHINode *NewLHS = 0, *NewRHS = 0;
10801   if (LHSVal == 0) {
10802     NewLHS = PHINode::Create(LHSType,
10803                              FirstInst->getOperand(0)->getName() + ".pn");
10804     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10805     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10806     InsertNewInstBefore(NewLHS, PN);
10807     LHSVal = NewLHS;
10808   }
10809   
10810   if (RHSVal == 0) {
10811     NewRHS = PHINode::Create(RHSType,
10812                              FirstInst->getOperand(1)->getName() + ".pn");
10813     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10814     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10815     InsertNewInstBefore(NewRHS, PN);
10816     RHSVal = NewRHS;
10817   }
10818   
10819   // Add all operands to the new PHIs.
10820   if (NewLHS || NewRHS) {
10821     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10822       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10823       if (NewLHS) {
10824         Value *NewInLHS = InInst->getOperand(0);
10825         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10826       }
10827       if (NewRHS) {
10828         Value *NewInRHS = InInst->getOperand(1);
10829         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10830       }
10831     }
10832   }
10833     
10834   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10835     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10836   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10837   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10838                          LHSVal, RHSVal);
10839 }
10840
10841 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10842   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10843   
10844   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10845                                         FirstInst->op_end());
10846   // This is true if all GEP bases are allocas and if all indices into them are
10847   // constants.
10848   bool AllBasePointersAreAllocas = true;
10849
10850   // We don't want to replace this phi if the replacement would require
10851   // more than one phi, which leads to higher register pressure. This is
10852   // especially bad when the PHIs are in the header of a loop.
10853   bool NeededPhi = false;
10854   
10855   // Scan to see if all operands are the same opcode, and all have one use.
10856   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10857     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10858     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10859       GEP->getNumOperands() != FirstInst->getNumOperands())
10860       return 0;
10861
10862     // Keep track of whether or not all GEPs are of alloca pointers.
10863     if (AllBasePointersAreAllocas &&
10864         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10865          !GEP->hasAllConstantIndices()))
10866       AllBasePointersAreAllocas = false;
10867     
10868     // Compare the operand lists.
10869     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10870       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10871         continue;
10872       
10873       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10874       // if one of the PHIs has a constant for the index.  The index may be
10875       // substantially cheaper to compute for the constants, so making it a
10876       // variable index could pessimize the path.  This also handles the case
10877       // for struct indices, which must always be constant.
10878       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10879           isa<ConstantInt>(GEP->getOperand(op)))
10880         return 0;
10881       
10882       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10883         return 0;
10884
10885       // If we already needed a PHI for an earlier operand, and another operand
10886       // also requires a PHI, we'd be introducing more PHIs than we're
10887       // eliminating, which increases register pressure on entry to the PHI's
10888       // block.
10889       if (NeededPhi)
10890         return 0;
10891
10892       FixedOperands[op] = 0;  // Needs a PHI.
10893       NeededPhi = true;
10894     }
10895   }
10896   
10897   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10898   // bother doing this transformation.  At best, this will just save a bit of
10899   // offset calculation, but all the predecessors will have to materialize the
10900   // stack address into a register anyway.  We'd actually rather *clone* the
10901   // load up into the predecessors so that we have a load of a gep of an alloca,
10902   // which can usually all be folded into the load.
10903   if (AllBasePointersAreAllocas)
10904     return 0;
10905   
10906   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10907   // that is variable.
10908   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10909   
10910   bool HasAnyPHIs = false;
10911   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10912     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10913     Value *FirstOp = FirstInst->getOperand(i);
10914     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10915                                      FirstOp->getName()+".pn");
10916     InsertNewInstBefore(NewPN, PN);
10917     
10918     NewPN->reserveOperandSpace(e);
10919     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10920     OperandPhis[i] = NewPN;
10921     FixedOperands[i] = NewPN;
10922     HasAnyPHIs = true;
10923   }
10924
10925   
10926   // Add all operands to the new PHIs.
10927   if (HasAnyPHIs) {
10928     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10929       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10930       BasicBlock *InBB = PN.getIncomingBlock(i);
10931       
10932       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10933         if (PHINode *OpPhi = OperandPhis[op])
10934           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10935     }
10936   }
10937   
10938   Value *Base = FixedOperands[0];
10939   return cast<GEPOperator>(FirstInst)->isInBounds() ?
10940     GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10941                                       FixedOperands.end()) :
10942     GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10943                               FixedOperands.end());
10944 }
10945
10946
10947 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10948 /// sink the load out of the block that defines it.  This means that it must be
10949 /// obvious the value of the load is not changed from the point of the load to
10950 /// the end of the block it is in.
10951 ///
10952 /// Finally, it is safe, but not profitable, to sink a load targetting a
10953 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10954 /// to a register.
10955 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10956   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10957   
10958   for (++BBI; BBI != E; ++BBI)
10959     if (BBI->mayWriteToMemory())
10960       return false;
10961   
10962   // Check for non-address taken alloca.  If not address-taken already, it isn't
10963   // profitable to do this xform.
10964   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10965     bool isAddressTaken = false;
10966     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10967          UI != E; ++UI) {
10968       if (isa<LoadInst>(UI)) continue;
10969       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10970         // If storing TO the alloca, then the address isn't taken.
10971         if (SI->getOperand(1) == AI) continue;
10972       }
10973       isAddressTaken = true;
10974       break;
10975     }
10976     
10977     if (!isAddressTaken && AI->isStaticAlloca())
10978       return false;
10979   }
10980   
10981   // If this load is a load from a GEP with a constant offset from an alloca,
10982   // then we don't want to sink it.  In its present form, it will be
10983   // load [constant stack offset].  Sinking it will cause us to have to
10984   // materialize the stack addresses in each predecessor in a register only to
10985   // do a shared load from register in the successor.
10986   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10987     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10988       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10989         return false;
10990   
10991   return true;
10992 }
10993
10994 Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
10995   LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
10996   
10997   // When processing loads, we need to propagate two bits of information to the
10998   // sunk load: whether it is volatile, and what its alignment is.  We currently
10999   // don't sink loads when some have their alignment specified and some don't.
11000   // visitLoadInst will propagate an alignment onto the load when TD is around,
11001   // and if TD isn't around, we can't handle the mixed case.
11002   bool isVolatile = FirstLI->isVolatile();
11003   unsigned LoadAlignment = FirstLI->getAlignment();
11004   
11005   // We can't sink the load if the loaded value could be modified between the
11006   // load and the PHI.
11007   if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
11008       !isSafeAndProfitableToSinkLoad(FirstLI))
11009     return 0;
11010   
11011   // If the PHI is of volatile loads and the load block has multiple
11012   // successors, sinking it would remove a load of the volatile value from
11013   // the path through the other successor.
11014   if (isVolatile && 
11015       FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
11016     return 0;
11017   
11018   // Check to see if all arguments are the same operation.
11019   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11020     LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
11021     if (!LI || !LI->hasOneUse())
11022       return 0;
11023     
11024     // We can't sink the load if the loaded value could be modified between 
11025     // the load and the PHI.
11026     if (LI->isVolatile() != isVolatile ||
11027         LI->getParent() != PN.getIncomingBlock(i) ||
11028         !isSafeAndProfitableToSinkLoad(LI))
11029       return 0;
11030       
11031     // If some of the loads have an alignment specified but not all of them,
11032     // we can't do the transformation.
11033     if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
11034       return 0;
11035     
11036     LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
11037     
11038     // If the PHI is of volatile loads and the load block has multiple
11039     // successors, sinking it would remove a load of the volatile value from
11040     // the path through the other successor.
11041     if (isVolatile &&
11042         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
11043       return 0;
11044   }
11045   
11046   // Okay, they are all the same operation.  Create a new PHI node of the
11047   // correct type, and PHI together all of the LHS's of the instructions.
11048   PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
11049                                    PN.getName()+".in");
11050   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
11051   
11052   Value *InVal = FirstLI->getOperand(0);
11053   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
11054   
11055   // Add all operands to the new PHI.
11056   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11057     Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
11058     if (NewInVal != InVal)
11059       InVal = 0;
11060     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11061   }
11062   
11063   Value *PhiVal;
11064   if (InVal) {
11065     // The new PHI unions all of the same values together.  This is really
11066     // common, so we handle it intelligently here for compile-time speed.
11067     PhiVal = InVal;
11068     delete NewPN;
11069   } else {
11070     InsertNewInstBefore(NewPN, PN);
11071     PhiVal = NewPN;
11072   }
11073   
11074   // If this was a volatile load that we are merging, make sure to loop through
11075   // and mark all the input loads as non-volatile.  If we don't do this, we will
11076   // insert a new volatile load and the old ones will not be deletable.
11077   if (isVolatile)
11078     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
11079       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
11080   
11081   return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
11082 }
11083
11084
11085
11086 /// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
11087 /// operator and they all are only used by the PHI, PHI together their
11088 /// inputs, and do the operation once, to the result of the PHI.
11089 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
11090   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
11091
11092   if (isa<GetElementPtrInst>(FirstInst))
11093     return FoldPHIArgGEPIntoPHI(PN);
11094   if (isa<LoadInst>(FirstInst))
11095     return FoldPHIArgLoadIntoPHI(PN);
11096   
11097   // Scan the instruction, looking for input operations that can be folded away.
11098   // If all input operands to the phi are the same instruction (e.g. a cast from
11099   // the same type or "+42") we can pull the operation through the PHI, reducing
11100   // code size and simplifying code.
11101   Constant *ConstantOp = 0;
11102   const Type *CastSrcTy = 0;
11103   
11104   if (isa<CastInst>(FirstInst)) {
11105     CastSrcTy = FirstInst->getOperand(0)->getType();
11106
11107     // Be careful about transforming integer PHIs.  We don't want to pessimize
11108     // the code by turning an i32 into an i1293.
11109     if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
11110       if (!ShouldChangeType(PN.getType(), CastSrcTy, TD))
11111         return 0;
11112     }
11113   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
11114     // Can fold binop, compare or shift here if the RHS is a constant, 
11115     // otherwise call FoldPHIArgBinOpIntoPHI.
11116     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
11117     if (ConstantOp == 0)
11118       return FoldPHIArgBinOpIntoPHI(PN);
11119   } else {
11120     return 0;  // Cannot fold this operation.
11121   }
11122
11123   // Check to see if all arguments are the same operation.
11124   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11125     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
11126     if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
11127       return 0;
11128     if (CastSrcTy) {
11129       if (I->getOperand(0)->getType() != CastSrcTy)
11130         return 0;  // Cast operation must match.
11131     } else if (I->getOperand(1) != ConstantOp) {
11132       return 0;
11133     }
11134   }
11135
11136   // Okay, they are all the same operation.  Create a new PHI node of the
11137   // correct type, and PHI together all of the LHS's of the instructions.
11138   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
11139                                    PN.getName()+".in");
11140   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
11141
11142   Value *InVal = FirstInst->getOperand(0);
11143   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
11144
11145   // Add all operands to the new PHI.
11146   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11147     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
11148     if (NewInVal != InVal)
11149       InVal = 0;
11150     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11151   }
11152
11153   Value *PhiVal;
11154   if (InVal) {
11155     // The new PHI unions all of the same values together.  This is really
11156     // common, so we handle it intelligently here for compile-time speed.
11157     PhiVal = InVal;
11158     delete NewPN;
11159   } else {
11160     InsertNewInstBefore(NewPN, PN);
11161     PhiVal = NewPN;
11162   }
11163
11164   // Insert and return the new operation.
11165   if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
11166     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
11167   
11168   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
11169     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
11170   
11171   CmpInst *CIOp = cast<CmpInst>(FirstInst);
11172   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
11173                          PhiVal, ConstantOp);
11174 }
11175
11176 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
11177 /// that is dead.
11178 static bool DeadPHICycle(PHINode *PN,
11179                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
11180   if (PN->use_empty()) return true;
11181   if (!PN->hasOneUse()) return false;
11182
11183   // Remember this node, and if we find the cycle, return.
11184   if (!PotentiallyDeadPHIs.insert(PN))
11185     return true;
11186   
11187   // Don't scan crazily complex things.
11188   if (PotentiallyDeadPHIs.size() == 16)
11189     return false;
11190
11191   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
11192     return DeadPHICycle(PU, PotentiallyDeadPHIs);
11193
11194   return false;
11195 }
11196
11197 /// PHIsEqualValue - Return true if this phi node is always equal to
11198 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
11199 ///   z = some value; x = phi (y, z); y = phi (x, z)
11200 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
11201                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
11202   // See if we already saw this PHI node.
11203   if (!ValueEqualPHIs.insert(PN))
11204     return true;
11205   
11206   // Don't scan crazily complex things.
11207   if (ValueEqualPHIs.size() == 16)
11208     return false;
11209  
11210   // Scan the operands to see if they are either phi nodes or are equal to
11211   // the value.
11212   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11213     Value *Op = PN->getIncomingValue(i);
11214     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
11215       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
11216         return false;
11217     } else if (Op != NonPhiInVal)
11218       return false;
11219   }
11220   
11221   return true;
11222 }
11223
11224
11225 namespace {
11226 struct PHIUsageRecord {
11227   unsigned PHIId;     // The ID # of the PHI (something determinstic to sort on)
11228   unsigned Shift;     // The amount shifted.
11229   Instruction *Inst;  // The trunc instruction.
11230   
11231   PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
11232     : PHIId(pn), Shift(Sh), Inst(User) {}
11233   
11234   bool operator<(const PHIUsageRecord &RHS) const {
11235     if (PHIId < RHS.PHIId) return true;
11236     if (PHIId > RHS.PHIId) return false;
11237     if (Shift < RHS.Shift) return true;
11238     if (Shift > RHS.Shift) return false;
11239     return Inst->getType()->getPrimitiveSizeInBits() <
11240            RHS.Inst->getType()->getPrimitiveSizeInBits();
11241   }
11242 };
11243   
11244 struct LoweredPHIRecord {
11245   PHINode *PN;        // The PHI that was lowered.
11246   unsigned Shift;     // The amount shifted.
11247   unsigned Width;     // The width extracted.
11248   
11249   LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
11250     : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
11251   
11252   // Ctor form used by DenseMap.
11253   LoweredPHIRecord(PHINode *pn, unsigned Sh)
11254     : PN(pn), Shift(Sh), Width(0) {}
11255 };
11256 }
11257
11258 namespace llvm {
11259   template<>
11260   struct DenseMapInfo<LoweredPHIRecord> {
11261     static inline LoweredPHIRecord getEmptyKey() {
11262       return LoweredPHIRecord(0, 0);
11263     }
11264     static inline LoweredPHIRecord getTombstoneKey() {
11265       return LoweredPHIRecord(0, 1);
11266     }
11267     static unsigned getHashValue(const LoweredPHIRecord &Val) {
11268       return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
11269              (Val.Width>>3);
11270     }
11271     static bool isEqual(const LoweredPHIRecord &LHS,
11272                         const LoweredPHIRecord &RHS) {
11273       return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
11274              LHS.Width == RHS.Width;
11275     }
11276   };
11277   template <>
11278   struct isPodLike<LoweredPHIRecord> { static const bool value = true; };
11279 }
11280
11281
11282 /// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
11283 /// illegal type: see if it is only used by trunc or trunc(lshr) operations.  If
11284 /// so, we split the PHI into the various pieces being extracted.  This sort of
11285 /// thing is introduced when SROA promotes an aggregate to large integer values.
11286 ///
11287 /// TODO: The user of the trunc may be an bitcast to float/double/vector or an
11288 /// inttoptr.  We should produce new PHIs in the right type.
11289 ///
11290 Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
11291   // PHIUsers - Keep track of all of the truncated values extracted from a set
11292   // of PHIs, along with their offset.  These are the things we want to rewrite.
11293   SmallVector<PHIUsageRecord, 16> PHIUsers;
11294   
11295   // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
11296   // nodes which are extracted from. PHIsToSlice is a set we use to avoid
11297   // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
11298   // check the uses of (to ensure they are all extracts).
11299   SmallVector<PHINode*, 8> PHIsToSlice;
11300   SmallPtrSet<PHINode*, 8> PHIsInspected;
11301   
11302   PHIsToSlice.push_back(&FirstPhi);
11303   PHIsInspected.insert(&FirstPhi);
11304   
11305   for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
11306     PHINode *PN = PHIsToSlice[PHIId];
11307     
11308     // Scan the input list of the PHI.  If any input is an invoke, and if the
11309     // input is defined in the predecessor, then we won't be split the critical
11310     // edge which is required to insert a truncate.  Because of this, we have to
11311     // bail out.
11312     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11313       InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
11314       if (II == 0) continue;
11315       if (II->getParent() != PN->getIncomingBlock(i))
11316         continue;
11317      
11318       // If we have a phi, and if it's directly in the predecessor, then we have
11319       // a critical edge where we need to put the truncate.  Since we can't
11320       // split the edge in instcombine, we have to bail out.
11321       return 0;
11322     }
11323       
11324     
11325     for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
11326          UI != E; ++UI) {
11327       Instruction *User = cast<Instruction>(*UI);
11328       
11329       // If the user is a PHI, inspect its uses recursively.
11330       if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
11331         if (PHIsInspected.insert(UserPN))
11332           PHIsToSlice.push_back(UserPN);
11333         continue;
11334       }
11335       
11336       // Truncates are always ok.
11337       if (isa<TruncInst>(User)) {
11338         PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
11339         continue;
11340       }
11341       
11342       // Otherwise it must be a lshr which can only be used by one trunc.
11343       if (User->getOpcode() != Instruction::LShr ||
11344           !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
11345           !isa<ConstantInt>(User->getOperand(1)))
11346         return 0;
11347       
11348       unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
11349       PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
11350     }
11351   }
11352   
11353   // If we have no users, they must be all self uses, just nuke the PHI.
11354   if (PHIUsers.empty())
11355     return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
11356   
11357   // If this phi node is transformable, create new PHIs for all the pieces
11358   // extracted out of it.  First, sort the users by their offset and size.
11359   array_pod_sort(PHIUsers.begin(), PHIUsers.end());
11360   
11361   DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
11362             for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11363               errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
11364         );
11365   
11366   // PredValues - This is a temporary used when rewriting PHI nodes.  It is
11367   // hoisted out here to avoid construction/destruction thrashing.
11368   DenseMap<BasicBlock*, Value*> PredValues;
11369   
11370   // ExtractedVals - Each new PHI we introduce is saved here so we don't
11371   // introduce redundant PHIs.
11372   DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
11373   
11374   for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
11375     unsigned PHIId = PHIUsers[UserI].PHIId;
11376     PHINode *PN = PHIsToSlice[PHIId];
11377     unsigned Offset = PHIUsers[UserI].Shift;
11378     const Type *Ty = PHIUsers[UserI].Inst->getType();
11379     
11380     PHINode *EltPHI;
11381     
11382     // If we've already lowered a user like this, reuse the previously lowered
11383     // value.
11384     if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
11385       
11386       // Otherwise, Create the new PHI node for this user.
11387       EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
11388       assert(EltPHI->getType() != PN->getType() &&
11389              "Truncate didn't shrink phi?");
11390     
11391       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11392         BasicBlock *Pred = PN->getIncomingBlock(i);
11393         Value *&PredVal = PredValues[Pred];
11394         
11395         // If we already have a value for this predecessor, reuse it.
11396         if (PredVal) {
11397           EltPHI->addIncoming(PredVal, Pred);
11398           continue;
11399         }
11400
11401         // Handle the PHI self-reuse case.
11402         Value *InVal = PN->getIncomingValue(i);
11403         if (InVal == PN) {
11404           PredVal = EltPHI;
11405           EltPHI->addIncoming(PredVal, Pred);
11406           continue;
11407         }
11408         
11409         if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
11410           // If the incoming value was a PHI, and if it was one of the PHIs we
11411           // already rewrote it, just use the lowered value.
11412           if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
11413             PredVal = Res;
11414             EltPHI->addIncoming(PredVal, Pred);
11415             continue;
11416           }
11417         }
11418         
11419         // Otherwise, do an extract in the predecessor.
11420         Builder->SetInsertPoint(Pred, Pred->getTerminator());
11421         Value *Res = InVal;
11422         if (Offset)
11423           Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
11424                                                           Offset), "extract");
11425         Res = Builder->CreateTrunc(Res, Ty, "extract.t");
11426         PredVal = Res;
11427         EltPHI->addIncoming(Res, Pred);
11428         
11429         // If the incoming value was a PHI, and if it was one of the PHIs we are
11430         // rewriting, we will ultimately delete the code we inserted.  This
11431         // means we need to revisit that PHI to make sure we extract out the
11432         // needed piece.
11433         if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
11434           if (PHIsInspected.count(OldInVal)) {
11435             unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
11436                                           OldInVal)-PHIsToSlice.begin();
11437             PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset, 
11438                                               cast<Instruction>(Res)));
11439             ++UserE;
11440           }
11441       }
11442       PredValues.clear();
11443       
11444       DEBUG(errs() << "  Made element PHI for offset " << Offset << ": "
11445                    << *EltPHI << '\n');
11446       ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
11447     }
11448     
11449     // Replace the use of this piece with the PHI node.
11450     ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
11451   }
11452   
11453   // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
11454   // with undefs.
11455   Value *Undef = UndefValue::get(FirstPhi.getType());
11456   for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11457     ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
11458   return ReplaceInstUsesWith(FirstPhi, Undef);
11459 }
11460
11461 // PHINode simplification
11462 //
11463 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
11464   // If LCSSA is around, don't mess with Phi nodes
11465   if (MustPreserveLCSSA) return 0;
11466   
11467   if (Value *V = PN.hasConstantValue())
11468     return ReplaceInstUsesWith(PN, V);
11469
11470   // If all PHI operands are the same operation, pull them through the PHI,
11471   // reducing code size.
11472   if (isa<Instruction>(PN.getIncomingValue(0)) &&
11473       isa<Instruction>(PN.getIncomingValue(1)) &&
11474       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
11475       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
11476       // FIXME: The hasOneUse check will fail for PHIs that use the value more
11477       // than themselves more than once.
11478       PN.getIncomingValue(0)->hasOneUse())
11479     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
11480       return Result;
11481
11482   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
11483   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
11484   // PHI)... break the cycle.
11485   if (PN.hasOneUse()) {
11486     Instruction *PHIUser = cast<Instruction>(PN.use_back());
11487     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
11488       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
11489       PotentiallyDeadPHIs.insert(&PN);
11490       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
11491         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
11492     }
11493    
11494     // If this phi has a single use, and if that use just computes a value for
11495     // the next iteration of a loop, delete the phi.  This occurs with unused
11496     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
11497     // common case here is good because the only other things that catch this
11498     // are induction variable analysis (sometimes) and ADCE, which is only run
11499     // late.
11500     if (PHIUser->hasOneUse() &&
11501         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
11502         PHIUser->use_back() == &PN) {
11503       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
11504     }
11505   }
11506
11507   // We sometimes end up with phi cycles that non-obviously end up being the
11508   // same value, for example:
11509   //   z = some value; x = phi (y, z); y = phi (x, z)
11510   // where the phi nodes don't necessarily need to be in the same block.  Do a
11511   // quick check to see if the PHI node only contains a single non-phi value, if
11512   // so, scan to see if the phi cycle is actually equal to that value.
11513   {
11514     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
11515     // Scan for the first non-phi operand.
11516     while (InValNo != NumOperandVals && 
11517            isa<PHINode>(PN.getIncomingValue(InValNo)))
11518       ++InValNo;
11519
11520     if (InValNo != NumOperandVals) {
11521       Value *NonPhiInVal = PN.getOperand(InValNo);
11522       
11523       // Scan the rest of the operands to see if there are any conflicts, if so
11524       // there is no need to recursively scan other phis.
11525       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11526         Value *OpVal = PN.getIncomingValue(InValNo);
11527         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11528           break;
11529       }
11530       
11531       // If we scanned over all operands, then we have one unique value plus
11532       // phi values.  Scan PHI nodes to see if they all merge in each other or
11533       // the value.
11534       if (InValNo == NumOperandVals) {
11535         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11536         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11537           return ReplaceInstUsesWith(PN, NonPhiInVal);
11538       }
11539     }
11540   }
11541
11542   // If there are multiple PHIs, sort their operands so that they all list
11543   // the blocks in the same order. This will help identical PHIs be eliminated
11544   // by other passes. Other passes shouldn't depend on this for correctness
11545   // however.
11546   PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
11547   if (&PN != FirstPN)
11548     for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
11549       BasicBlock *BBA = PN.getIncomingBlock(i);
11550       BasicBlock *BBB = FirstPN->getIncomingBlock(i);
11551       if (BBA != BBB) {
11552         Value *VA = PN.getIncomingValue(i);
11553         unsigned j = PN.getBasicBlockIndex(BBB);
11554         Value *VB = PN.getIncomingValue(j);
11555         PN.setIncomingBlock(i, BBB);
11556         PN.setIncomingValue(i, VB);
11557         PN.setIncomingBlock(j, BBA);
11558         PN.setIncomingValue(j, VA);
11559         // NOTE: Instcombine normally would want us to "return &PN" if we
11560         // modified any of the operands of an instruction.  However, since we
11561         // aren't adding or removing uses (just rearranging them) we don't do
11562         // this in this case.
11563       }
11564     }
11565
11566   // If this is an integer PHI and we know that it has an illegal type, see if
11567   // it is only used by trunc or trunc(lshr) operations.  If so, we split the
11568   // PHI into the various pieces being extracted.  This sort of thing is
11569   // introduced when SROA promotes an aggregate to a single large integer type.
11570   if (isa<IntegerType>(PN.getType()) && TD &&
11571       !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
11572     if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
11573       return Res;
11574   
11575   return 0;
11576 }
11577
11578 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
11579   SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
11580
11581   if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
11582     return ReplaceInstUsesWith(GEP, V);
11583
11584   Value *PtrOp = GEP.getOperand(0);
11585
11586   if (isa<UndefValue>(GEP.getOperand(0)))
11587     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
11588
11589   // Eliminate unneeded casts for indices.
11590   if (TD) {
11591     bool MadeChange = false;
11592     unsigned PtrSize = TD->getPointerSizeInBits();
11593     
11594     gep_type_iterator GTI = gep_type_begin(GEP);
11595     for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11596          I != E; ++I, ++GTI) {
11597       if (!isa<SequentialType>(*GTI)) continue;
11598       
11599       // If we are using a wider index than needed for this platform, shrink it
11600       // to what we need.  If narrower, sign-extend it to what we need.  This
11601       // explicit cast can make subsequent optimizations more obvious.
11602       unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
11603       if (OpBits == PtrSize)
11604         continue;
11605       
11606       *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
11607       MadeChange = true;
11608     }
11609     if (MadeChange) return &GEP;
11610   }
11611
11612   // Combine Indices - If the source pointer to this getelementptr instruction
11613   // is a getelementptr instruction, combine the indices of the two
11614   // getelementptr instructions into a single instruction.
11615   //
11616   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
11617     // Note that if our source is a gep chain itself that we wait for that
11618     // chain to be resolved before we perform this transformation.  This
11619     // avoids us creating a TON of code in some cases.
11620     //
11621     if (GetElementPtrInst *SrcGEP =
11622           dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11623       if (SrcGEP->getNumOperands() == 2)
11624         return 0;   // Wait until our source is folded to completion.
11625
11626     SmallVector<Value*, 8> Indices;
11627
11628     // Find out whether the last index in the source GEP is a sequential idx.
11629     bool EndsWithSequential = false;
11630     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11631          I != E; ++I)
11632       EndsWithSequential = !isa<StructType>(*I);
11633
11634     // Can we combine the two pointer arithmetics offsets?
11635     if (EndsWithSequential) {
11636       // Replace: gep (gep %P, long B), long A, ...
11637       // With:    T = long A+B; gep %P, T, ...
11638       //
11639       Value *Sum;
11640       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11641       Value *GO1 = GEP.getOperand(1);
11642       if (SO1 == Constant::getNullValue(SO1->getType())) {
11643         Sum = GO1;
11644       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
11645         Sum = SO1;
11646       } else {
11647         // If they aren't the same type, then the input hasn't been processed
11648         // by the loop above yet (which canonicalizes sequential index types to
11649         // intptr_t).  Just avoid transforming this until the input has been
11650         // normalized.
11651         if (SO1->getType() != GO1->getType())
11652           return 0;
11653         Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11654       }
11655
11656       // Update the GEP in place if possible.
11657       if (Src->getNumOperands() == 2) {
11658         GEP.setOperand(0, Src->getOperand(0));
11659         GEP.setOperand(1, Sum);
11660         return &GEP;
11661       }
11662       Indices.append(Src->op_begin()+1, Src->op_end()-1);
11663       Indices.push_back(Sum);
11664       Indices.append(GEP.op_begin()+2, GEP.op_end());
11665     } else if (isa<Constant>(*GEP.idx_begin()) &&
11666                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11667                Src->getNumOperands() != 1) {
11668       // Otherwise we can do the fold if the first index of the GEP is a zero
11669       Indices.append(Src->op_begin()+1, Src->op_end());
11670       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
11671     }
11672
11673     if (!Indices.empty())
11674       return (cast<GEPOperator>(&GEP)->isInBounds() &&
11675               Src->isInBounds()) ?
11676         GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11677                                           Indices.end(), GEP.getName()) :
11678         GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
11679                                   Indices.end(), GEP.getName());
11680   }
11681   
11682   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11683   if (Value *X = getBitCastOperand(PtrOp)) {
11684     assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
11685
11686     // If the input bitcast is actually "bitcast(bitcast(x))", then we don't 
11687     // want to change the gep until the bitcasts are eliminated.
11688     if (getBitCastOperand(X)) {
11689       Worklist.AddValue(PtrOp);
11690       return 0;
11691     }
11692     
11693     bool HasZeroPointerIndex = false;
11694     if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
11695       HasZeroPointerIndex = C->isZero();
11696     
11697     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11698     // into     : GEP [10 x i8]* X, i32 0, ...
11699     //
11700     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11701     //           into     : GEP i8* X, ...
11702     // 
11703     // This occurs when the program declares an array extern like "int X[];"
11704     if (HasZeroPointerIndex) {
11705       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11706       const PointerType *XTy = cast<PointerType>(X->getType());
11707       if (const ArrayType *CATy =
11708           dyn_cast<ArrayType>(CPTy->getElementType())) {
11709         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11710         if (CATy->getElementType() == XTy->getElementType()) {
11711           // -> GEP i8* X, ...
11712           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11713           return cast<GEPOperator>(&GEP)->isInBounds() ?
11714             GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11715                                               GEP.getName()) :
11716             GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11717                                       GEP.getName());
11718         }
11719         
11720         if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
11721           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11722           if (CATy->getElementType() == XATy->getElementType()) {
11723             // -> GEP [10 x i8]* X, i32 0, ...
11724             // At this point, we know that the cast source type is a pointer
11725             // to an array of the same type as the destination pointer
11726             // array.  Because the array type is never stepped over (there
11727             // is a leading zero) we can fold the cast into this GEP.
11728             GEP.setOperand(0, X);
11729             return &GEP;
11730           }
11731         }
11732       }
11733     } else if (GEP.getNumOperands() == 2) {
11734       // Transform things like:
11735       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11736       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11737       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11738       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11739       if (TD && isa<ArrayType>(SrcElTy) &&
11740           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11741           TD->getTypeAllocSize(ResElTy)) {
11742         Value *Idx[2];
11743         Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11744         Idx[1] = GEP.getOperand(1);
11745         Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11746           Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11747           Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11748         // V and GEP are both pointer types --> BitCast
11749         return new BitCastInst(NewGEP, GEP.getType());
11750       }
11751       
11752       // Transform things like:
11753       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11754       //   (where tmp = 8*tmp2) into:
11755       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11756       
11757       if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
11758         uint64_t ArrayEltSize =
11759             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11760         
11761         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11762         // allow either a mul, shift, or constant here.
11763         Value *NewIdx = 0;
11764         ConstantInt *Scale = 0;
11765         if (ArrayEltSize == 1) {
11766           NewIdx = GEP.getOperand(1);
11767           Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11768         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11769           NewIdx = ConstantInt::get(CI->getType(), 1);
11770           Scale = CI;
11771         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11772           if (Inst->getOpcode() == Instruction::Shl &&
11773               isa<ConstantInt>(Inst->getOperand(1))) {
11774             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11775             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11776             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11777                                      1ULL << ShAmtVal);
11778             NewIdx = Inst->getOperand(0);
11779           } else if (Inst->getOpcode() == Instruction::Mul &&
11780                      isa<ConstantInt>(Inst->getOperand(1))) {
11781             Scale = cast<ConstantInt>(Inst->getOperand(1));
11782             NewIdx = Inst->getOperand(0);
11783           }
11784         }
11785         
11786         // If the index will be to exactly the right offset with the scale taken
11787         // out, perform the transformation. Note, we don't know whether Scale is
11788         // signed or not. We'll use unsigned version of division/modulo
11789         // operation after making sure Scale doesn't have the sign bit set.
11790         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11791             Scale->getZExtValue() % ArrayEltSize == 0) {
11792           Scale = ConstantInt::get(Scale->getType(),
11793                                    Scale->getZExtValue() / ArrayEltSize);
11794           if (Scale->getZExtValue() != 1) {
11795             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11796                                                        false /*ZExt*/);
11797             NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
11798           }
11799
11800           // Insert the new GEP instruction.
11801           Value *Idx[2];
11802           Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11803           Idx[1] = NewIdx;
11804           Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11805             Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11806             Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11807           // The NewGEP must be pointer typed, so must the old one -> BitCast
11808           return new BitCastInst(NewGEP, GEP.getType());
11809         }
11810       }
11811     }
11812   }
11813   
11814   /// See if we can simplify:
11815   ///   X = bitcast A* to B*
11816   ///   Y = gep X, <...constant indices...>
11817   /// into a gep of the original struct.  This is important for SROA and alias
11818   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11819   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11820     if (TD &&
11821         !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11822       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11823       // a constant back from EmitGEPOffset.
11824       ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, *this));
11825       int64_t Offset = OffsetV->getSExtValue();
11826       
11827       // If this GEP instruction doesn't move the pointer, just replace the GEP
11828       // with a bitcast of the real input to the dest type.
11829       if (Offset == 0) {
11830         // If the bitcast is of an allocation, and the allocation will be
11831         // converted to match the type of the cast, don't touch this.
11832         if (isa<AllocaInst>(BCI->getOperand(0)) ||
11833             isMalloc(BCI->getOperand(0))) {
11834           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11835           if (Instruction *I = visitBitCast(*BCI)) {
11836             if (I != BCI) {
11837               I->takeName(BCI);
11838               BCI->getParent()->getInstList().insert(BCI, I);
11839               ReplaceInstUsesWith(*BCI, I);
11840             }
11841             return &GEP;
11842           }
11843         }
11844         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11845       }
11846       
11847       // Otherwise, if the offset is non-zero, we need to find out if there is a
11848       // field at Offset in 'A's type.  If so, we can pull the cast through the
11849       // GEP.
11850       SmallVector<Value*, 8> NewIndices;
11851       const Type *InTy =
11852         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11853       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11854         Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11855           Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11856                                      NewIndices.end()) :
11857           Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11858                              NewIndices.end());
11859         
11860         if (NGEP->getType() == GEP.getType())
11861           return ReplaceInstUsesWith(GEP, NGEP);
11862         NGEP->takeName(&GEP);
11863         return new BitCastInst(NGEP, GEP.getType());
11864       }
11865     }
11866   }    
11867     
11868   return 0;
11869 }
11870
11871 Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
11872   // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
11873   if (AI.isArrayAllocation()) {  // Check C != 1
11874     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11875       const Type *NewTy = 
11876         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11877       assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11878       AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
11879       New->setAlignment(AI.getAlignment());
11880
11881       // Scan to the end of the allocation instructions, to skip over a block of
11882       // allocas if possible...also skip interleaved debug info
11883       //
11884       BasicBlock::iterator It = New;
11885       while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11886
11887       // Now that I is pointing to the first non-allocation-inst in the block,
11888       // insert our getelementptr instruction...
11889       //
11890       Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
11891       Value *Idx[2];
11892       Idx[0] = NullIdx;
11893       Idx[1] = NullIdx;
11894       Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11895                                                    New->getName()+".sub", It);
11896
11897       // Now make everything use the getelementptr instead of the original
11898       // allocation.
11899       return ReplaceInstUsesWith(AI, V);
11900     } else if (isa<UndefValue>(AI.getArraySize())) {
11901       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11902     }
11903   }
11904
11905   if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11906     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11907     // Note that we only do this for alloca's, because malloc should allocate
11908     // and return a unique pointer, even for a zero byte allocation.
11909     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11910       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11911
11912     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11913     if (AI.getAlignment() == 0)
11914       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11915   }
11916
11917   return 0;
11918 }
11919
11920 Instruction *InstCombiner::visitFree(Instruction &FI) {
11921   Value *Op = FI.getOperand(1);
11922
11923   // free undef -> unreachable.
11924   if (isa<UndefValue>(Op)) {
11925     // Insert a new store to null because we cannot modify the CFG here.
11926     new StoreInst(ConstantInt::getTrue(*Context),
11927            UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
11928     return EraseInstFromFunction(FI);
11929   }
11930   
11931   // If we have 'free null' delete the instruction.  This can happen in stl code
11932   // when lots of inlining happens.
11933   if (isa<ConstantPointerNull>(Op))
11934     return EraseInstFromFunction(FI);
11935
11936   // If we have a malloc call whose only use is a free call, delete both.
11937   if (isMalloc(Op)) {
11938     if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11939       if (Op->hasOneUse() && CI->hasOneUse()) {
11940         EraseInstFromFunction(FI);
11941         EraseInstFromFunction(*CI);
11942         return EraseInstFromFunction(*cast<Instruction>(Op));
11943       }
11944     } else {
11945       // Op is a call to malloc
11946       if (Op->hasOneUse()) {
11947         EraseInstFromFunction(FI);
11948         return EraseInstFromFunction(*cast<Instruction>(Op));
11949       }
11950     }
11951   }
11952
11953   return 0;
11954 }
11955
11956 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11957 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11958                                         const TargetData *TD) {
11959   User *CI = cast<User>(LI.getOperand(0));
11960   Value *CastOp = CI->getOperand(0);
11961   LLVMContext *Context = IC.getContext();
11962
11963   const PointerType *DestTy = cast<PointerType>(CI->getType());
11964   const Type *DestPTy = DestTy->getElementType();
11965   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11966
11967     // If the address spaces don't match, don't eliminate the cast.
11968     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11969       return 0;
11970
11971     const Type *SrcPTy = SrcTy->getElementType();
11972
11973     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11974          isa<VectorType>(DestPTy)) {
11975       // If the source is an array, the code below will not succeed.  Check to
11976       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11977       // constants.
11978       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11979         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11980           if (ASrcTy->getNumElements() != 0) {
11981             Value *Idxs[2];
11982             Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11983             Idxs[1] = Idxs[0];
11984             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11985             SrcTy = cast<PointerType>(CastOp->getType());
11986             SrcPTy = SrcTy->getElementType();
11987           }
11988
11989       if (IC.getTargetData() &&
11990           (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11991             isa<VectorType>(SrcPTy)) &&
11992           // Do not allow turning this into a load of an integer, which is then
11993           // casted to a pointer, this pessimizes pointer analysis a lot.
11994           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11995           IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11996                IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11997
11998         // Okay, we are casting from one integer or pointer type to another of
11999         // the same size.  Instead of casting the pointer before the load, cast
12000         // the result of the loaded value.
12001         Value *NewLoad = 
12002           IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
12003         // Now cast the result of the load.
12004         return new BitCastInst(NewLoad, LI.getType());
12005       }
12006     }
12007   }
12008   return 0;
12009 }
12010
12011 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
12012   Value *Op = LI.getOperand(0);
12013
12014   // Attempt to improve the alignment.
12015   if (TD) {
12016     unsigned KnownAlign =
12017       GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
12018     if (KnownAlign >
12019         (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
12020                                   LI.getAlignment()))
12021       LI.setAlignment(KnownAlign);
12022   }
12023
12024   // load (cast X) --> cast (load X) iff safe.
12025   if (isa<CastInst>(Op))
12026     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
12027       return Res;
12028
12029   // None of the following transforms are legal for volatile loads.
12030   if (LI.isVolatile()) return 0;
12031   
12032   // Do really simple store-to-load forwarding and load CSE, to catch cases
12033   // where there are several consequtive memory accesses to the same location,
12034   // separated by a few arithmetic operations.
12035   BasicBlock::iterator BBI = &LI;
12036   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
12037     return ReplaceInstUsesWith(LI, AvailableVal);
12038
12039   // load(gep null, ...) -> unreachable
12040   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
12041     const Value *GEPI0 = GEPI->getOperand(0);
12042     // TODO: Consider a target hook for valid address spaces for this xform.
12043     if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
12044       // Insert a new store to null instruction before the load to indicate
12045       // that this code is not reachable.  We do this instead of inserting
12046       // an unreachable instruction directly because we cannot modify the
12047       // CFG.
12048       new StoreInst(UndefValue::get(LI.getType()),
12049                     Constant::getNullValue(Op->getType()), &LI);
12050       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
12051     }
12052   } 
12053
12054   // load null/undef -> unreachable
12055   // TODO: Consider a target hook for valid address spaces for this xform.
12056   if (isa<UndefValue>(Op) ||
12057       (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
12058     // Insert a new store to null instruction before the load to indicate that
12059     // this code is not reachable.  We do this instead of inserting an
12060     // unreachable instruction directly because we cannot modify the CFG.
12061     new StoreInst(UndefValue::get(LI.getType()),
12062                   Constant::getNullValue(Op->getType()), &LI);
12063     return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
12064   }
12065
12066   // Instcombine load (constantexpr_cast global) -> cast (load global)
12067   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
12068     if (CE->isCast())
12069       if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
12070         return Res;
12071   
12072   if (Op->hasOneUse()) {
12073     // Change select and PHI nodes to select values instead of addresses: this
12074     // helps alias analysis out a lot, allows many others simplifications, and
12075     // exposes redundancy in the code.
12076     //
12077     // Note that we cannot do the transformation unless we know that the
12078     // introduced loads cannot trap!  Something like this is valid as long as
12079     // the condition is always false: load (select bool %C, int* null, int* %G),
12080     // but it would not be valid if we transformed it to load from null
12081     // unconditionally.
12082     //
12083     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
12084       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
12085       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
12086           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
12087         Value *V1 = Builder->CreateLoad(SI->getOperand(1),
12088                                         SI->getOperand(1)->getName()+".val");
12089         Value *V2 = Builder->CreateLoad(SI->getOperand(2),
12090                                         SI->getOperand(2)->getName()+".val");
12091         return SelectInst::Create(SI->getCondition(), V1, V2);
12092       }
12093
12094       // load (select (cond, null, P)) -> load P
12095       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
12096         if (C->isNullValue()) {
12097           LI.setOperand(0, SI->getOperand(2));
12098           return &LI;
12099         }
12100
12101       // load (select (cond, P, null)) -> load P
12102       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
12103         if (C->isNullValue()) {
12104           LI.setOperand(0, SI->getOperand(1));
12105           return &LI;
12106         }
12107     }
12108   }
12109   return 0;
12110 }
12111
12112 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
12113 /// when possible.  This makes it generally easy to do alias analysis and/or
12114 /// SROA/mem2reg of the memory object.
12115 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
12116   User *CI = cast<User>(SI.getOperand(1));
12117   Value *CastOp = CI->getOperand(0);
12118
12119   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
12120   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
12121   if (SrcTy == 0) return 0;
12122   
12123   const Type *SrcPTy = SrcTy->getElementType();
12124
12125   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
12126     return 0;
12127   
12128   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
12129   /// to its first element.  This allows us to handle things like:
12130   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
12131   /// on 32-bit hosts.
12132   SmallVector<Value*, 4> NewGEPIndices;
12133   
12134   // If the source is an array, the code below will not succeed.  Check to
12135   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
12136   // constants.
12137   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
12138     // Index through pointer.
12139     Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
12140     NewGEPIndices.push_back(Zero);
12141     
12142     while (1) {
12143       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
12144         if (!STy->getNumElements()) /* Struct can be empty {} */
12145           break;
12146         NewGEPIndices.push_back(Zero);
12147         SrcPTy = STy->getElementType(0);
12148       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
12149         NewGEPIndices.push_back(Zero);
12150         SrcPTy = ATy->getElementType();
12151       } else {
12152         break;
12153       }
12154     }
12155     
12156     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
12157   }
12158
12159   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
12160     return 0;
12161   
12162   // If the pointers point into different address spaces or if they point to
12163   // values with different sizes, we can't do the transformation.
12164   if (!IC.getTargetData() ||
12165       SrcTy->getAddressSpace() != 
12166         cast<PointerType>(CI->getType())->getAddressSpace() ||
12167       IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
12168       IC.getTargetData()->getTypeSizeInBits(DestPTy))
12169     return 0;
12170
12171   // Okay, we are casting from one integer or pointer type to another of
12172   // the same size.  Instead of casting the pointer before 
12173   // the store, cast the value to be stored.
12174   Value *NewCast;
12175   Value *SIOp0 = SI.getOperand(0);
12176   Instruction::CastOps opcode = Instruction::BitCast;
12177   const Type* CastSrcTy = SIOp0->getType();
12178   const Type* CastDstTy = SrcPTy;
12179   if (isa<PointerType>(CastDstTy)) {
12180     if (CastSrcTy->isInteger())
12181       opcode = Instruction::IntToPtr;
12182   } else if (isa<IntegerType>(CastDstTy)) {
12183     if (isa<PointerType>(SIOp0->getType()))
12184       opcode = Instruction::PtrToInt;
12185   }
12186   
12187   // SIOp0 is a pointer to aggregate and this is a store to the first field,
12188   // emit a GEP to index into its first field.
12189   if (!NewGEPIndices.empty())
12190     CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
12191                                            NewGEPIndices.end());
12192   
12193   NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
12194                                    SIOp0->getName()+".c");
12195   return new StoreInst(NewCast, CastOp);
12196 }
12197
12198 /// equivalentAddressValues - Test if A and B will obviously have the same
12199 /// value. This includes recognizing that %t0 and %t1 will have the same
12200 /// value in code like this:
12201 ///   %t0 = getelementptr \@a, 0, 3
12202 ///   store i32 0, i32* %t0
12203 ///   %t1 = getelementptr \@a, 0, 3
12204 ///   %t2 = load i32* %t1
12205 ///
12206 static bool equivalentAddressValues(Value *A, Value *B) {
12207   // Test if the values are trivially equivalent.
12208   if (A == B) return true;
12209   
12210   // Test if the values come form identical arithmetic instructions.
12211   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
12212   // its only used to compare two uses within the same basic block, which
12213   // means that they'll always either have the same value or one of them
12214   // will have an undefined value.
12215   if (isa<BinaryOperator>(A) ||
12216       isa<CastInst>(A) ||
12217       isa<PHINode>(A) ||
12218       isa<GetElementPtrInst>(A))
12219     if (Instruction *BI = dyn_cast<Instruction>(B))
12220       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
12221         return true;
12222   
12223   // Otherwise they may not be equivalent.
12224   return false;
12225 }
12226
12227 // If this instruction has two uses, one of which is a llvm.dbg.declare,
12228 // return the llvm.dbg.declare.
12229 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
12230   if (!V->hasNUses(2))
12231     return 0;
12232   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
12233        UI != E; ++UI) {
12234     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
12235       return DI;
12236     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
12237       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
12238         return DI;
12239       }
12240   }
12241   return 0;
12242 }
12243
12244 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
12245   Value *Val = SI.getOperand(0);
12246   Value *Ptr = SI.getOperand(1);
12247
12248   // If the RHS is an alloca with a single use, zapify the store, making the
12249   // alloca dead.
12250   // If the RHS is an alloca with a two uses, the other one being a 
12251   // llvm.dbg.declare, zapify the store and the declare, making the
12252   // alloca dead.  We must do this to prevent declare's from affecting
12253   // codegen.
12254   if (!SI.isVolatile()) {
12255     if (Ptr->hasOneUse()) {
12256       if (isa<AllocaInst>(Ptr)) {
12257         EraseInstFromFunction(SI);
12258         ++NumCombined;
12259         return 0;
12260       }
12261       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
12262         if (isa<AllocaInst>(GEP->getOperand(0))) {
12263           if (GEP->getOperand(0)->hasOneUse()) {
12264             EraseInstFromFunction(SI);
12265             ++NumCombined;
12266             return 0;
12267           }
12268           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
12269             EraseInstFromFunction(*DI);
12270             EraseInstFromFunction(SI);
12271             ++NumCombined;
12272             return 0;
12273           }
12274         }
12275       }
12276     }
12277     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
12278       EraseInstFromFunction(*DI);
12279       EraseInstFromFunction(SI);
12280       ++NumCombined;
12281       return 0;
12282     }
12283   }
12284
12285   // Attempt to improve the alignment.
12286   if (TD) {
12287     unsigned KnownAlign =
12288       GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
12289     if (KnownAlign >
12290         (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
12291                                   SI.getAlignment()))
12292       SI.setAlignment(KnownAlign);
12293   }
12294
12295   // Do really simple DSE, to catch cases where there are several consecutive
12296   // stores to the same location, separated by a few arithmetic operations. This
12297   // situation often occurs with bitfield accesses.
12298   BasicBlock::iterator BBI = &SI;
12299   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
12300        --ScanInsts) {
12301     --BBI;
12302     // Don't count debug info directives, lest they affect codegen,
12303     // and we skip pointer-to-pointer bitcasts, which are NOPs.
12304     // It is necessary for correctness to skip those that feed into a
12305     // llvm.dbg.declare, as these are not present when debugging is off.
12306     if (isa<DbgInfoIntrinsic>(BBI) ||
12307         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12308       ScanInsts++;
12309       continue;
12310     }    
12311     
12312     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
12313       // Prev store isn't volatile, and stores to the same location?
12314       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
12315                                                           SI.getOperand(1))) {
12316         ++NumDeadStore;
12317         ++BBI;
12318         EraseInstFromFunction(*PrevSI);
12319         continue;
12320       }
12321       break;
12322     }
12323     
12324     // If this is a load, we have to stop.  However, if the loaded value is from
12325     // the pointer we're loading and is producing the pointer we're storing,
12326     // then *this* store is dead (X = load P; store X -> P).
12327     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
12328       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
12329           !SI.isVolatile()) {
12330         EraseInstFromFunction(SI);
12331         ++NumCombined;
12332         return 0;
12333       }
12334       // Otherwise, this is a load from some other location.  Stores before it
12335       // may not be dead.
12336       break;
12337     }
12338     
12339     // Don't skip over loads or things that can modify memory.
12340     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
12341       break;
12342   }
12343   
12344   
12345   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
12346
12347   // store X, null    -> turns into 'unreachable' in SimplifyCFG
12348   if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
12349     if (!isa<UndefValue>(Val)) {
12350       SI.setOperand(0, UndefValue::get(Val->getType()));
12351       if (Instruction *U = dyn_cast<Instruction>(Val))
12352         Worklist.Add(U);  // Dropped a use.
12353       ++NumCombined;
12354     }
12355     return 0;  // Do not modify these!
12356   }
12357
12358   // store undef, Ptr -> noop
12359   if (isa<UndefValue>(Val)) {
12360     EraseInstFromFunction(SI);
12361     ++NumCombined;
12362     return 0;
12363   }
12364
12365   // If the pointer destination is a cast, see if we can fold the cast into the
12366   // source instead.
12367   if (isa<CastInst>(Ptr))
12368     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12369       return Res;
12370   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
12371     if (CE->isCast())
12372       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12373         return Res;
12374
12375   
12376   // If this store is the last instruction in the basic block (possibly
12377   // excepting debug info instructions and the pointer bitcasts that feed
12378   // into them), and if the block ends with an unconditional branch, try
12379   // to move it to the successor block.
12380   BBI = &SI; 
12381   do {
12382     ++BBI;
12383   } while (isa<DbgInfoIntrinsic>(BBI) ||
12384            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
12385   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
12386     if (BI->isUnconditional())
12387       if (SimplifyStoreAtEndOfBlock(SI))
12388         return 0;  // xform done!
12389   
12390   return 0;
12391 }
12392
12393 /// SimplifyStoreAtEndOfBlock - Turn things like:
12394 ///   if () { *P = v1; } else { *P = v2 }
12395 /// into a phi node with a store in the successor.
12396 ///
12397 /// Simplify things like:
12398 ///   *P = v1; if () { *P = v2; }
12399 /// into a phi node with a store in the successor.
12400 ///
12401 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12402   BasicBlock *StoreBB = SI.getParent();
12403   
12404   // Check to see if the successor block has exactly two incoming edges.  If
12405   // so, see if the other predecessor contains a store to the same location.
12406   // if so, insert a PHI node (if needed) and move the stores down.
12407   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
12408   
12409   // Determine whether Dest has exactly two predecessors and, if so, compute
12410   // the other predecessor.
12411   pred_iterator PI = pred_begin(DestBB);
12412   BasicBlock *OtherBB = 0;
12413   if (*PI != StoreBB)
12414     OtherBB = *PI;
12415   ++PI;
12416   if (PI == pred_end(DestBB))
12417     return false;
12418   
12419   if (*PI != StoreBB) {
12420     if (OtherBB)
12421       return false;
12422     OtherBB = *PI;
12423   }
12424   if (++PI != pred_end(DestBB))
12425     return false;
12426
12427   // Bail out if all the relevant blocks aren't distinct (this can happen,
12428   // for example, if SI is in an infinite loop)
12429   if (StoreBB == DestBB || OtherBB == DestBB)
12430     return false;
12431
12432   // Verify that the other block ends in a branch and is not otherwise empty.
12433   BasicBlock::iterator BBI = OtherBB->getTerminator();
12434   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12435   if (!OtherBr || BBI == OtherBB->begin())
12436     return false;
12437   
12438   // If the other block ends in an unconditional branch, check for the 'if then
12439   // else' case.  there is an instruction before the branch.
12440   StoreInst *OtherStore = 0;
12441   if (OtherBr->isUnconditional()) {
12442     --BBI;
12443     // Skip over debugging info.
12444     while (isa<DbgInfoIntrinsic>(BBI) ||
12445            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12446       if (BBI==OtherBB->begin())
12447         return false;
12448       --BBI;
12449     }
12450     // If this isn't a store, isn't a store to the same location, or if the
12451     // alignments differ, bail out.
12452     OtherStore = dyn_cast<StoreInst>(BBI);
12453     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
12454         OtherStore->getAlignment() != SI.getAlignment())
12455       return false;
12456   } else {
12457     // Otherwise, the other block ended with a conditional branch. If one of the
12458     // destinations is StoreBB, then we have the if/then case.
12459     if (OtherBr->getSuccessor(0) != StoreBB && 
12460         OtherBr->getSuccessor(1) != StoreBB)
12461       return false;
12462     
12463     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12464     // if/then triangle.  See if there is a store to the same ptr as SI that
12465     // lives in OtherBB.
12466     for (;; --BBI) {
12467       // Check to see if we find the matching store.
12468       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12469         if (OtherStore->getOperand(1) != SI.getOperand(1) ||
12470             OtherStore->getAlignment() != SI.getAlignment())
12471           return false;
12472         break;
12473       }
12474       // If we find something that may be using or overwriting the stored
12475       // value, or if we run out of instructions, we can't do the xform.
12476       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12477           BBI == OtherBB->begin())
12478         return false;
12479     }
12480     
12481     // In order to eliminate the store in OtherBr, we have to
12482     // make sure nothing reads or overwrites the stored value in
12483     // StoreBB.
12484     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12485       // FIXME: This should really be AA driven.
12486       if (I->mayReadFromMemory() || I->mayWriteToMemory())
12487         return false;
12488     }
12489   }
12490   
12491   // Insert a PHI node now if we need it.
12492   Value *MergedVal = OtherStore->getOperand(0);
12493   if (MergedVal != SI.getOperand(0)) {
12494     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12495     PN->reserveOperandSpace(2);
12496     PN->addIncoming(SI.getOperand(0), SI.getParent());
12497     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12498     MergedVal = InsertNewInstBefore(PN, DestBB->front());
12499   }
12500   
12501   // Advance to a place where it is safe to insert the new store and
12502   // insert it.
12503   BBI = DestBB->getFirstNonPHI();
12504   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12505                                     OtherStore->isVolatile(),
12506                                     SI.getAlignment()), *BBI);
12507   
12508   // Nuke the old stores.
12509   EraseInstFromFunction(SI);
12510   EraseInstFromFunction(*OtherStore);
12511   ++NumCombined;
12512   return true;
12513 }
12514
12515
12516 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12517   // Change br (not X), label True, label False to: br X, label False, True
12518   Value *X = 0;
12519   BasicBlock *TrueDest;
12520   BasicBlock *FalseDest;
12521   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
12522       !isa<Constant>(X)) {
12523     // Swap Destinations and condition...
12524     BI.setCondition(X);
12525     BI.setSuccessor(0, FalseDest);
12526     BI.setSuccessor(1, TrueDest);
12527     return &BI;
12528   }
12529
12530   // Cannonicalize fcmp_one -> fcmp_oeq
12531   FCmpInst::Predicate FPred; Value *Y;
12532   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12533                              TrueDest, FalseDest)) &&
12534       BI.getCondition()->hasOneUse())
12535     if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12536         FPred == FCmpInst::FCMP_OGE) {
12537       FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12538       Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12539       
12540       // Swap Destinations and condition.
12541       BI.setSuccessor(0, FalseDest);
12542       BI.setSuccessor(1, TrueDest);
12543       Worklist.Add(Cond);
12544       return &BI;
12545     }
12546
12547   // Cannonicalize icmp_ne -> icmp_eq
12548   ICmpInst::Predicate IPred;
12549   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12550                       TrueDest, FalseDest)) &&
12551       BI.getCondition()->hasOneUse())
12552     if (IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12553         IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12554         IPred == ICmpInst::ICMP_SGE) {
12555       ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12556       Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12557       // Swap Destinations and condition.
12558       BI.setSuccessor(0, FalseDest);
12559       BI.setSuccessor(1, TrueDest);
12560       Worklist.Add(Cond);
12561       return &BI;
12562     }
12563
12564   return 0;
12565 }
12566
12567 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12568   Value *Cond = SI.getCondition();
12569   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12570     if (I->getOpcode() == Instruction::Add)
12571       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12572         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12573         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12574           SI.setOperand(i,
12575                    ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
12576                                                 AddRHS));
12577         SI.setOperand(0, I->getOperand(0));
12578         Worklist.Add(I);
12579         return &SI;
12580       }
12581   }
12582   return 0;
12583 }
12584
12585 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12586   Value *Agg = EV.getAggregateOperand();
12587
12588   if (!EV.hasIndices())
12589     return ReplaceInstUsesWith(EV, Agg);
12590
12591   if (Constant *C = dyn_cast<Constant>(Agg)) {
12592     if (isa<UndefValue>(C))
12593       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12594       
12595     if (isa<ConstantAggregateZero>(C))
12596       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12597
12598     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12599       // Extract the element indexed by the first index out of the constant
12600       Value *V = C->getOperand(*EV.idx_begin());
12601       if (EV.getNumIndices() > 1)
12602         // Extract the remaining indices out of the constant indexed by the
12603         // first index
12604         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12605       else
12606         return ReplaceInstUsesWith(EV, V);
12607     }
12608     return 0; // Can't handle other constants
12609   } 
12610   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12611     // We're extracting from an insertvalue instruction, compare the indices
12612     const unsigned *exti, *exte, *insi, *inse;
12613     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12614          exte = EV.idx_end(), inse = IV->idx_end();
12615          exti != exte && insi != inse;
12616          ++exti, ++insi) {
12617       if (*insi != *exti)
12618         // The insert and extract both reference distinctly different elements.
12619         // This means the extract is not influenced by the insert, and we can
12620         // replace the aggregate operand of the extract with the aggregate
12621         // operand of the insert. i.e., replace
12622         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12623         // %E = extractvalue { i32, { i32 } } %I, 0
12624         // with
12625         // %E = extractvalue { i32, { i32 } } %A, 0
12626         return ExtractValueInst::Create(IV->getAggregateOperand(),
12627                                         EV.idx_begin(), EV.idx_end());
12628     }
12629     if (exti == exte && insi == inse)
12630       // Both iterators are at the end: Index lists are identical. Replace
12631       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12632       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12633       // with "i32 42"
12634       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12635     if (exti == exte) {
12636       // The extract list is a prefix of the insert list. i.e. replace
12637       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12638       // %E = extractvalue { i32, { i32 } } %I, 1
12639       // with
12640       // %X = extractvalue { i32, { i32 } } %A, 1
12641       // %E = insertvalue { i32 } %X, i32 42, 0
12642       // by switching the order of the insert and extract (though the
12643       // insertvalue should be left in, since it may have other uses).
12644       Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12645                                                  EV.idx_begin(), EV.idx_end());
12646       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12647                                      insi, inse);
12648     }
12649     if (insi == inse)
12650       // The insert list is a prefix of the extract list
12651       // We can simply remove the common indices from the extract and make it
12652       // operate on the inserted value instead of the insertvalue result.
12653       // i.e., replace
12654       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12655       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12656       // with
12657       // %E extractvalue { i32 } { i32 42 }, 0
12658       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12659                                       exti, exte);
12660   }
12661   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
12662     // We're extracting from an intrinsic, see if we're the only user, which
12663     // allows us to simplify multiple result intrinsics to simpler things that
12664     // just get one value..
12665     if (II->hasOneUse()) {
12666       // Check if we're grabbing the overflow bit or the result of a 'with
12667       // overflow' intrinsic.  If it's the latter we can remove the intrinsic
12668       // and replace it with a traditional binary instruction.
12669       switch (II->getIntrinsicID()) {
12670       case Intrinsic::uadd_with_overflow:
12671       case Intrinsic::sadd_with_overflow:
12672         if (*EV.idx_begin() == 0) {  // Normal result.
12673           Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12674           II->replaceAllUsesWith(UndefValue::get(II->getType()));
12675           EraseInstFromFunction(*II);
12676           return BinaryOperator::CreateAdd(LHS, RHS);
12677         }
12678         break;
12679       case Intrinsic::usub_with_overflow:
12680       case Intrinsic::ssub_with_overflow:
12681         if (*EV.idx_begin() == 0) {  // Normal result.
12682           Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12683           II->replaceAllUsesWith(UndefValue::get(II->getType()));
12684           EraseInstFromFunction(*II);
12685           return BinaryOperator::CreateSub(LHS, RHS);
12686         }
12687         break;
12688       case Intrinsic::umul_with_overflow:
12689       case Intrinsic::smul_with_overflow:
12690         if (*EV.idx_begin() == 0) {  // Normal result.
12691           Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12692           II->replaceAllUsesWith(UndefValue::get(II->getType()));
12693           EraseInstFromFunction(*II);
12694           return BinaryOperator::CreateMul(LHS, RHS);
12695         }
12696         break;
12697       default:
12698         break;
12699       }
12700     }
12701   }
12702   // Can't simplify extracts from other values. Note that nested extracts are
12703   // already simplified implicitely by the above (extract ( extract (insert) )
12704   // will be translated into extract ( insert ( extract ) ) first and then just
12705   // the value inserted, if appropriate).
12706   return 0;
12707 }
12708
12709 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12710 /// is to leave as a vector operation.
12711 static bool CheapToScalarize(Value *V, bool isConstant) {
12712   if (isa<ConstantAggregateZero>(V)) 
12713     return true;
12714   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12715     if (isConstant) return true;
12716     // If all elts are the same, we can extract.
12717     Constant *Op0 = C->getOperand(0);
12718     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12719       if (C->getOperand(i) != Op0)
12720         return false;
12721     return true;
12722   }
12723   Instruction *I = dyn_cast<Instruction>(V);
12724   if (!I) return false;
12725   
12726   // Insert element gets simplified to the inserted element or is deleted if
12727   // this is constant idx extract element and its a constant idx insertelt.
12728   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12729       isa<ConstantInt>(I->getOperand(2)))
12730     return true;
12731   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12732     return true;
12733   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12734     if (BO->hasOneUse() &&
12735         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12736          CheapToScalarize(BO->getOperand(1), isConstant)))
12737       return true;
12738   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12739     if (CI->hasOneUse() &&
12740         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12741          CheapToScalarize(CI->getOperand(1), isConstant)))
12742       return true;
12743   
12744   return false;
12745 }
12746
12747 /// Read and decode a shufflevector mask.
12748 ///
12749 /// It turns undef elements into values that are larger than the number of
12750 /// elements in the input.
12751 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12752   unsigned NElts = SVI->getType()->getNumElements();
12753   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12754     return std::vector<unsigned>(NElts, 0);
12755   if (isa<UndefValue>(SVI->getOperand(2)))
12756     return std::vector<unsigned>(NElts, 2*NElts);
12757
12758   std::vector<unsigned> Result;
12759   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12760   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12761     if (isa<UndefValue>(*i))
12762       Result.push_back(NElts*2);  // undef -> 8
12763     else
12764       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12765   return Result;
12766 }
12767
12768 /// FindScalarElement - Given a vector and an element number, see if the scalar
12769 /// value is already around as a register, for example if it were inserted then
12770 /// extracted from the vector.
12771 static Value *FindScalarElement(Value *V, unsigned EltNo,
12772                                 LLVMContext *Context) {
12773   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12774   const VectorType *PTy = cast<VectorType>(V->getType());
12775   unsigned Width = PTy->getNumElements();
12776   if (EltNo >= Width)  // Out of range access.
12777     return UndefValue::get(PTy->getElementType());
12778   
12779   if (isa<UndefValue>(V))
12780     return UndefValue::get(PTy->getElementType());
12781   else if (isa<ConstantAggregateZero>(V))
12782     return Constant::getNullValue(PTy->getElementType());
12783   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12784     return CP->getOperand(EltNo);
12785   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12786     // If this is an insert to a variable element, we don't know what it is.
12787     if (!isa<ConstantInt>(III->getOperand(2))) 
12788       return 0;
12789     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12790     
12791     // If this is an insert to the element we are looking for, return the
12792     // inserted value.
12793     if (EltNo == IIElt) 
12794       return III->getOperand(1);
12795     
12796     // Otherwise, the insertelement doesn't modify the value, recurse on its
12797     // vector input.
12798     return FindScalarElement(III->getOperand(0), EltNo, Context);
12799   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12800     unsigned LHSWidth =
12801       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12802     unsigned InEl = getShuffleMask(SVI)[EltNo];
12803     if (InEl < LHSWidth)
12804       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12805     else if (InEl < LHSWidth*2)
12806       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12807     else
12808       return UndefValue::get(PTy->getElementType());
12809   }
12810   
12811   // Otherwise, we don't know.
12812   return 0;
12813 }
12814
12815 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12816   // If vector val is undef, replace extract with scalar undef.
12817   if (isa<UndefValue>(EI.getOperand(0)))
12818     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12819
12820   // If vector val is constant 0, replace extract with scalar 0.
12821   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12822     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12823   
12824   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12825     // If vector val is constant with all elements the same, replace EI with
12826     // that element. When the elements are not identical, we cannot replace yet
12827     // (we do that below, but only when the index is constant).
12828     Constant *op0 = C->getOperand(0);
12829     for (unsigned i = 1; i != C->getNumOperands(); ++i)
12830       if (C->getOperand(i) != op0) {
12831         op0 = 0; 
12832         break;
12833       }
12834     if (op0)
12835       return ReplaceInstUsesWith(EI, op0);
12836   }
12837   
12838   // If extracting a specified index from the vector, see if we can recursively
12839   // find a previously computed scalar that was inserted into the vector.
12840   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12841     unsigned IndexVal = IdxC->getZExtValue();
12842     unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
12843       
12844     // If this is extracting an invalid index, turn this into undef, to avoid
12845     // crashing the code below.
12846     if (IndexVal >= VectorWidth)
12847       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12848     
12849     // This instruction only demands the single element from the input vector.
12850     // If the input vector has a single use, simplify it based on this use
12851     // property.
12852     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12853       APInt UndefElts(VectorWidth, 0);
12854       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12855       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12856                                                 DemandedMask, UndefElts)) {
12857         EI.setOperand(0, V);
12858         return &EI;
12859       }
12860     }
12861     
12862     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12863       return ReplaceInstUsesWith(EI, Elt);
12864     
12865     // If the this extractelement is directly using a bitcast from a vector of
12866     // the same number of elements, see if we can find the source element from
12867     // it.  In this case, we will end up needing to bitcast the scalars.
12868     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12869       if (const VectorType *VT = 
12870               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12871         if (VT->getNumElements() == VectorWidth)
12872           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12873                                              IndexVal, Context))
12874             return new BitCastInst(Elt, EI.getType());
12875     }
12876   }
12877   
12878   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12879     // Push extractelement into predecessor operation if legal and
12880     // profitable to do so
12881     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12882       if (I->hasOneUse() &&
12883           CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12884         Value *newEI0 =
12885           Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12886                                         EI.getName()+".lhs");
12887         Value *newEI1 =
12888           Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12889                                         EI.getName()+".rhs");
12890         return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12891       }
12892     } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12893       // Extracting the inserted element?
12894       if (IE->getOperand(2) == EI.getOperand(1))
12895         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12896       // If the inserted and extracted elements are constants, they must not
12897       // be the same value, extract from the pre-inserted value instead.
12898       if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
12899         Worklist.AddValue(EI.getOperand(0));
12900         EI.setOperand(0, IE->getOperand(0));
12901         return &EI;
12902       }
12903     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12904       // If this is extracting an element from a shufflevector, figure out where
12905       // it came from and extract from the appropriate input element instead.
12906       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12907         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12908         Value *Src;
12909         unsigned LHSWidth =
12910           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12911
12912         if (SrcIdx < LHSWidth)
12913           Src = SVI->getOperand(0);
12914         else if (SrcIdx < LHSWidth*2) {
12915           SrcIdx -= LHSWidth;
12916           Src = SVI->getOperand(1);
12917         } else {
12918           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12919         }
12920         return ExtractElementInst::Create(Src,
12921                          ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12922                                           false));
12923       }
12924     }
12925     // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12926   }
12927   return 0;
12928 }
12929
12930 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12931 /// elements from either LHS or RHS, return the shuffle mask and true. 
12932 /// Otherwise, return false.
12933 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12934                                          std::vector<Constant*> &Mask,
12935                                          LLVMContext *Context) {
12936   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12937          "Invalid CollectSingleShuffleElements");
12938   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12939
12940   if (isa<UndefValue>(V)) {
12941     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12942     return true;
12943   } else if (V == LHS) {
12944     for (unsigned i = 0; i != NumElts; ++i)
12945       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12946     return true;
12947   } else if (V == RHS) {
12948     for (unsigned i = 0; i != NumElts; ++i)
12949       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
12950     return true;
12951   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12952     // If this is an insert of an extract from some other vector, include it.
12953     Value *VecOp    = IEI->getOperand(0);
12954     Value *ScalarOp = IEI->getOperand(1);
12955     Value *IdxOp    = IEI->getOperand(2);
12956     
12957     if (!isa<ConstantInt>(IdxOp))
12958       return false;
12959     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12960     
12961     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12962       // Okay, we can handle this if the vector we are insertinting into is
12963       // transitively ok.
12964       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12965         // If so, update the mask to reflect the inserted undef.
12966         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
12967         return true;
12968       }      
12969     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12970       if (isa<ConstantInt>(EI->getOperand(1)) &&
12971           EI->getOperand(0)->getType() == V->getType()) {
12972         unsigned ExtractedIdx =
12973           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12974         
12975         // This must be extracting from either LHS or RHS.
12976         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12977           // Okay, we can handle this if the vector we are insertinting into is
12978           // transitively ok.
12979           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12980             // If so, update the mask to reflect the inserted value.
12981             if (EI->getOperand(0) == LHS) {
12982               Mask[InsertedIdx % NumElts] = 
12983                  ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12984             } else {
12985               assert(EI->getOperand(0) == RHS);
12986               Mask[InsertedIdx % NumElts] = 
12987                 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
12988               
12989             }
12990             return true;
12991           }
12992         }
12993       }
12994     }
12995   }
12996   // TODO: Handle shufflevector here!
12997   
12998   return false;
12999 }
13000
13001 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
13002 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
13003 /// that computes V and the LHS value of the shuffle.
13004 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
13005                                      Value *&RHS, LLVMContext *Context) {
13006   assert(isa<VectorType>(V->getType()) && 
13007          (RHS == 0 || V->getType() == RHS->getType()) &&
13008          "Invalid shuffle!");
13009   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
13010
13011   if (isa<UndefValue>(V)) {
13012     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
13013     return V;
13014   } else if (isa<ConstantAggregateZero>(V)) {
13015     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
13016     return V;
13017   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
13018     // If this is an insert of an extract from some other vector, include it.
13019     Value *VecOp    = IEI->getOperand(0);
13020     Value *ScalarOp = IEI->getOperand(1);
13021     Value *IdxOp    = IEI->getOperand(2);
13022     
13023     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13024       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13025           EI->getOperand(0)->getType() == V->getType()) {
13026         unsigned ExtractedIdx =
13027           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13028         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
13029         
13030         // Either the extracted from or inserted into vector must be RHSVec,
13031         // otherwise we'd end up with a shuffle of three inputs.
13032         if (EI->getOperand(0) == RHS || RHS == 0) {
13033           RHS = EI->getOperand(0);
13034           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
13035           Mask[InsertedIdx % NumElts] = 
13036             ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
13037           return V;
13038         }
13039         
13040         if (VecOp == RHS) {
13041           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
13042                                             RHS, Context);
13043           // Everything but the extracted element is replaced with the RHS.
13044           for (unsigned i = 0; i != NumElts; ++i) {
13045             if (i != InsertedIdx)
13046               Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
13047           }
13048           return V;
13049         }
13050         
13051         // If this insertelement is a chain that comes from exactly these two
13052         // vectors, return the vector and the effective shuffle.
13053         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
13054                                          Context))
13055           return EI->getOperand(0);
13056         
13057       }
13058     }
13059   }
13060   // TODO: Handle shufflevector here!
13061   
13062   // Otherwise, can't do anything fancy.  Return an identity vector.
13063   for (unsigned i = 0; i != NumElts; ++i)
13064     Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
13065   return V;
13066 }
13067
13068 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
13069   Value *VecOp    = IE.getOperand(0);
13070   Value *ScalarOp = IE.getOperand(1);
13071   Value *IdxOp    = IE.getOperand(2);
13072   
13073   // Inserting an undef or into an undefined place, remove this.
13074   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
13075     ReplaceInstUsesWith(IE, VecOp);
13076   
13077   // If the inserted element was extracted from some other vector, and if the 
13078   // indexes are constant, try to turn this into a shufflevector operation.
13079   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13080     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13081         EI->getOperand(0)->getType() == IE.getType()) {
13082       unsigned NumVectorElts = IE.getType()->getNumElements();
13083       unsigned ExtractedIdx =
13084         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13085       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
13086       
13087       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
13088         return ReplaceInstUsesWith(IE, VecOp);
13089       
13090       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
13091         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
13092       
13093       // If we are extracting a value from a vector, then inserting it right
13094       // back into the same place, just use the input vector.
13095       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
13096         return ReplaceInstUsesWith(IE, VecOp);      
13097       
13098       // If this insertelement isn't used by some other insertelement, turn it
13099       // (and any insertelements it points to), into one big shuffle.
13100       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
13101         std::vector<Constant*> Mask;
13102         Value *RHS = 0;
13103         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
13104         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
13105         // We now have a shuffle of LHS, RHS, Mask.
13106         return new ShuffleVectorInst(LHS, RHS,
13107                                      ConstantVector::get(Mask));
13108       }
13109     }
13110   }
13111
13112   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
13113   APInt UndefElts(VWidth, 0);
13114   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13115   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
13116     return &IE;
13117
13118   return 0;
13119 }
13120
13121
13122 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
13123   Value *LHS = SVI.getOperand(0);
13124   Value *RHS = SVI.getOperand(1);
13125   std::vector<unsigned> Mask = getShuffleMask(&SVI);
13126
13127   bool MadeChange = false;
13128
13129   // Undefined shuffle mask -> undefined value.
13130   if (isa<UndefValue>(SVI.getOperand(2)))
13131     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
13132
13133   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
13134
13135   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
13136     return 0;
13137
13138   APInt UndefElts(VWidth, 0);
13139   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13140   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
13141     LHS = SVI.getOperand(0);
13142     RHS = SVI.getOperand(1);
13143     MadeChange = true;
13144   }
13145   
13146   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
13147   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
13148   if (LHS == RHS || isa<UndefValue>(LHS)) {
13149     if (isa<UndefValue>(LHS) && LHS == RHS) {
13150       // shuffle(undef,undef,mask) -> undef.
13151       return ReplaceInstUsesWith(SVI, LHS);
13152     }
13153     
13154     // Remap any references to RHS to use LHS.
13155     std::vector<Constant*> Elts;
13156     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13157       if (Mask[i] >= 2*e)
13158         Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13159       else {
13160         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
13161             (Mask[i] <  e && isa<UndefValue>(LHS))) {
13162           Mask[i] = 2*e;     // Turn into undef.
13163           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13164         } else {
13165           Mask[i] = Mask[i] % e;  // Force to LHS.
13166           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
13167         }
13168       }
13169     }
13170     SVI.setOperand(0, SVI.getOperand(1));
13171     SVI.setOperand(1, UndefValue::get(RHS->getType()));
13172     SVI.setOperand(2, ConstantVector::get(Elts));
13173     LHS = SVI.getOperand(0);
13174     RHS = SVI.getOperand(1);
13175     MadeChange = true;
13176   }
13177   
13178   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
13179   bool isLHSID = true, isRHSID = true;
13180     
13181   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13182     if (Mask[i] >= e*2) continue;  // Ignore undef values.
13183     // Is this an identity shuffle of the LHS value?
13184     isLHSID &= (Mask[i] == i);
13185       
13186     // Is this an identity shuffle of the RHS value?
13187     isRHSID &= (Mask[i]-e == i);
13188   }
13189
13190   // Eliminate identity shuffles.
13191   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
13192   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
13193   
13194   // If the LHS is a shufflevector itself, see if we can combine it with this
13195   // one without producing an unusual shuffle.  Here we are really conservative:
13196   // we are absolutely afraid of producing a shuffle mask not in the input
13197   // program, because the code gen may not be smart enough to turn a merged
13198   // shuffle into two specific shuffles: it may produce worse code.  As such,
13199   // we only merge two shuffles if the result is one of the two input shuffle
13200   // masks.  In this case, merging the shuffles just removes one instruction,
13201   // which we know is safe.  This is good for things like turning:
13202   // (splat(splat)) -> splat.
13203   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
13204     if (isa<UndefValue>(RHS)) {
13205       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
13206
13207       if (LHSMask.size() == Mask.size()) {
13208         std::vector<unsigned> NewMask;
13209         for (unsigned i = 0, e = Mask.size(); i != e; ++i)
13210           if (Mask[i] >= e)
13211             NewMask.push_back(2*e);
13212           else
13213             NewMask.push_back(LHSMask[Mask[i]]);
13214       
13215         // If the result mask is equal to the src shuffle or this
13216         // shuffle mask, do the replacement.
13217         if (NewMask == LHSMask || NewMask == Mask) {
13218           unsigned LHSInNElts =
13219             cast<VectorType>(LHSSVI->getOperand(0)->getType())->
13220             getNumElements();
13221           std::vector<Constant*> Elts;
13222           for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
13223             if (NewMask[i] >= LHSInNElts*2) {
13224               Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13225             } else {
13226               Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
13227                                               NewMask[i]));
13228             }
13229           }
13230           return new ShuffleVectorInst(LHSSVI->getOperand(0),
13231                                        LHSSVI->getOperand(1),
13232                                        ConstantVector::get(Elts));
13233         }
13234       }
13235     }
13236   }
13237
13238   return MadeChange ? &SVI : 0;
13239 }
13240
13241
13242
13243
13244 /// TryToSinkInstruction - Try to move the specified instruction from its
13245 /// current block into the beginning of DestBlock, which can only happen if it's
13246 /// safe to move the instruction past all of the instructions between it and the
13247 /// end of its block.
13248 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
13249   assert(I->hasOneUse() && "Invariants didn't hold!");
13250
13251   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
13252   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
13253     return false;
13254
13255   // Do not sink alloca instructions out of the entry block.
13256   if (isa<AllocaInst>(I) && I->getParent() ==
13257         &DestBlock->getParent()->getEntryBlock())
13258     return false;
13259
13260   // We can only sink load instructions if there is nothing between the load and
13261   // the end of block that could change the value.
13262   if (I->mayReadFromMemory()) {
13263     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
13264          Scan != E; ++Scan)
13265       if (Scan->mayWriteToMemory())
13266         return false;
13267   }
13268
13269   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
13270
13271   CopyPrecedingStopPoint(I, InsertPos);
13272   I->moveBefore(InsertPos);
13273   ++NumSunkInst;
13274   return true;
13275 }
13276
13277
13278 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
13279 /// all reachable code to the worklist.
13280 ///
13281 /// This has a couple of tricks to make the code faster and more powerful.  In
13282 /// particular, we constant fold and DCE instructions as we go, to avoid adding
13283 /// them to the worklist (this significantly speeds up instcombine on code where
13284 /// many instructions are dead or constant).  Additionally, if we find a branch
13285 /// whose condition is a known constant, we only visit the reachable successors.
13286 ///
13287 static bool AddReachableCodeToWorklist(BasicBlock *BB, 
13288                                        SmallPtrSet<BasicBlock*, 64> &Visited,
13289                                        InstCombiner &IC,
13290                                        const TargetData *TD) {
13291   bool MadeIRChange = false;
13292   SmallVector<BasicBlock*, 256> Worklist;
13293   Worklist.push_back(BB);
13294   
13295   std::vector<Instruction*> InstrsForInstCombineWorklist;
13296   InstrsForInstCombineWorklist.reserve(128);
13297
13298   SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
13299   
13300   while (!Worklist.empty()) {
13301     BB = Worklist.back();
13302     Worklist.pop_back();
13303     
13304     // We have now visited this block!  If we've already been here, ignore it.
13305     if (!Visited.insert(BB)) continue;
13306
13307     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
13308       Instruction *Inst = BBI++;
13309       
13310       // DCE instruction if trivially dead.
13311       if (isInstructionTriviallyDead(Inst)) {
13312         ++NumDeadInst;
13313         DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
13314         Inst->eraseFromParent();
13315         continue;
13316       }
13317       
13318       // ConstantProp instruction if trivially constant.
13319       if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
13320         if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
13321           DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
13322                        << *Inst << '\n');
13323           Inst->replaceAllUsesWith(C);
13324           ++NumConstProp;
13325           Inst->eraseFromParent();
13326           continue;
13327         }
13328       
13329       
13330       
13331       if (TD) {
13332         // See if we can constant fold its operands.
13333         for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
13334              i != e; ++i) {
13335           ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
13336           if (CE == 0) continue;
13337           
13338           // If we already folded this constant, don't try again.
13339           if (!FoldedConstants.insert(CE))
13340             continue;
13341           
13342           Constant *NewC = ConstantFoldConstantExpression(CE, TD);
13343           if (NewC && NewC != CE) {
13344             *i = NewC;
13345             MadeIRChange = true;
13346           }
13347         }
13348       }
13349       
13350
13351       InstrsForInstCombineWorklist.push_back(Inst);
13352     }
13353
13354     // Recursively visit successors.  If this is a branch or switch on a
13355     // constant, only visit the reachable successor.
13356     TerminatorInst *TI = BB->getTerminator();
13357     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
13358       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
13359         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
13360         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
13361         Worklist.push_back(ReachableBB);
13362         continue;
13363       }
13364     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
13365       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
13366         // See if this is an explicit destination.
13367         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
13368           if (SI->getCaseValue(i) == Cond) {
13369             BasicBlock *ReachableBB = SI->getSuccessor(i);
13370             Worklist.push_back(ReachableBB);
13371             continue;
13372           }
13373         
13374         // Otherwise it is the default destination.
13375         Worklist.push_back(SI->getSuccessor(0));
13376         continue;
13377       }
13378     }
13379     
13380     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
13381       Worklist.push_back(TI->getSuccessor(i));
13382   }
13383   
13384   // Once we've found all of the instructions to add to instcombine's worklist,
13385   // add them in reverse order.  This way instcombine will visit from the top
13386   // of the function down.  This jives well with the way that it adds all uses
13387   // of instructions to the worklist after doing a transformation, thus avoiding
13388   // some N^2 behavior in pathological cases.
13389   IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
13390                               InstrsForInstCombineWorklist.size());
13391   
13392   return MadeIRChange;
13393 }
13394
13395 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
13396   MadeIRChange = false;
13397   
13398   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
13399         << F.getNameStr() << "\n");
13400
13401   {
13402     // Do a depth-first traversal of the function, populate the worklist with
13403     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
13404     // track of which blocks we visit.
13405     SmallPtrSet<BasicBlock*, 64> Visited;
13406     MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
13407
13408     // Do a quick scan over the function.  If we find any blocks that are
13409     // unreachable, remove any instructions inside of them.  This prevents
13410     // the instcombine code from having to deal with some bad special cases.
13411     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
13412       if (!Visited.count(BB)) {
13413         Instruction *Term = BB->getTerminator();
13414         while (Term != BB->begin()) {   // Remove instrs bottom-up
13415           BasicBlock::iterator I = Term; --I;
13416
13417           DEBUG(errs() << "IC: DCE: " << *I << '\n');
13418           // A debug intrinsic shouldn't force another iteration if we weren't
13419           // going to do one without it.
13420           if (!isa<DbgInfoIntrinsic>(I)) {
13421             ++NumDeadInst;
13422             MadeIRChange = true;
13423           }
13424
13425           // If I is not void type then replaceAllUsesWith undef.
13426           // This allows ValueHandlers and custom metadata to adjust itself.
13427           if (!I->getType()->isVoidTy())
13428             I->replaceAllUsesWith(UndefValue::get(I->getType()));
13429           I->eraseFromParent();
13430         }
13431       }
13432   }
13433
13434   while (!Worklist.isEmpty()) {
13435     Instruction *I = Worklist.RemoveOne();
13436     if (I == 0) continue;  // skip null values.
13437
13438     // Check to see if we can DCE the instruction.
13439     if (isInstructionTriviallyDead(I)) {
13440       DEBUG(errs() << "IC: DCE: " << *I << '\n');
13441       EraseInstFromFunction(*I);
13442       ++NumDeadInst;
13443       MadeIRChange = true;
13444       continue;
13445     }
13446
13447     // Instruction isn't dead, see if we can constant propagate it.
13448     if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
13449       if (Constant *C = ConstantFoldInstruction(I, TD)) {
13450         DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
13451
13452         // Add operands to the worklist.
13453         ReplaceInstUsesWith(*I, C);
13454         ++NumConstProp;
13455         EraseInstFromFunction(*I);
13456         MadeIRChange = true;
13457         continue;
13458       }
13459
13460     // See if we can trivially sink this instruction to a successor basic block.
13461     if (I->hasOneUse()) {
13462       BasicBlock *BB = I->getParent();
13463       Instruction *UserInst = cast<Instruction>(I->use_back());
13464       BasicBlock *UserParent;
13465       
13466       // Get the block the use occurs in.
13467       if (PHINode *PN = dyn_cast<PHINode>(UserInst))
13468         UserParent = PN->getIncomingBlock(I->use_begin().getUse());
13469       else
13470         UserParent = UserInst->getParent();
13471       
13472       if (UserParent != BB) {
13473         bool UserIsSuccessor = false;
13474         // See if the user is one of our successors.
13475         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13476           if (*SI == UserParent) {
13477             UserIsSuccessor = true;
13478             break;
13479           }
13480
13481         // If the user is one of our immediate successors, and if that successor
13482         // only has us as a predecessors (we'd have to split the critical edge
13483         // otherwise), we can keep going.
13484         if (UserIsSuccessor && UserParent->getSinglePredecessor())
13485           // Okay, the CFG is simple enough, try to sink this instruction.
13486           MadeIRChange |= TryToSinkInstruction(I, UserParent);
13487       }
13488     }
13489
13490     // Now that we have an instruction, try combining it to simplify it.
13491     Builder->SetInsertPoint(I->getParent(), I);
13492     
13493 #ifndef NDEBUG
13494     std::string OrigI;
13495 #endif
13496     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
13497     DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
13498
13499     if (Instruction *Result = visit(*I)) {
13500       ++NumCombined;
13501       // Should we replace the old instruction with a new one?
13502       if (Result != I) {
13503         DEBUG(errs() << "IC: Old = " << *I << '\n'
13504                      << "    New = " << *Result << '\n');
13505
13506         // Everything uses the new instruction now.
13507         I->replaceAllUsesWith(Result);
13508
13509         // Push the new instruction and any users onto the worklist.
13510         Worklist.Add(Result);
13511         Worklist.AddUsersToWorkList(*Result);
13512
13513         // Move the name to the new instruction first.
13514         Result->takeName(I);
13515
13516         // Insert the new instruction into the basic block...
13517         BasicBlock *InstParent = I->getParent();
13518         BasicBlock::iterator InsertPos = I;
13519
13520         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
13521           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13522             ++InsertPos;
13523
13524         InstParent->getInstList().insert(InsertPos, Result);
13525
13526         EraseInstFromFunction(*I);
13527       } else {
13528 #ifndef NDEBUG
13529         DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13530                      << "    New = " << *I << '\n');
13531 #endif
13532
13533         // If the instruction was modified, it's possible that it is now dead.
13534         // if so, remove it.
13535         if (isInstructionTriviallyDead(I)) {
13536           EraseInstFromFunction(*I);
13537         } else {
13538           Worklist.Add(I);
13539           Worklist.AddUsersToWorkList(*I);
13540         }
13541       }
13542       MadeIRChange = true;
13543     }
13544   }
13545
13546   Worklist.Zap();
13547   return MadeIRChange;
13548 }
13549
13550
13551 bool InstCombiner::runOnFunction(Function &F) {
13552   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13553   Context = &F.getContext();
13554   TD = getAnalysisIfAvailable<TargetData>();
13555
13556   
13557   /// Builder - This is an IRBuilder that automatically inserts new
13558   /// instructions into the worklist when they are created.
13559   IRBuilder<true, TargetFolder, InstCombineIRInserter> 
13560     TheBuilder(F.getContext(), TargetFolder(TD),
13561                InstCombineIRInserter(Worklist));
13562   Builder = &TheBuilder;
13563   
13564   bool EverMadeChange = false;
13565
13566   // Iterate while there is work to do.
13567   unsigned Iteration = 0;
13568   while (DoOneIteration(F, Iteration++))
13569     EverMadeChange = true;
13570   
13571   Builder = 0;
13572   return EverMadeChange;
13573 }
13574
13575 FunctionPass *llvm::createInstructionCombiningPass() {
13576   return new InstCombiner();
13577 }