give instcombine some helper functions for matching MIN and MAX, and
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions.  This pass does not modify the CFG.  This pass is where
12 // algebraic simplification happens.
13 //
14 // This pass combines things like:
15 //    %Y = add i32 %X, 1
16 //    %Z = add i32 %Y, 1
17 // into:
18 //    %Z = add i32 %X, 2
19 //
20 // This is a simple worklist driven algorithm.
21 //
22 // This pass guarantees that the following canonicalizations are performed on
23 // the program:
24 //    1. If a binary operator has a constant operand, it is moved to the RHS
25 //    2. Bitwise operators with constant operands are always grouped so that
26 //       shifts are performed first, then or's, then and's, then xor's.
27 //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All cmp instructions on boolean values are replaced with logical ops
29 //    5. add X, X is represented as (X*2) => (X << 1)
30 //    6. Multiplies with a power-of-two constant argument are transformed into
31 //       shifts.
32 //   ... etc.
33 //
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/LLVMContext.h"
40 #include "llvm/Pass.h"
41 #include "llvm/DerivedTypes.h"
42 #include "llvm/GlobalVariable.h"
43 #include "llvm/Operator.h"
44 #include "llvm/Analysis/ConstantFolding.h"
45 #include "llvm/Analysis/InstructionSimplify.h"
46 #include "llvm/Analysis/MemoryBuiltins.h"
47 #include "llvm/Analysis/ValueTracking.h"
48 #include "llvm/Target/TargetData.h"
49 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
50 #include "llvm/Transforms/Utils/Local.h"
51 #include "llvm/Support/CallSite.h"
52 #include "llvm/Support/ConstantRange.h"
53 #include "llvm/Support/Debug.h"
54 #include "llvm/Support/ErrorHandling.h"
55 #include "llvm/Support/GetElementPtrTypeIterator.h"
56 #include "llvm/Support/InstVisitor.h"
57 #include "llvm/Support/IRBuilder.h"
58 #include "llvm/Support/MathExtras.h"
59 #include "llvm/Support/PatternMatch.h"
60 #include "llvm/Support/TargetFolder.h"
61 #include "llvm/Support/raw_ostream.h"
62 #include "llvm/ADT/DenseMap.h"
63 #include "llvm/ADT/SmallVector.h"
64 #include "llvm/ADT/SmallPtrSet.h"
65 #include "llvm/ADT/Statistic.h"
66 #include "llvm/ADT/STLExtras.h"
67 #include <algorithm>
68 #include <climits>
69 using namespace llvm;
70 using namespace llvm::PatternMatch;
71
72 STATISTIC(NumCombined , "Number of insts combined");
73 STATISTIC(NumConstProp, "Number of constant folds");
74 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
75 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
76 STATISTIC(NumSunkInst , "Number of instructions sunk");
77
78 /// SelectPatternFlavor - We can match a variety of different patterns for
79 /// select operations.
80 enum SelectPatternFlavor {
81   SPF_UNKNOWN = 0,
82   SPF_SMIN, SPF_UMIN,
83   SPF_SMAX, SPF_UMAX
84   //SPF_ABS - TODO.
85 };
86
87 namespace {
88   /// InstCombineWorklist - This is the worklist management logic for
89   /// InstCombine.
90   class InstCombineWorklist {
91     SmallVector<Instruction*, 256> Worklist;
92     DenseMap<Instruction*, unsigned> WorklistMap;
93     
94     void operator=(const InstCombineWorklist&RHS);   // DO NOT IMPLEMENT
95     InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
96   public:
97     InstCombineWorklist() {}
98     
99     bool isEmpty() const { return Worklist.empty(); }
100     
101     /// Add - Add the specified instruction to the worklist if it isn't already
102     /// in it.
103     void Add(Instruction *I) {
104       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {
105         DEBUG(errs() << "IC: ADD: " << *I << '\n');
106         Worklist.push_back(I);
107       }
108     }
109     
110     void AddValue(Value *V) {
111       if (Instruction *I = dyn_cast<Instruction>(V))
112         Add(I);
113     }
114     
115     /// AddInitialGroup - Add the specified batch of stuff in reverse order.
116     /// which should only be done when the worklist is empty and when the group
117     /// has no duplicates.
118     void AddInitialGroup(Instruction *const *List, unsigned NumEntries) {
119       assert(Worklist.empty() && "Worklist must be empty to add initial group");
120       Worklist.reserve(NumEntries+16);
121       DEBUG(errs() << "IC: ADDING: " << NumEntries << " instrs to worklist\n");
122       for (; NumEntries; --NumEntries) {
123         Instruction *I = List[NumEntries-1];
124         WorklistMap.insert(std::make_pair(I, Worklist.size()));
125         Worklist.push_back(I);
126       }
127     }
128     
129     // Remove - remove I from the worklist if it exists.
130     void Remove(Instruction *I) {
131       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
132       if (It == WorklistMap.end()) return; // Not in worklist.
133       
134       // Don't bother moving everything down, just null out the slot.
135       Worklist[It->second] = 0;
136       
137       WorklistMap.erase(It);
138     }
139     
140     Instruction *RemoveOne() {
141       Instruction *I = Worklist.back();
142       Worklist.pop_back();
143       WorklistMap.erase(I);
144       return I;
145     }
146
147     /// AddUsersToWorkList - When an instruction is simplified, add all users of
148     /// the instruction to the work lists because they might get more simplified
149     /// now.
150     ///
151     void AddUsersToWorkList(Instruction &I) {
152       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
153            UI != UE; ++UI)
154         Add(cast<Instruction>(*UI));
155     }
156     
157     
158     /// Zap - check that the worklist is empty and nuke the backing store for
159     /// the map if it is large.
160     void Zap() {
161       assert(WorklistMap.empty() && "Worklist empty, but map not?");
162       
163       // Do an explicit clear, this shrinks the map if needed.
164       WorklistMap.clear();
165     }
166   };
167 } // end anonymous namespace.
168
169
170 namespace {
171   /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
172   /// just like the normal insertion helper, but also adds any new instructions
173   /// to the instcombine worklist.
174   class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
175     InstCombineWorklist &Worklist;
176   public:
177     InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
178     
179     void InsertHelper(Instruction *I, const Twine &Name,
180                       BasicBlock *BB, BasicBlock::iterator InsertPt) const {
181       IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
182       Worklist.Add(I);
183     }
184   };
185 } // end anonymous namespace
186
187
188 namespace {
189   class InstCombiner : public FunctionPass,
190                        public InstVisitor<InstCombiner, Instruction*> {
191     TargetData *TD;
192     bool MustPreserveLCSSA;
193     bool MadeIRChange;
194   public:
195     /// Worklist - All of the instructions that need to be simplified.
196     InstCombineWorklist Worklist;
197
198     /// Builder - This is an IRBuilder that automatically inserts new
199     /// instructions into the worklist when they are created.
200     typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
201     BuilderTy *Builder;
202         
203     static char ID; // Pass identification, replacement for typeid
204     InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
205
206     LLVMContext *Context;
207     LLVMContext *getContext() const { return Context; }
208
209   public:
210     virtual bool runOnFunction(Function &F);
211     
212     bool DoOneIteration(Function &F, unsigned ItNum);
213
214     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
215       AU.addPreservedID(LCSSAID);
216       AU.setPreservesCFG();
217     }
218
219     TargetData *getTargetData() const { return TD; }
220
221     // Visitation implementation - Implement instruction combining for different
222     // instruction types.  The semantics are as follows:
223     // Return Value:
224     //    null        - No change was made
225     //     I          - Change was made, I is still valid, I may be dead though
226     //   otherwise    - Change was made, replace I with returned instruction
227     //
228     Instruction *visitAdd(BinaryOperator &I);
229     Instruction *visitFAdd(BinaryOperator &I);
230     Value *OptimizePointerDifference(Value *LHS, Value *RHS, const Type *Ty);
231     Instruction *visitSub(BinaryOperator &I);
232     Instruction *visitFSub(BinaryOperator &I);
233     Instruction *visitMul(BinaryOperator &I);
234     Instruction *visitFMul(BinaryOperator &I);
235     Instruction *visitURem(BinaryOperator &I);
236     Instruction *visitSRem(BinaryOperator &I);
237     Instruction *visitFRem(BinaryOperator &I);
238     bool SimplifyDivRemOfSelect(BinaryOperator &I);
239     Instruction *commonRemTransforms(BinaryOperator &I);
240     Instruction *commonIRemTransforms(BinaryOperator &I);
241     Instruction *commonDivTransforms(BinaryOperator &I);
242     Instruction *commonIDivTransforms(BinaryOperator &I);
243     Instruction *visitUDiv(BinaryOperator &I);
244     Instruction *visitSDiv(BinaryOperator &I);
245     Instruction *visitFDiv(BinaryOperator &I);
246     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
247     Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
248     Instruction *visitAnd(BinaryOperator &I);
249     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
250     Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
251     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
252                                      Value *A, Value *B, Value *C);
253     Instruction *visitOr (BinaryOperator &I);
254     Instruction *visitXor(BinaryOperator &I);
255     Instruction *visitShl(BinaryOperator &I);
256     Instruction *visitAShr(BinaryOperator &I);
257     Instruction *visitLShr(BinaryOperator &I);
258     Instruction *commonShiftTransforms(BinaryOperator &I);
259     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
260                                       Constant *RHSC);
261     Instruction *visitFCmpInst(FCmpInst &I);
262     Instruction *visitICmpInst(ICmpInst &I);
263     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
264     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
265                                                 Instruction *LHS,
266                                                 ConstantInt *RHS);
267     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
268                                 ConstantInt *DivRHS);
269     Instruction *FoldICmpAddOpCst(ICmpInst &ICI, Value *X, ConstantInt *CI,
270                                   ICmpInst::Predicate Pred, Value *TheAdd);
271     Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
272                              ICmpInst::Predicate Cond, Instruction &I);
273     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
274                                      BinaryOperator &I);
275     Instruction *commonCastTransforms(CastInst &CI);
276     Instruction *commonIntCastTransforms(CastInst &CI);
277     Instruction *commonPointerCastTransforms(CastInst &CI);
278     Instruction *visitTrunc(TruncInst &CI);
279     Instruction *visitZExt(ZExtInst &CI);
280     Instruction *visitSExt(SExtInst &CI);
281     Instruction *visitFPTrunc(FPTruncInst &CI);
282     Instruction *visitFPExt(CastInst &CI);
283     Instruction *visitFPToUI(FPToUIInst &FI);
284     Instruction *visitFPToSI(FPToSIInst &FI);
285     Instruction *visitUIToFP(CastInst &CI);
286     Instruction *visitSIToFP(CastInst &CI);
287     Instruction *visitPtrToInt(PtrToIntInst &CI);
288     Instruction *visitIntToPtr(IntToPtrInst &CI);
289     Instruction *visitBitCast(BitCastInst &CI);
290     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
291                                 Instruction *FI);
292     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
293     Instruction *FoldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
294                               Value *A, Value *B, Instruction &Outer,
295                               SelectPatternFlavor SPF2, Value *C);
296     Instruction *visitSelectInst(SelectInst &SI);
297     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
298     Instruction *visitCallInst(CallInst &CI);
299     Instruction *visitInvokeInst(InvokeInst &II);
300
301     Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
302     Instruction *visitPHINode(PHINode &PN);
303     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
304     Instruction *visitAllocaInst(AllocaInst &AI);
305     Instruction *visitFree(Instruction &FI);
306     Instruction *visitLoadInst(LoadInst &LI);
307     Instruction *visitStoreInst(StoreInst &SI);
308     Instruction *visitBranchInst(BranchInst &BI);
309     Instruction *visitSwitchInst(SwitchInst &SI);
310     Instruction *visitInsertElementInst(InsertElementInst &IE);
311     Instruction *visitExtractElementInst(ExtractElementInst &EI);
312     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
313     Instruction *visitExtractValueInst(ExtractValueInst &EV);
314
315     // visitInstruction - Specify what to return for unhandled instructions...
316     Instruction *visitInstruction(Instruction &I) { return 0; }
317
318   private:
319     Instruction *visitCallSite(CallSite CS);
320     bool transformConstExprCastCall(CallSite CS);
321     Instruction *transformCallThroughTrampoline(CallSite CS);
322     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
323                                    bool DoXform = true);
324     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
325     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
326
327
328   public:
329     // InsertNewInstBefore - insert an instruction New before instruction Old
330     // in the program.  Add the new instruction to the worklist.
331     //
332     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
333       assert(New && New->getParent() == 0 &&
334              "New instruction already inserted into a basic block!");
335       BasicBlock *BB = Old.getParent();
336       BB->getInstList().insert(&Old, New);  // Insert inst
337       Worklist.Add(New);
338       return New;
339     }
340         
341     // ReplaceInstUsesWith - This method is to be used when an instruction is
342     // found to be dead, replacable with another preexisting expression.  Here
343     // we add all uses of I to the worklist, replace all uses of I with the new
344     // value, then return I, so that the inst combiner will know that I was
345     // modified.
346     //
347     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
348       Worklist.AddUsersToWorkList(I);   // Add all modified instrs to worklist.
349       
350       // If we are replacing the instruction with itself, this must be in a
351       // segment of unreachable code, so just clobber the instruction.
352       if (&I == V) 
353         V = UndefValue::get(I.getType());
354         
355       I.replaceAllUsesWith(V);
356       return &I;
357     }
358
359     // EraseInstFromFunction - When dealing with an instruction that has side
360     // effects or produces a void value, we can't rely on DCE to delete the
361     // instruction.  Instead, visit methods should return the value returned by
362     // this function.
363     Instruction *EraseInstFromFunction(Instruction &I) {
364       DEBUG(errs() << "IC: ERASE " << I << '\n');
365
366       assert(I.use_empty() && "Cannot erase instruction that is used!");
367       // Make sure that we reprocess all operands now that we reduced their
368       // use counts.
369       if (I.getNumOperands() < 8) {
370         for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
371           if (Instruction *Op = dyn_cast<Instruction>(*i))
372             Worklist.Add(Op);
373       }
374       Worklist.Remove(&I);
375       I.eraseFromParent();
376       MadeIRChange = true;
377       return 0;  // Don't do anything with FI
378     }
379         
380     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
381                            APInt &KnownOne, unsigned Depth = 0) const {
382       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
383     }
384     
385     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
386                            unsigned Depth = 0) const {
387       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
388     }
389     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
390       return llvm::ComputeNumSignBits(Op, TD, Depth);
391     }
392
393   private:
394
395     /// SimplifyCommutative - This performs a few simplifications for 
396     /// commutative operators.
397     bool SimplifyCommutative(BinaryOperator &I);
398
399     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
400     /// based on the demanded bits.
401     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
402                                    APInt& KnownZero, APInt& KnownOne,
403                                    unsigned Depth);
404     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
405                               APInt& KnownZero, APInt& KnownOne,
406                               unsigned Depth=0);
407         
408     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
409     /// SimplifyDemandedBits knows about.  See if the instruction has any
410     /// properties that allow us to simplify its operands.
411     bool SimplifyDemandedInstructionBits(Instruction &Inst);
412         
413     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
414                                       APInt& UndefElts, unsigned Depth = 0);
415       
416     // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
417     // which has a PHI node as operand #0, see if we can fold the instruction
418     // into the PHI (which is only possible if all operands to the PHI are
419     // constants).
420     //
421     // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
422     // that would normally be unprofitable because they strongly encourage jump
423     // threading.
424     Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
425
426     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
427     // operator and they all are only used by the PHI, PHI together their
428     // inputs, and do the operation once, to the result of the PHI.
429     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
430     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
431     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
432     Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
433
434     
435     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
436                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
437     
438     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
439                               bool isSub, Instruction &I);
440     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
441                                  bool isSigned, bool Inside, Instruction &IB);
442     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
443     Instruction *MatchBSwap(BinaryOperator &I);
444     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
445     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
446     Instruction *SimplifyMemSet(MemSetInst *MI);
447
448
449     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
450
451     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
452                                     unsigned CastOpc, int &NumCastsRemoved);
453     unsigned GetOrEnforceKnownAlignment(Value *V,
454                                         unsigned PrefAlign = 0);
455
456   };
457 } // end anonymous namespace
458
459 char InstCombiner::ID = 0;
460 static RegisterPass<InstCombiner>
461 X("instcombine", "Combine redundant instructions");
462
463 // getComplexity:  Assign a complexity or rank value to LLVM Values...
464 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
465 static unsigned getComplexity(Value *V) {
466   if (isa<Instruction>(V)) {
467     if (BinaryOperator::isNeg(V) ||
468         BinaryOperator::isFNeg(V) ||
469         BinaryOperator::isNot(V))
470       return 3;
471     return 4;
472   }
473   if (isa<Argument>(V)) return 3;
474   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
475 }
476
477 // isOnlyUse - Return true if this instruction will be deleted if we stop using
478 // it.
479 static bool isOnlyUse(Value *V) {
480   return V->hasOneUse() || isa<Constant>(V);
481 }
482
483 // getPromotedType - Return the specified type promoted as it would be to pass
484 // though a va_arg area...
485 static const Type *getPromotedType(const Type *Ty) {
486   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
487     if (ITy->getBitWidth() < 32)
488       return Type::getInt32Ty(Ty->getContext());
489   }
490   return Ty;
491 }
492
493 /// ShouldChangeType - Return true if it is desirable to convert a computation
494 /// from 'From' to 'To'.  We don't want to convert from a legal to an illegal
495 /// type for example, or from a smaller to a larger illegal type.
496 static bool ShouldChangeType(const Type *From, const Type *To,
497                              const TargetData *TD) {
498   assert(isa<IntegerType>(From) && isa<IntegerType>(To));
499   
500   // If we don't have TD, we don't know if the source/dest are legal.
501   if (!TD) return false;
502   
503   unsigned FromWidth = From->getPrimitiveSizeInBits();
504   unsigned ToWidth = To->getPrimitiveSizeInBits();
505   bool FromLegal = TD->isLegalInteger(FromWidth);
506   bool ToLegal = TD->isLegalInteger(ToWidth);
507   
508   // If this is a legal integer from type, and the result would be an illegal
509   // type, don't do the transformation.
510   if (FromLegal && !ToLegal)
511     return false;
512   
513   // Otherwise, if both are illegal, do not increase the size of the result. We
514   // do allow things like i160 -> i64, but not i64 -> i160.
515   if (!FromLegal && !ToLegal && ToWidth > FromWidth)
516     return false;
517   
518   return true;
519 }
520
521 /// getBitCastOperand - If the specified operand is a CastInst, a constant
522 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
523 /// operand value, otherwise return null.
524 static Value *getBitCastOperand(Value *V) {
525   if (Operator *O = dyn_cast<Operator>(V)) {
526     if (O->getOpcode() == Instruction::BitCast)
527       return O->getOperand(0);
528     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
529       if (GEP->hasAllZeroIndices())
530         return GEP->getPointerOperand();
531   }
532   return 0;
533 }
534
535 /// This function is a wrapper around CastInst::isEliminableCastPair. It
536 /// simply extracts arguments and returns what that function returns.
537 static Instruction::CastOps 
538 isEliminableCastPair(
539   const CastInst *CI, ///< The first cast instruction
540   unsigned opcode,       ///< The opcode of the second cast instruction
541   const Type *DstTy,     ///< The target type for the second cast instruction
542   TargetData *TD         ///< The target data for pointer size
543 ) {
544
545   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
546   const Type *MidTy = CI->getType();                  // B from above
547
548   // Get the opcodes of the two Cast instructions
549   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
550   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
551
552   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
553                                                 DstTy,
554                                   TD ? TD->getIntPtrType(CI->getContext()) : 0);
555   
556   // We don't want to form an inttoptr or ptrtoint that converts to an integer
557   // type that differs from the pointer size.
558   if ((Res == Instruction::IntToPtr &&
559           (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
560       (Res == Instruction::PtrToInt &&
561           (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
562     Res = 0;
563   
564   return Instruction::CastOps(Res);
565 }
566
567 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
568 /// in any code being generated.  It does not require codegen if V is simple
569 /// enough or if the cast can be folded into other casts.
570 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
571                               const Type *Ty, TargetData *TD) {
572   if (V->getType() == Ty || isa<Constant>(V)) return false;
573   
574   // If this is another cast that can be eliminated, it isn't codegen either.
575   if (const CastInst *CI = dyn_cast<CastInst>(V))
576     if (isEliminableCastPair(CI, opcode, Ty, TD))
577       return false;
578   return true;
579 }
580
581 // SimplifyCommutative - This performs a few simplifications for commutative
582 // operators:
583 //
584 //  1. Order operands such that they are listed from right (least complex) to
585 //     left (most complex).  This puts constants before unary operators before
586 //     binary operators.
587 //
588 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
589 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
590 //
591 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
592   bool Changed = false;
593   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
594     Changed = !I.swapOperands();
595
596   if (!I.isAssociative()) return Changed;
597   Instruction::BinaryOps Opcode = I.getOpcode();
598   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
599     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
600       if (isa<Constant>(I.getOperand(1))) {
601         Constant *Folded = ConstantExpr::get(I.getOpcode(),
602                                              cast<Constant>(I.getOperand(1)),
603                                              cast<Constant>(Op->getOperand(1)));
604         I.setOperand(0, Op->getOperand(0));
605         I.setOperand(1, Folded);
606         return true;
607       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
608         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
609             isOnlyUse(Op) && isOnlyUse(Op1)) {
610           Constant *C1 = cast<Constant>(Op->getOperand(1));
611           Constant *C2 = cast<Constant>(Op1->getOperand(1));
612
613           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
614           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
615           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
616                                                     Op1->getOperand(0),
617                                                     Op1->getName(), &I);
618           Worklist.Add(New);
619           I.setOperand(0, New);
620           I.setOperand(1, Folded);
621           return true;
622         }
623     }
624   return Changed;
625 }
626
627 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
628 // if the LHS is a constant zero (which is the 'negate' form).
629 //
630 static inline Value *dyn_castNegVal(Value *V) {
631   if (BinaryOperator::isNeg(V))
632     return BinaryOperator::getNegArgument(V);
633
634   // Constants can be considered to be negated values if they can be folded.
635   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
636     return ConstantExpr::getNeg(C);
637
638   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
639     if (C->getType()->getElementType()->isInteger())
640       return ConstantExpr::getNeg(C);
641
642   return 0;
643 }
644
645 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
646 // instruction if the LHS is a constant negative zero (which is the 'negate'
647 // form).
648 //
649 static inline Value *dyn_castFNegVal(Value *V) {
650   if (BinaryOperator::isFNeg(V))
651     return BinaryOperator::getFNegArgument(V);
652
653   // Constants can be considered to be negated values if they can be folded.
654   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
655     return ConstantExpr::getFNeg(C);
656
657   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
658     if (C->getType()->getElementType()->isFloatingPoint())
659       return ConstantExpr::getFNeg(C);
660
661   return 0;
662 }
663
664 /// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
665 /// returning the kind and providing the out parameter results if we
666 /// successfully match.
667 static SelectPatternFlavor
668 MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
669   SelectInst *SI = dyn_cast<SelectInst>(V);
670   if (SI == 0) return SPF_UNKNOWN;
671   
672   ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
673   if (ICI == 0) return SPF_UNKNOWN;
674   
675   LHS = ICI->getOperand(0);
676   RHS = ICI->getOperand(1);
677   
678   // (icmp X, Y) ? X : Y 
679   if (SI->getTrueValue() == ICI->getOperand(0) &&
680       SI->getFalseValue() == ICI->getOperand(1)) {
681     switch (ICI->getPredicate()) {
682     default: return SPF_UNKNOWN; // Equality.
683     case ICmpInst::ICMP_UGT:
684     case ICmpInst::ICMP_UGE: return SPF_UMAX;
685     case ICmpInst::ICMP_SGT:
686     case ICmpInst::ICMP_SGE: return SPF_SMAX;
687     case ICmpInst::ICMP_ULT:
688     case ICmpInst::ICMP_ULE: return SPF_UMIN;
689     case ICmpInst::ICMP_SLT:
690     case ICmpInst::ICMP_SLE: return SPF_SMIN;
691     }
692   }
693   
694   // (icmp X, Y) ? Y : X 
695   if (SI->getTrueValue() == ICI->getOperand(1) &&
696       SI->getFalseValue() == ICI->getOperand(0)) {
697     switch (ICI->getPredicate()) {
698       default: return SPF_UNKNOWN; // Equality.
699       case ICmpInst::ICMP_UGT:
700       case ICmpInst::ICMP_UGE: return SPF_UMIN;
701       case ICmpInst::ICMP_SGT:
702       case ICmpInst::ICMP_SGE: return SPF_SMIN;
703       case ICmpInst::ICMP_ULT:
704       case ICmpInst::ICMP_ULE: return SPF_UMAX;
705       case ICmpInst::ICMP_SLT:
706       case ICmpInst::ICMP_SLE: return SPF_SMAX;
707     }
708   }
709   
710   // TODO: (X > 4) ? X : 5   -->  (X >= 5) ? X : 5  -->  MAX(X, 5)
711   
712   return SPF_UNKNOWN;
713 }
714
715 /// isFreeToInvert - Return true if the specified value is free to invert (apply
716 /// ~ to).  This happens in cases where the ~ can be eliminated.
717 static inline bool isFreeToInvert(Value *V) {
718   // ~(~(X)) -> X.
719   if (BinaryOperator::isNot(V))
720     return true;
721   
722   // Constants can be considered to be not'ed values.
723   if (isa<ConstantInt>(V))
724     return true;
725   
726   // Compares can be inverted if they have a single use.
727   if (CmpInst *CI = dyn_cast<CmpInst>(V))
728     return CI->hasOneUse();
729   
730   return false;
731 }
732
733 static inline Value *dyn_castNotVal(Value *V) {
734   // If this is not(not(x)) don't return that this is a not: we want the two
735   // not's to be folded first.
736   if (BinaryOperator::isNot(V)) {
737     Value *Operand = BinaryOperator::getNotArgument(V);
738     if (!isFreeToInvert(Operand))
739       return Operand;
740   }
741
742   // Constants can be considered to be not'ed values...
743   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
744     return ConstantInt::get(C->getType(), ~C->getValue());
745   return 0;
746 }
747
748
749
750 // dyn_castFoldableMul - If this value is a multiply that can be folded into
751 // other computations (because it has a constant operand), return the
752 // non-constant operand of the multiply, and set CST to point to the multiplier.
753 // Otherwise, return null.
754 //
755 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
756   if (V->hasOneUse() && V->getType()->isInteger())
757     if (Instruction *I = dyn_cast<Instruction>(V)) {
758       if (I->getOpcode() == Instruction::Mul)
759         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
760           return I->getOperand(0);
761       if (I->getOpcode() == Instruction::Shl)
762         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
763           // The multiplier is really 1 << CST.
764           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
765           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
766           CST = ConstantInt::get(V->getType()->getContext(),
767                                  APInt(BitWidth, 1).shl(CSTVal));
768           return I->getOperand(0);
769         }
770     }
771   return 0;
772 }
773
774 /// AddOne - Add one to a ConstantInt
775 static Constant *AddOne(Constant *C) {
776   return ConstantExpr::getAdd(C, 
777     ConstantInt::get(C->getType(), 1));
778 }
779 /// SubOne - Subtract one from a ConstantInt
780 static Constant *SubOne(ConstantInt *C) {
781   return ConstantExpr::getSub(C, 
782     ConstantInt::get(C->getType(), 1));
783 }
784 /// MultiplyOverflows - True if the multiply can not be expressed in an int
785 /// this size.
786 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
787   uint32_t W = C1->getBitWidth();
788   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
789   if (sign) {
790     LHSExt.sext(W * 2);
791     RHSExt.sext(W * 2);
792   } else {
793     LHSExt.zext(W * 2);
794     RHSExt.zext(W * 2);
795   }
796
797   APInt MulExt = LHSExt * RHSExt;
798
799   if (!sign)
800     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
801   
802   APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
803   APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
804   return MulExt.slt(Min) || MulExt.sgt(Max);
805 }
806
807
808 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
809 /// specified instruction is a constant integer.  If so, check to see if there
810 /// are any bits set in the constant that are not demanded.  If so, shrink the
811 /// constant and return true.
812 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
813                                    APInt Demanded) {
814   assert(I && "No instruction?");
815   assert(OpNo < I->getNumOperands() && "Operand index too large");
816
817   // If the operand is not a constant integer, nothing to do.
818   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
819   if (!OpC) return false;
820
821   // If there are no bits set that aren't demanded, nothing to do.
822   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
823   if ((~Demanded & OpC->getValue()) == 0)
824     return false;
825
826   // This instruction is producing bits that are not demanded. Shrink the RHS.
827   Demanded &= OpC->getValue();
828   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
829   return true;
830 }
831
832 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
833 // set of known zero and one bits, compute the maximum and minimum values that
834 // could have the specified known zero and known one bits, returning them in
835 // min/max.
836 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
837                                                    const APInt& KnownOne,
838                                                    APInt& Min, APInt& Max) {
839   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
840          KnownZero.getBitWidth() == Min.getBitWidth() &&
841          KnownZero.getBitWidth() == Max.getBitWidth() &&
842          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
843   APInt UnknownBits = ~(KnownZero|KnownOne);
844
845   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
846   // bit if it is unknown.
847   Min = KnownOne;
848   Max = KnownOne|UnknownBits;
849   
850   if (UnknownBits.isNegative()) { // Sign bit is unknown
851     Min.set(Min.getBitWidth()-1);
852     Max.clear(Max.getBitWidth()-1);
853   }
854 }
855
856 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
857 // a set of known zero and one bits, compute the maximum and minimum values that
858 // could have the specified known zero and known one bits, returning them in
859 // min/max.
860 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
861                                                      const APInt &KnownOne,
862                                                      APInt &Min, APInt &Max) {
863   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
864          KnownZero.getBitWidth() == Min.getBitWidth() &&
865          KnownZero.getBitWidth() == Max.getBitWidth() &&
866          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
867   APInt UnknownBits = ~(KnownZero|KnownOne);
868   
869   // The minimum value is when the unknown bits are all zeros.
870   Min = KnownOne;
871   // The maximum value is when the unknown bits are all ones.
872   Max = KnownOne|UnknownBits;
873 }
874
875 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
876 /// SimplifyDemandedBits knows about.  See if the instruction has any
877 /// properties that allow us to simplify its operands.
878 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
879   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
880   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
881   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
882   
883   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
884                                      KnownZero, KnownOne, 0);
885   if (V == 0) return false;
886   if (V == &Inst) return true;
887   ReplaceInstUsesWith(Inst, V);
888   return true;
889 }
890
891 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
892 /// specified instruction operand if possible, updating it in place.  It returns
893 /// true if it made any change and false otherwise.
894 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
895                                         APInt &KnownZero, APInt &KnownOne,
896                                         unsigned Depth) {
897   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
898                                           KnownZero, KnownOne, Depth);
899   if (NewVal == 0) return false;
900   U = NewVal;
901   return true;
902 }
903
904
905 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
906 /// value based on the demanded bits.  When this function is called, it is known
907 /// that only the bits set in DemandedMask of the result of V are ever used
908 /// downstream. Consequently, depending on the mask and V, it may be possible
909 /// to replace V with a constant or one of its operands. In such cases, this
910 /// function does the replacement and returns true. In all other cases, it
911 /// returns false after analyzing the expression and setting KnownOne and known
912 /// to be one in the expression.  KnownZero contains all the bits that are known
913 /// to be zero in the expression. These are provided to potentially allow the
914 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
915 /// the expression. KnownOne and KnownZero always follow the invariant that 
916 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
917 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
918 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
919 /// and KnownOne must all be the same.
920 ///
921 /// This returns null if it did not change anything and it permits no
922 /// simplification.  This returns V itself if it did some simplification of V's
923 /// operands based on the information about what bits are demanded. This returns
924 /// some other non-null value if it found out that V is equal to another value
925 /// in the context where the specified bits are demanded, but not for all users.
926 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
927                                              APInt &KnownZero, APInt &KnownOne,
928                                              unsigned Depth) {
929   assert(V != 0 && "Null pointer of Value???");
930   assert(Depth <= 6 && "Limit Search Depth");
931   uint32_t BitWidth = DemandedMask.getBitWidth();
932   const Type *VTy = V->getType();
933   assert((TD || !isa<PointerType>(VTy)) &&
934          "SimplifyDemandedBits needs to know bit widths!");
935   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
936          (!VTy->isIntOrIntVector() ||
937           VTy->getScalarSizeInBits() == BitWidth) &&
938          KnownZero.getBitWidth() == BitWidth &&
939          KnownOne.getBitWidth() == BitWidth &&
940          "Value *V, DemandedMask, KnownZero and KnownOne "
941          "must have same BitWidth");
942   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
943     // We know all of the bits for a constant!
944     KnownOne = CI->getValue() & DemandedMask;
945     KnownZero = ~KnownOne & DemandedMask;
946     return 0;
947   }
948   if (isa<ConstantPointerNull>(V)) {
949     // We know all of the bits for a constant!
950     KnownOne.clear();
951     KnownZero = DemandedMask;
952     return 0;
953   }
954
955   KnownZero.clear();
956   KnownOne.clear();
957   if (DemandedMask == 0) {   // Not demanding any bits from V.
958     if (isa<UndefValue>(V))
959       return 0;
960     return UndefValue::get(VTy);
961   }
962   
963   if (Depth == 6)        // Limit search depth.
964     return 0;
965   
966   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
967   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
968
969   Instruction *I = dyn_cast<Instruction>(V);
970   if (!I) {
971     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
972     return 0;        // Only analyze instructions.
973   }
974
975   // If there are multiple uses of this value and we aren't at the root, then
976   // we can't do any simplifications of the operands, because DemandedMask
977   // only reflects the bits demanded by *one* of the users.
978   if (Depth != 0 && !I->hasOneUse()) {
979     // Despite the fact that we can't simplify this instruction in all User's
980     // context, we can at least compute the knownzero/knownone bits, and we can
981     // do simplifications that apply to *just* the one user if we know that
982     // this instruction has a simpler value in that context.
983     if (I->getOpcode() == Instruction::And) {
984       // If either the LHS or the RHS are Zero, the result is zero.
985       ComputeMaskedBits(I->getOperand(1), DemandedMask,
986                         RHSKnownZero, RHSKnownOne, Depth+1);
987       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
988                         LHSKnownZero, LHSKnownOne, Depth+1);
989       
990       // If all of the demanded bits are known 1 on one side, return the other.
991       // These bits cannot contribute to the result of the 'and' in this
992       // context.
993       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
994           (DemandedMask & ~LHSKnownZero))
995         return I->getOperand(0);
996       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
997           (DemandedMask & ~RHSKnownZero))
998         return I->getOperand(1);
999       
1000       // If all of the demanded bits in the inputs are known zeros, return zero.
1001       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1002         return Constant::getNullValue(VTy);
1003       
1004     } else if (I->getOpcode() == Instruction::Or) {
1005       // We can simplify (X|Y) -> X or Y in the user's context if we know that
1006       // only bits from X or Y are demanded.
1007       
1008       // If either the LHS or the RHS are One, the result is One.
1009       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
1010                         RHSKnownZero, RHSKnownOne, Depth+1);
1011       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
1012                         LHSKnownZero, LHSKnownOne, Depth+1);
1013       
1014       // If all of the demanded bits are known zero on one side, return the
1015       // other.  These bits cannot contribute to the result of the 'or' in this
1016       // context.
1017       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
1018           (DemandedMask & ~LHSKnownOne))
1019         return I->getOperand(0);
1020       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
1021           (DemandedMask & ~RHSKnownOne))
1022         return I->getOperand(1);
1023       
1024       // If all of the potentially set bits on one side are known to be set on
1025       // the other side, just use the 'other' side.
1026       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
1027           (DemandedMask & (~RHSKnownZero)))
1028         return I->getOperand(0);
1029       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1030           (DemandedMask & (~LHSKnownZero)))
1031         return I->getOperand(1);
1032     }
1033     
1034     // Compute the KnownZero/KnownOne bits to simplify things downstream.
1035     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
1036     return 0;
1037   }
1038   
1039   // If this is the root being simplified, allow it to have multiple uses,
1040   // just set the DemandedMask to all bits so that we can try to simplify the
1041   // operands.  This allows visitTruncInst (for example) to simplify the
1042   // operand of a trunc without duplicating all the logic below.
1043   if (Depth == 0 && !V->hasOneUse())
1044     DemandedMask = APInt::getAllOnesValue(BitWidth);
1045   
1046   switch (I->getOpcode()) {
1047   default:
1048     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1049     break;
1050   case Instruction::And:
1051     // If either the LHS or the RHS are Zero, the result is zero.
1052     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1053                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1054         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
1055                              LHSKnownZero, LHSKnownOne, Depth+1))
1056       return I;
1057     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1058     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1059
1060     // If all of the demanded bits are known 1 on one side, return the other.
1061     // These bits cannot contribute to the result of the 'and'.
1062     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
1063         (DemandedMask & ~LHSKnownZero))
1064       return I->getOperand(0);
1065     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
1066         (DemandedMask & ~RHSKnownZero))
1067       return I->getOperand(1);
1068     
1069     // If all of the demanded bits in the inputs are known zeros, return zero.
1070     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1071       return Constant::getNullValue(VTy);
1072       
1073     // If the RHS is a constant, see if we can simplify it.
1074     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1075       return I;
1076       
1077     // Output known-1 bits are only known if set in both the LHS & RHS.
1078     RHSKnownOne &= LHSKnownOne;
1079     // Output known-0 are known to be clear if zero in either the LHS | RHS.
1080     RHSKnownZero |= LHSKnownZero;
1081     break;
1082   case Instruction::Or:
1083     // If either the LHS or the RHS are One, the result is One.
1084     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1085                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1086         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
1087                              LHSKnownZero, LHSKnownOne, Depth+1))
1088       return I;
1089     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1090     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1091     
1092     // If all of the demanded bits are known zero on one side, return the other.
1093     // These bits cannot contribute to the result of the 'or'.
1094     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
1095         (DemandedMask & ~LHSKnownOne))
1096       return I->getOperand(0);
1097     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
1098         (DemandedMask & ~RHSKnownOne))
1099       return I->getOperand(1);
1100
1101     // If all of the potentially set bits on one side are known to be set on
1102     // the other side, just use the 'other' side.
1103     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
1104         (DemandedMask & (~RHSKnownZero)))
1105       return I->getOperand(0);
1106     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1107         (DemandedMask & (~LHSKnownZero)))
1108       return I->getOperand(1);
1109         
1110     // If the RHS is a constant, see if we can simplify it.
1111     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1112       return I;
1113           
1114     // Output known-0 bits are only known if clear in both the LHS & RHS.
1115     RHSKnownZero &= LHSKnownZero;
1116     // Output known-1 are known to be set if set in either the LHS | RHS.
1117     RHSKnownOne |= LHSKnownOne;
1118     break;
1119   case Instruction::Xor: {
1120     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1121                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1122         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1123                              LHSKnownZero, LHSKnownOne, Depth+1))
1124       return I;
1125     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1126     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1127     
1128     // If all of the demanded bits are known zero on one side, return the other.
1129     // These bits cannot contribute to the result of the 'xor'.
1130     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1131       return I->getOperand(0);
1132     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1133       return I->getOperand(1);
1134     
1135     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1136     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1137                          (RHSKnownOne & LHSKnownOne);
1138     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1139     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1140                         (RHSKnownOne & LHSKnownZero);
1141     
1142     // If all of the demanded bits are known to be zero on one side or the
1143     // other, turn this into an *inclusive* or.
1144     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1145     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1146       Instruction *Or = 
1147         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1148                                  I->getName());
1149       return InsertNewInstBefore(Or, *I);
1150     }
1151     
1152     // If all of the demanded bits on one side are known, and all of the set
1153     // bits on that side are also known to be set on the other side, turn this
1154     // into an AND, as we know the bits will be cleared.
1155     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1156     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1157       // all known
1158       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1159         Constant *AndC = Constant::getIntegerValue(VTy,
1160                                                    ~RHSKnownOne & DemandedMask);
1161         Instruction *And = 
1162           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1163         return InsertNewInstBefore(And, *I);
1164       }
1165     }
1166     
1167     // If the RHS is a constant, see if we can simplify it.
1168     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1169     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1170       return I;
1171     
1172     // If our LHS is an 'and' and if it has one use, and if any of the bits we
1173     // are flipping are known to be set, then the xor is just resetting those
1174     // bits to zero.  We can just knock out bits from the 'and' and the 'xor',
1175     // simplifying both of them.
1176     if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1177       if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1178           isa<ConstantInt>(I->getOperand(1)) &&
1179           isa<ConstantInt>(LHSInst->getOperand(1)) &&
1180           (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1181         ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1182         ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1183         APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1184         
1185         Constant *AndC =
1186           ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1187         Instruction *NewAnd = 
1188           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1189         InsertNewInstBefore(NewAnd, *I);
1190         
1191         Constant *XorC =
1192           ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1193         Instruction *NewXor =
1194           BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1195         return InsertNewInstBefore(NewXor, *I);
1196       }
1197           
1198           
1199     RHSKnownZero = KnownZeroOut;
1200     RHSKnownOne  = KnownOneOut;
1201     break;
1202   }
1203   case Instruction::Select:
1204     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1205                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1206         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1207                              LHSKnownZero, LHSKnownOne, Depth+1))
1208       return I;
1209     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1210     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1211     
1212     // If the operands are constants, see if we can simplify them.
1213     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1214         ShrinkDemandedConstant(I, 2, DemandedMask))
1215       return I;
1216     
1217     // Only known if known in both the LHS and RHS.
1218     RHSKnownOne &= LHSKnownOne;
1219     RHSKnownZero &= LHSKnownZero;
1220     break;
1221   case Instruction::Trunc: {
1222     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1223     DemandedMask.zext(truncBf);
1224     RHSKnownZero.zext(truncBf);
1225     RHSKnownOne.zext(truncBf);
1226     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1227                              RHSKnownZero, RHSKnownOne, Depth+1))
1228       return I;
1229     DemandedMask.trunc(BitWidth);
1230     RHSKnownZero.trunc(BitWidth);
1231     RHSKnownOne.trunc(BitWidth);
1232     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1233     break;
1234   }
1235   case Instruction::BitCast:
1236     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1237       return false;  // vector->int or fp->int?
1238
1239     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1240       if (const VectorType *SrcVTy =
1241             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1242         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1243           // Don't touch a bitcast between vectors of different element counts.
1244           return false;
1245       } else
1246         // Don't touch a scalar-to-vector bitcast.
1247         return false;
1248     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1249       // Don't touch a vector-to-scalar bitcast.
1250       return false;
1251
1252     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1253                              RHSKnownZero, RHSKnownOne, Depth+1))
1254       return I;
1255     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1256     break;
1257   case Instruction::ZExt: {
1258     // Compute the bits in the result that are not present in the input.
1259     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1260     
1261     DemandedMask.trunc(SrcBitWidth);
1262     RHSKnownZero.trunc(SrcBitWidth);
1263     RHSKnownOne.trunc(SrcBitWidth);
1264     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1265                              RHSKnownZero, RHSKnownOne, Depth+1))
1266       return I;
1267     DemandedMask.zext(BitWidth);
1268     RHSKnownZero.zext(BitWidth);
1269     RHSKnownOne.zext(BitWidth);
1270     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1271     // The top bits are known to be zero.
1272     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1273     break;
1274   }
1275   case Instruction::SExt: {
1276     // Compute the bits in the result that are not present in the input.
1277     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1278     
1279     APInt InputDemandedBits = DemandedMask & 
1280                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1281
1282     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1283     // If any of the sign extended bits are demanded, we know that the sign
1284     // bit is demanded.
1285     if ((NewBits & DemandedMask) != 0)
1286       InputDemandedBits.set(SrcBitWidth-1);
1287       
1288     InputDemandedBits.trunc(SrcBitWidth);
1289     RHSKnownZero.trunc(SrcBitWidth);
1290     RHSKnownOne.trunc(SrcBitWidth);
1291     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1292                              RHSKnownZero, RHSKnownOne, Depth+1))
1293       return I;
1294     InputDemandedBits.zext(BitWidth);
1295     RHSKnownZero.zext(BitWidth);
1296     RHSKnownOne.zext(BitWidth);
1297     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1298       
1299     // If the sign bit of the input is known set or clear, then we know the
1300     // top bits of the result.
1301
1302     // If the input sign bit is known zero, or if the NewBits are not demanded
1303     // convert this into a zero extension.
1304     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1305       // Convert to ZExt cast
1306       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1307       return InsertNewInstBefore(NewCast, *I);
1308     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1309       RHSKnownOne |= NewBits;
1310     }
1311     break;
1312   }
1313   case Instruction::Add: {
1314     // Figure out what the input bits are.  If the top bits of the and result
1315     // are not demanded, then the add doesn't demand them from its input
1316     // either.
1317     unsigned NLZ = DemandedMask.countLeadingZeros();
1318       
1319     // If there is a constant on the RHS, there are a variety of xformations
1320     // we can do.
1321     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1322       // If null, this should be simplified elsewhere.  Some of the xforms here
1323       // won't work if the RHS is zero.
1324       if (RHS->isZero())
1325         break;
1326       
1327       // If the top bit of the output is demanded, demand everything from the
1328       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1329       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1330
1331       // Find information about known zero/one bits in the input.
1332       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1333                                LHSKnownZero, LHSKnownOne, Depth+1))
1334         return I;
1335
1336       // If the RHS of the add has bits set that can't affect the input, reduce
1337       // the constant.
1338       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1339         return I;
1340       
1341       // Avoid excess work.
1342       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1343         break;
1344       
1345       // Turn it into OR if input bits are zero.
1346       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1347         Instruction *Or =
1348           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1349                                    I->getName());
1350         return InsertNewInstBefore(Or, *I);
1351       }
1352       
1353       // We can say something about the output known-zero and known-one bits,
1354       // depending on potential carries from the input constant and the
1355       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1356       // bits set and the RHS constant is 0x01001, then we know we have a known
1357       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1358       
1359       // To compute this, we first compute the potential carry bits.  These are
1360       // the bits which may be modified.  I'm not aware of a better way to do
1361       // this scan.
1362       const APInt &RHSVal = RHS->getValue();
1363       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1364       
1365       // Now that we know which bits have carries, compute the known-1/0 sets.
1366       
1367       // Bits are known one if they are known zero in one operand and one in the
1368       // other, and there is no input carry.
1369       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1370                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1371       
1372       // Bits are known zero if they are known zero in both operands and there
1373       // is no input carry.
1374       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1375     } else {
1376       // If the high-bits of this ADD are not demanded, then it does not demand
1377       // the high bits of its LHS or RHS.
1378       if (DemandedMask[BitWidth-1] == 0) {
1379         // Right fill the mask of bits for this ADD to demand the most
1380         // significant bit and all those below it.
1381         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1382         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1383                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1384             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1385                                  LHSKnownZero, LHSKnownOne, Depth+1))
1386           return I;
1387       }
1388     }
1389     break;
1390   }
1391   case Instruction::Sub:
1392     // If the high-bits of this SUB are not demanded, then it does not demand
1393     // the high bits of its LHS or RHS.
1394     if (DemandedMask[BitWidth-1] == 0) {
1395       // Right fill the mask of bits for this SUB to demand the most
1396       // significant bit and all those below it.
1397       uint32_t NLZ = DemandedMask.countLeadingZeros();
1398       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1399       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1400                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1401           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1402                                LHSKnownZero, LHSKnownOne, Depth+1))
1403         return I;
1404     }
1405     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1406     // the known zeros and ones.
1407     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1408     break;
1409   case Instruction::Shl:
1410     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1411       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1412       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1413       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1414                                RHSKnownZero, RHSKnownOne, Depth+1))
1415         return I;
1416       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1417       RHSKnownZero <<= ShiftAmt;
1418       RHSKnownOne  <<= ShiftAmt;
1419       // low bits known zero.
1420       if (ShiftAmt)
1421         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1422     }
1423     break;
1424   case Instruction::LShr:
1425     // For a logical shift right
1426     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1427       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1428       
1429       // Unsigned shift right.
1430       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1431       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1432                                RHSKnownZero, RHSKnownOne, Depth+1))
1433         return I;
1434       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1435       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1436       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1437       if (ShiftAmt) {
1438         // Compute the new bits that are at the top now.
1439         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1440         RHSKnownZero |= HighBits;  // high bits known zero.
1441       }
1442     }
1443     break;
1444   case Instruction::AShr:
1445     // If this is an arithmetic shift right and only the low-bit is set, we can
1446     // always convert this into a logical shr, even if the shift amount is
1447     // variable.  The low bit of the shift cannot be an input sign bit unless
1448     // the shift amount is >= the size of the datatype, which is undefined.
1449     if (DemandedMask == 1) {
1450       // Perform the logical shift right.
1451       Instruction *NewVal = BinaryOperator::CreateLShr(
1452                         I->getOperand(0), I->getOperand(1), I->getName());
1453       return InsertNewInstBefore(NewVal, *I);
1454     }    
1455
1456     // If the sign bit is the only bit demanded by this ashr, then there is no
1457     // need to do it, the shift doesn't change the high bit.
1458     if (DemandedMask.isSignBit())
1459       return I->getOperand(0);
1460     
1461     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1462       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1463       
1464       // Signed shift right.
1465       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1466       // If any of the "high bits" are demanded, we should set the sign bit as
1467       // demanded.
1468       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1469         DemandedMaskIn.set(BitWidth-1);
1470       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1471                                RHSKnownZero, RHSKnownOne, Depth+1))
1472         return I;
1473       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1474       // Compute the new bits that are at the top now.
1475       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1476       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1477       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1478         
1479       // Handle the sign bits.
1480       APInt SignBit(APInt::getSignBit(BitWidth));
1481       // Adjust to where it is now in the mask.
1482       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1483         
1484       // If the input sign bit is known to be zero, or if none of the top bits
1485       // are demanded, turn this into an unsigned shift right.
1486       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1487           (HighBits & ~DemandedMask) == HighBits) {
1488         // Perform the logical shift right.
1489         Instruction *NewVal = BinaryOperator::CreateLShr(
1490                           I->getOperand(0), SA, I->getName());
1491         return InsertNewInstBefore(NewVal, *I);
1492       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1493         RHSKnownOne |= HighBits;
1494       }
1495     }
1496     break;
1497   case Instruction::SRem:
1498     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1499       APInt RA = Rem->getValue().abs();
1500       if (RA.isPowerOf2()) {
1501         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1502           return I->getOperand(0);
1503
1504         APInt LowBits = RA - 1;
1505         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1506         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1507                                  LHSKnownZero, LHSKnownOne, Depth+1))
1508           return I;
1509
1510         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1511           LHSKnownZero |= ~LowBits;
1512
1513         KnownZero |= LHSKnownZero & DemandedMask;
1514
1515         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1516       }
1517     }
1518     break;
1519   case Instruction::URem: {
1520     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1521     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1522     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1523                              KnownZero2, KnownOne2, Depth+1) ||
1524         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1525                              KnownZero2, KnownOne2, Depth+1))
1526       return I;
1527
1528     unsigned Leaders = KnownZero2.countLeadingOnes();
1529     Leaders = std::max(Leaders,
1530                        KnownZero2.countLeadingOnes());
1531     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1532     break;
1533   }
1534   case Instruction::Call:
1535     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1536       switch (II->getIntrinsicID()) {
1537       default: break;
1538       case Intrinsic::bswap: {
1539         // If the only bits demanded come from one byte of the bswap result,
1540         // just shift the input byte into position to eliminate the bswap.
1541         unsigned NLZ = DemandedMask.countLeadingZeros();
1542         unsigned NTZ = DemandedMask.countTrailingZeros();
1543           
1544         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1545         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1546         // have 14 leading zeros, round to 8.
1547         NLZ &= ~7;
1548         NTZ &= ~7;
1549         // If we need exactly one byte, we can do this transformation.
1550         if (BitWidth-NLZ-NTZ == 8) {
1551           unsigned ResultBit = NTZ;
1552           unsigned InputBit = BitWidth-NTZ-8;
1553           
1554           // Replace this with either a left or right shift to get the byte into
1555           // the right place.
1556           Instruction *NewVal;
1557           if (InputBit > ResultBit)
1558             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1559                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1560           else
1561             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1562                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1563           NewVal->takeName(I);
1564           return InsertNewInstBefore(NewVal, *I);
1565         }
1566           
1567         // TODO: Could compute known zero/one bits based on the input.
1568         break;
1569       }
1570       }
1571     }
1572     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1573     break;
1574   }
1575   
1576   // If the client is only demanding bits that we know, return the known
1577   // constant.
1578   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1579     return Constant::getIntegerValue(VTy, RHSKnownOne);
1580   return false;
1581 }
1582
1583
1584 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1585 /// any number of elements. DemandedElts contains the set of elements that are
1586 /// actually used by the caller.  This method analyzes which elements of the
1587 /// operand are undef and returns that information in UndefElts.
1588 ///
1589 /// If the information about demanded elements can be used to simplify the
1590 /// operation, the operation is simplified, then the resultant value is
1591 /// returned.  This returns null if no change was made.
1592 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1593                                                 APInt& UndefElts,
1594                                                 unsigned Depth) {
1595   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1596   APInt EltMask(APInt::getAllOnesValue(VWidth));
1597   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1598
1599   if (isa<UndefValue>(V)) {
1600     // If the entire vector is undefined, just return this info.
1601     UndefElts = EltMask;
1602     return 0;
1603   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1604     UndefElts = EltMask;
1605     return UndefValue::get(V->getType());
1606   }
1607
1608   UndefElts = 0;
1609   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1610     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1611     Constant *Undef = UndefValue::get(EltTy);
1612
1613     std::vector<Constant*> Elts;
1614     for (unsigned i = 0; i != VWidth; ++i)
1615       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1616         Elts.push_back(Undef);
1617         UndefElts.set(i);
1618       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1619         Elts.push_back(Undef);
1620         UndefElts.set(i);
1621       } else {                               // Otherwise, defined.
1622         Elts.push_back(CP->getOperand(i));
1623       }
1624
1625     // If we changed the constant, return it.
1626     Constant *NewCP = ConstantVector::get(Elts);
1627     return NewCP != CP ? NewCP : 0;
1628   } else if (isa<ConstantAggregateZero>(V)) {
1629     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1630     // set to undef.
1631     
1632     // Check if this is identity. If so, return 0 since we are not simplifying
1633     // anything.
1634     if (DemandedElts == ((1ULL << VWidth) -1))
1635       return 0;
1636     
1637     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1638     Constant *Zero = Constant::getNullValue(EltTy);
1639     Constant *Undef = UndefValue::get(EltTy);
1640     std::vector<Constant*> Elts;
1641     for (unsigned i = 0; i != VWidth; ++i) {
1642       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1643       Elts.push_back(Elt);
1644     }
1645     UndefElts = DemandedElts ^ EltMask;
1646     return ConstantVector::get(Elts);
1647   }
1648   
1649   // Limit search depth.
1650   if (Depth == 10)
1651     return 0;
1652
1653   // If multiple users are using the root value, procede with
1654   // simplification conservatively assuming that all elements
1655   // are needed.
1656   if (!V->hasOneUse()) {
1657     // Quit if we find multiple users of a non-root value though.
1658     // They'll be handled when it's their turn to be visited by
1659     // the main instcombine process.
1660     if (Depth != 0)
1661       // TODO: Just compute the UndefElts information recursively.
1662       return 0;
1663
1664     // Conservatively assume that all elements are needed.
1665     DemandedElts = EltMask;
1666   }
1667   
1668   Instruction *I = dyn_cast<Instruction>(V);
1669   if (!I) return 0;        // Only analyze instructions.
1670   
1671   bool MadeChange = false;
1672   APInt UndefElts2(VWidth, 0);
1673   Value *TmpV;
1674   switch (I->getOpcode()) {
1675   default: break;
1676     
1677   case Instruction::InsertElement: {
1678     // If this is a variable index, we don't know which element it overwrites.
1679     // demand exactly the same input as we produce.
1680     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1681     if (Idx == 0) {
1682       // Note that we can't propagate undef elt info, because we don't know
1683       // which elt is getting updated.
1684       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1685                                         UndefElts2, Depth+1);
1686       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1687       break;
1688     }
1689     
1690     // If this is inserting an element that isn't demanded, remove this
1691     // insertelement.
1692     unsigned IdxNo = Idx->getZExtValue();
1693     if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1694       Worklist.Add(I);
1695       return I->getOperand(0);
1696     }
1697     
1698     // Otherwise, the element inserted overwrites whatever was there, so the
1699     // input demanded set is simpler than the output set.
1700     APInt DemandedElts2 = DemandedElts;
1701     DemandedElts2.clear(IdxNo);
1702     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1703                                       UndefElts, Depth+1);
1704     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1705
1706     // The inserted element is defined.
1707     UndefElts.clear(IdxNo);
1708     break;
1709   }
1710   case Instruction::ShuffleVector: {
1711     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1712     uint64_t LHSVWidth =
1713       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1714     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1715     for (unsigned i = 0; i < VWidth; i++) {
1716       if (DemandedElts[i]) {
1717         unsigned MaskVal = Shuffle->getMaskValue(i);
1718         if (MaskVal != -1u) {
1719           assert(MaskVal < LHSVWidth * 2 &&
1720                  "shufflevector mask index out of range!");
1721           if (MaskVal < LHSVWidth)
1722             LeftDemanded.set(MaskVal);
1723           else
1724             RightDemanded.set(MaskVal - LHSVWidth);
1725         }
1726       }
1727     }
1728
1729     APInt UndefElts4(LHSVWidth, 0);
1730     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1731                                       UndefElts4, Depth+1);
1732     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1733
1734     APInt UndefElts3(LHSVWidth, 0);
1735     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1736                                       UndefElts3, Depth+1);
1737     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1738
1739     bool NewUndefElts = false;
1740     for (unsigned i = 0; i < VWidth; i++) {
1741       unsigned MaskVal = Shuffle->getMaskValue(i);
1742       if (MaskVal == -1u) {
1743         UndefElts.set(i);
1744       } else if (MaskVal < LHSVWidth) {
1745         if (UndefElts4[MaskVal]) {
1746           NewUndefElts = true;
1747           UndefElts.set(i);
1748         }
1749       } else {
1750         if (UndefElts3[MaskVal - LHSVWidth]) {
1751           NewUndefElts = true;
1752           UndefElts.set(i);
1753         }
1754       }
1755     }
1756
1757     if (NewUndefElts) {
1758       // Add additional discovered undefs.
1759       std::vector<Constant*> Elts;
1760       for (unsigned i = 0; i < VWidth; ++i) {
1761         if (UndefElts[i])
1762           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
1763         else
1764           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
1765                                           Shuffle->getMaskValue(i)));
1766       }
1767       I->setOperand(2, ConstantVector::get(Elts));
1768       MadeChange = true;
1769     }
1770     break;
1771   }
1772   case Instruction::BitCast: {
1773     // Vector->vector casts only.
1774     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1775     if (!VTy) break;
1776     unsigned InVWidth = VTy->getNumElements();
1777     APInt InputDemandedElts(InVWidth, 0);
1778     unsigned Ratio;
1779
1780     if (VWidth == InVWidth) {
1781       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1782       // elements as are demanded of us.
1783       Ratio = 1;
1784       InputDemandedElts = DemandedElts;
1785     } else if (VWidth > InVWidth) {
1786       // Untested so far.
1787       break;
1788       
1789       // If there are more elements in the result than there are in the source,
1790       // then an input element is live if any of the corresponding output
1791       // elements are live.
1792       Ratio = VWidth/InVWidth;
1793       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1794         if (DemandedElts[OutIdx])
1795           InputDemandedElts.set(OutIdx/Ratio);
1796       }
1797     } else {
1798       // Untested so far.
1799       break;
1800       
1801       // If there are more elements in the source than there are in the result,
1802       // then an input element is live if the corresponding output element is
1803       // live.
1804       Ratio = InVWidth/VWidth;
1805       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1806         if (DemandedElts[InIdx/Ratio])
1807           InputDemandedElts.set(InIdx);
1808     }
1809     
1810     // div/rem demand all inputs, because they don't want divide by zero.
1811     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1812                                       UndefElts2, Depth+1);
1813     if (TmpV) {
1814       I->setOperand(0, TmpV);
1815       MadeChange = true;
1816     }
1817     
1818     UndefElts = UndefElts2;
1819     if (VWidth > InVWidth) {
1820       llvm_unreachable("Unimp");
1821       // If there are more elements in the result than there are in the source,
1822       // then an output element is undef if the corresponding input element is
1823       // undef.
1824       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1825         if (UndefElts2[OutIdx/Ratio])
1826           UndefElts.set(OutIdx);
1827     } else if (VWidth < InVWidth) {
1828       llvm_unreachable("Unimp");
1829       // If there are more elements in the source than there are in the result,
1830       // then a result element is undef if all of the corresponding input
1831       // elements are undef.
1832       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1833       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1834         if (!UndefElts2[InIdx])            // Not undef?
1835           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1836     }
1837     break;
1838   }
1839   case Instruction::And:
1840   case Instruction::Or:
1841   case Instruction::Xor:
1842   case Instruction::Add:
1843   case Instruction::Sub:
1844   case Instruction::Mul:
1845     // div/rem demand all inputs, because they don't want divide by zero.
1846     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1847                                       UndefElts, Depth+1);
1848     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1849     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1850                                       UndefElts2, Depth+1);
1851     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1852       
1853     // Output elements are undefined if both are undefined.  Consider things
1854     // like undef&0.  The result is known zero, not undef.
1855     UndefElts &= UndefElts2;
1856     break;
1857     
1858   case Instruction::Call: {
1859     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1860     if (!II) break;
1861     switch (II->getIntrinsicID()) {
1862     default: break;
1863       
1864     // Binary vector operations that work column-wise.  A dest element is a
1865     // function of the corresponding input elements from the two inputs.
1866     case Intrinsic::x86_sse_sub_ss:
1867     case Intrinsic::x86_sse_mul_ss:
1868     case Intrinsic::x86_sse_min_ss:
1869     case Intrinsic::x86_sse_max_ss:
1870     case Intrinsic::x86_sse2_sub_sd:
1871     case Intrinsic::x86_sse2_mul_sd:
1872     case Intrinsic::x86_sse2_min_sd:
1873     case Intrinsic::x86_sse2_max_sd:
1874       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1875                                         UndefElts, Depth+1);
1876       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1877       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1878                                         UndefElts2, Depth+1);
1879       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1880
1881       // If only the low elt is demanded and this is a scalarizable intrinsic,
1882       // scalarize it now.
1883       if (DemandedElts == 1) {
1884         switch (II->getIntrinsicID()) {
1885         default: break;
1886         case Intrinsic::x86_sse_sub_ss:
1887         case Intrinsic::x86_sse_mul_ss:
1888         case Intrinsic::x86_sse2_sub_sd:
1889         case Intrinsic::x86_sse2_mul_sd:
1890           // TODO: Lower MIN/MAX/ABS/etc
1891           Value *LHS = II->getOperand(1);
1892           Value *RHS = II->getOperand(2);
1893           // Extract the element as scalars.
1894           LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS, 
1895             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1896           RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1897             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1898           
1899           switch (II->getIntrinsicID()) {
1900           default: llvm_unreachable("Case stmts out of sync!");
1901           case Intrinsic::x86_sse_sub_ss:
1902           case Intrinsic::x86_sse2_sub_sd:
1903             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1904                                                         II->getName()), *II);
1905             break;
1906           case Intrinsic::x86_sse_mul_ss:
1907           case Intrinsic::x86_sse2_mul_sd:
1908             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1909                                                          II->getName()), *II);
1910             break;
1911           }
1912           
1913           Instruction *New =
1914             InsertElementInst::Create(
1915               UndefValue::get(II->getType()), TmpV,
1916               ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
1917           InsertNewInstBefore(New, *II);
1918           return New;
1919         }            
1920       }
1921         
1922       // Output elements are undefined if both are undefined.  Consider things
1923       // like undef&0.  The result is known zero, not undef.
1924       UndefElts &= UndefElts2;
1925       break;
1926     }
1927     break;
1928   }
1929   }
1930   return MadeChange ? I : 0;
1931 }
1932
1933
1934 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1935 /// function is designed to check a chain of associative operators for a
1936 /// potential to apply a certain optimization.  Since the optimization may be
1937 /// applicable if the expression was reassociated, this checks the chain, then
1938 /// reassociates the expression as necessary to expose the optimization
1939 /// opportunity.  This makes use of a special Functor, which must define
1940 /// 'shouldApply' and 'apply' methods.
1941 ///
1942 template<typename Functor>
1943 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1944   unsigned Opcode = Root.getOpcode();
1945   Value *LHS = Root.getOperand(0);
1946
1947   // Quick check, see if the immediate LHS matches...
1948   if (F.shouldApply(LHS))
1949     return F.apply(Root);
1950
1951   // Otherwise, if the LHS is not of the same opcode as the root, return.
1952   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1953   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1954     // Should we apply this transform to the RHS?
1955     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1956
1957     // If not to the RHS, check to see if we should apply to the LHS...
1958     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1959       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1960       ShouldApply = true;
1961     }
1962
1963     // If the functor wants to apply the optimization to the RHS of LHSI,
1964     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1965     if (ShouldApply) {
1966       // Now all of the instructions are in the current basic block, go ahead
1967       // and perform the reassociation.
1968       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1969
1970       // First move the selected RHS to the LHS of the root...
1971       Root.setOperand(0, LHSI->getOperand(1));
1972
1973       // Make what used to be the LHS of the root be the user of the root...
1974       Value *ExtraOperand = TmpLHSI->getOperand(1);
1975       if (&Root == TmpLHSI) {
1976         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1977         return 0;
1978       }
1979       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1980       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1981       BasicBlock::iterator ARI = &Root; ++ARI;
1982       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1983       ARI = Root;
1984
1985       // Now propagate the ExtraOperand down the chain of instructions until we
1986       // get to LHSI.
1987       while (TmpLHSI != LHSI) {
1988         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1989         // Move the instruction to immediately before the chain we are
1990         // constructing to avoid breaking dominance properties.
1991         NextLHSI->moveBefore(ARI);
1992         ARI = NextLHSI;
1993
1994         Value *NextOp = NextLHSI->getOperand(1);
1995         NextLHSI->setOperand(1, ExtraOperand);
1996         TmpLHSI = NextLHSI;
1997         ExtraOperand = NextOp;
1998       }
1999
2000       // Now that the instructions are reassociated, have the functor perform
2001       // the transformation...
2002       return F.apply(Root);
2003     }
2004
2005     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2006   }
2007   return 0;
2008 }
2009
2010 namespace {
2011
2012 // AddRHS - Implements: X + X --> X << 1
2013 struct AddRHS {
2014   Value *RHS;
2015   explicit AddRHS(Value *rhs) : RHS(rhs) {}
2016   bool shouldApply(Value *LHS) const { return LHS == RHS; }
2017   Instruction *apply(BinaryOperator &Add) const {
2018     return BinaryOperator::CreateShl(Add.getOperand(0),
2019                                      ConstantInt::get(Add.getType(), 1));
2020   }
2021 };
2022
2023 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2024 //                 iff C1&C2 == 0
2025 struct AddMaskingAnd {
2026   Constant *C2;
2027   explicit AddMaskingAnd(Constant *c) : C2(c) {}
2028   bool shouldApply(Value *LHS) const {
2029     ConstantInt *C1;
2030     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
2031            ConstantExpr::getAnd(C1, C2)->isNullValue();
2032   }
2033   Instruction *apply(BinaryOperator &Add) const {
2034     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
2035   }
2036 };
2037
2038 }
2039
2040 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
2041                                              InstCombiner *IC) {
2042   if (CastInst *CI = dyn_cast<CastInst>(&I))
2043     return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
2044
2045   // Figure out if the constant is the left or the right argument.
2046   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2047   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
2048
2049   if (Constant *SOC = dyn_cast<Constant>(SO)) {
2050     if (ConstIsRHS)
2051       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2052     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
2053   }
2054
2055   Value *Op0 = SO, *Op1 = ConstOperand;
2056   if (!ConstIsRHS)
2057     std::swap(Op0, Op1);
2058   
2059   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2060     return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
2061                                     SO->getName()+".op");
2062   if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
2063     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2064                                    SO->getName()+".cmp");
2065   if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
2066     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2067                                    SO->getName()+".cmp");
2068   llvm_unreachable("Unknown binary instruction type!");
2069 }
2070
2071 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
2072 // constant as the other operand, try to fold the binary operator into the
2073 // select arguments.  This also works for Cast instructions, which obviously do
2074 // not have a second operand.
2075 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2076                                      InstCombiner *IC) {
2077   // Don't modify shared select instructions
2078   if (!SI->hasOneUse()) return 0;
2079   Value *TV = SI->getOperand(1);
2080   Value *FV = SI->getOperand(2);
2081
2082   if (isa<Constant>(TV) || isa<Constant>(FV)) {
2083     // Bool selects with constant operands can be folded to logical ops.
2084     if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
2085
2086     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2087     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2088
2089     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2090                               SelectFalseVal);
2091   }
2092   return 0;
2093 }
2094
2095
2096 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2097 /// has a PHI node as operand #0, see if we can fold the instruction into the
2098 /// PHI (which is only possible if all operands to the PHI are constants).
2099 ///
2100 /// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2101 /// that would normally be unprofitable because they strongly encourage jump
2102 /// threading.
2103 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2104                                          bool AllowAggressive) {
2105   AllowAggressive = false;
2106   PHINode *PN = cast<PHINode>(I.getOperand(0));
2107   unsigned NumPHIValues = PN->getNumIncomingValues();
2108   if (NumPHIValues == 0 ||
2109       // We normally only transform phis with a single use, unless we're trying
2110       // hard to make jump threading happen.
2111       (!PN->hasOneUse() && !AllowAggressive))
2112     return 0;
2113   
2114   
2115   // Check to see if all of the operands of the PHI are simple constants
2116   // (constantint/constantfp/undef).  If there is one non-constant value,
2117   // remember the BB it is in.  If there is more than one or if *it* is a PHI,
2118   // bail out.  We don't do arbitrary constant expressions here because moving
2119   // their computation can be expensive without a cost model.
2120   BasicBlock *NonConstBB = 0;
2121   for (unsigned i = 0; i != NumPHIValues; ++i)
2122     if (!isa<Constant>(PN->getIncomingValue(i)) ||
2123         isa<ConstantExpr>(PN->getIncomingValue(i))) {
2124       if (NonConstBB) return 0;  // More than one non-const value.
2125       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
2126       NonConstBB = PN->getIncomingBlock(i);
2127       
2128       // If the incoming non-constant value is in I's block, we have an infinite
2129       // loop.
2130       if (NonConstBB == I.getParent())
2131         return 0;
2132     }
2133   
2134   // If there is exactly one non-constant value, we can insert a copy of the
2135   // operation in that block.  However, if this is a critical edge, we would be
2136   // inserting the computation one some other paths (e.g. inside a loop).  Only
2137   // do this if the pred block is unconditionally branching into the phi block.
2138   if (NonConstBB != 0 && !AllowAggressive) {
2139     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2140     if (!BI || !BI->isUnconditional()) return 0;
2141   }
2142
2143   // Okay, we can do the transformation: create the new PHI node.
2144   PHINode *NewPN = PHINode::Create(I.getType(), "");
2145   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2146   InsertNewInstBefore(NewPN, *PN);
2147   NewPN->takeName(PN);
2148
2149   // Next, add all of the operands to the PHI.
2150   if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2151     // We only currently try to fold the condition of a select when it is a phi,
2152     // not the true/false values.
2153     Value *TrueV = SI->getTrueValue();
2154     Value *FalseV = SI->getFalseValue();
2155     BasicBlock *PhiTransBB = PN->getParent();
2156     for (unsigned i = 0; i != NumPHIValues; ++i) {
2157       BasicBlock *ThisBB = PN->getIncomingBlock(i);
2158       Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2159       Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
2160       Value *InV = 0;
2161       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2162         InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
2163       } else {
2164         assert(PN->getIncomingBlock(i) == NonConstBB);
2165         InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2166                                  FalseVInPred,
2167                                  "phitmp", NonConstBB->getTerminator());
2168         Worklist.Add(cast<Instruction>(InV));
2169       }
2170       NewPN->addIncoming(InV, ThisBB);
2171     }
2172   } else if (I.getNumOperands() == 2) {
2173     Constant *C = cast<Constant>(I.getOperand(1));
2174     for (unsigned i = 0; i != NumPHIValues; ++i) {
2175       Value *InV = 0;
2176       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2177         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2178           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2179         else
2180           InV = ConstantExpr::get(I.getOpcode(), InC, C);
2181       } else {
2182         assert(PN->getIncomingBlock(i) == NonConstBB);
2183         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2184           InV = BinaryOperator::Create(BO->getOpcode(),
2185                                        PN->getIncomingValue(i), C, "phitmp",
2186                                        NonConstBB->getTerminator());
2187         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2188           InV = CmpInst::Create(CI->getOpcode(),
2189                                 CI->getPredicate(),
2190                                 PN->getIncomingValue(i), C, "phitmp",
2191                                 NonConstBB->getTerminator());
2192         else
2193           llvm_unreachable("Unknown binop!");
2194         
2195         Worklist.Add(cast<Instruction>(InV));
2196       }
2197       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2198     }
2199   } else { 
2200     CastInst *CI = cast<CastInst>(&I);
2201     const Type *RetTy = CI->getType();
2202     for (unsigned i = 0; i != NumPHIValues; ++i) {
2203       Value *InV;
2204       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2205         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2206       } else {
2207         assert(PN->getIncomingBlock(i) == NonConstBB);
2208         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2209                                I.getType(), "phitmp", 
2210                                NonConstBB->getTerminator());
2211         Worklist.Add(cast<Instruction>(InV));
2212       }
2213       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2214     }
2215   }
2216   return ReplaceInstUsesWith(I, NewPN);
2217 }
2218
2219
2220 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2221 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2222 /// This basically requires proving that the add in the original type would not
2223 /// overflow to change the sign bit or have a carry out.
2224 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2225   // There are different heuristics we can use for this.  Here are some simple
2226   // ones.
2227   
2228   // Add has the property that adding any two 2's complement numbers can only 
2229   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2230   // have at least two sign bits, we know that the addition of the two values
2231   // will sign extend fine.
2232   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2233     return true;
2234   
2235   
2236   // If one of the operands only has one non-zero bit, and if the other operand
2237   // has a known-zero bit in a more significant place than it (not including the
2238   // sign bit) the ripple may go up to and fill the zero, but won't change the
2239   // sign.  For example, (X & ~4) + 1.
2240   
2241   // TODO: Implement.
2242   
2243   return false;
2244 }
2245
2246
2247 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2248   bool Changed = SimplifyCommutative(I);
2249   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2250
2251   if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
2252                                  I.hasNoUnsignedWrap(), TD))
2253     return ReplaceInstUsesWith(I, V);
2254
2255   
2256   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2257     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2258       // X + (signbit) --> X ^ signbit
2259       const APInt& Val = CI->getValue();
2260       uint32_t BitWidth = Val.getBitWidth();
2261       if (Val == APInt::getSignBit(BitWidth))
2262         return BinaryOperator::CreateXor(LHS, RHS);
2263       
2264       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2265       // (X & 254)+1 -> (X&254)|1
2266       if (SimplifyDemandedInstructionBits(I))
2267         return &I;
2268
2269       // zext(bool) + C -> bool ? C + 1 : C
2270       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2271         if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2272           return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2273     }
2274
2275     if (isa<PHINode>(LHS))
2276       if (Instruction *NV = FoldOpIntoPhi(I))
2277         return NV;
2278     
2279     ConstantInt *XorRHS = 0;
2280     Value *XorLHS = 0;
2281     if (isa<ConstantInt>(RHSC) &&
2282         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2283       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2284       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2285       
2286       uint32_t Size = TySizeBits / 2;
2287       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2288       APInt CFF80Val(-C0080Val);
2289       do {
2290         if (TySizeBits > Size) {
2291           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2292           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2293           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2294               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2295             // This is a sign extend if the top bits are known zero.
2296             if (!MaskedValueIsZero(XorLHS, 
2297                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2298               Size = 0;  // Not a sign ext, but can't be any others either.
2299             break;
2300           }
2301         }
2302         Size >>= 1;
2303         C0080Val = APIntOps::lshr(C0080Val, Size);
2304         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2305       } while (Size >= 1);
2306       
2307       // FIXME: This shouldn't be necessary. When the backends can handle types
2308       // with funny bit widths then this switch statement should be removed. It
2309       // is just here to get the size of the "middle" type back up to something
2310       // that the back ends can handle.
2311       const Type *MiddleType = 0;
2312       switch (Size) {
2313         default: break;
2314         case 32: MiddleType = Type::getInt32Ty(*Context); break;
2315         case 16: MiddleType = Type::getInt16Ty(*Context); break;
2316         case  8: MiddleType = Type::getInt8Ty(*Context); break;
2317       }
2318       if (MiddleType) {
2319         Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
2320         return new SExtInst(NewTrunc, I.getType(), I.getName());
2321       }
2322     }
2323   }
2324
2325   if (I.getType() == Type::getInt1Ty(*Context))
2326     return BinaryOperator::CreateXor(LHS, RHS);
2327
2328   // X + X --> X << 1
2329   if (I.getType()->isInteger()) {
2330     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2331       return Result;
2332
2333     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2334       if (RHSI->getOpcode() == Instruction::Sub)
2335         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2336           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2337     }
2338     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2339       if (LHSI->getOpcode() == Instruction::Sub)
2340         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2341           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2342     }
2343   }
2344
2345   // -A + B  -->  B - A
2346   // -A + -B  -->  -(A + B)
2347   if (Value *LHSV = dyn_castNegVal(LHS)) {
2348     if (LHS->getType()->isIntOrIntVector()) {
2349       if (Value *RHSV = dyn_castNegVal(RHS)) {
2350         Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
2351         return BinaryOperator::CreateNeg(NewAdd);
2352       }
2353     }
2354     
2355     return BinaryOperator::CreateSub(RHS, LHSV);
2356   }
2357
2358   // A + -B  -->  A - B
2359   if (!isa<Constant>(RHS))
2360     if (Value *V = dyn_castNegVal(RHS))
2361       return BinaryOperator::CreateSub(LHS, V);
2362
2363
2364   ConstantInt *C2;
2365   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2366     if (X == RHS)   // X*C + X --> X * (C+1)
2367       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2368
2369     // X*C1 + X*C2 --> X * (C1+C2)
2370     ConstantInt *C1;
2371     if (X == dyn_castFoldableMul(RHS, C1))
2372       return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2373   }
2374
2375   // X + X*C --> X * (C+1)
2376   if (dyn_castFoldableMul(RHS, C2) == LHS)
2377     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2378
2379   // X + ~X --> -1   since   ~X = -X-1
2380   if (dyn_castNotVal(LHS) == RHS ||
2381       dyn_castNotVal(RHS) == LHS)
2382     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2383   
2384
2385   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2386   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2387     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2388       return R;
2389   
2390   // A+B --> A|B iff A and B have no bits set in common.
2391   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2392     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2393     APInt LHSKnownOne(IT->getBitWidth(), 0);
2394     APInt LHSKnownZero(IT->getBitWidth(), 0);
2395     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2396     if (LHSKnownZero != 0) {
2397       APInt RHSKnownOne(IT->getBitWidth(), 0);
2398       APInt RHSKnownZero(IT->getBitWidth(), 0);
2399       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2400       
2401       // No bits in common -> bitwise or.
2402       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2403         return BinaryOperator::CreateOr(LHS, RHS);
2404     }
2405   }
2406
2407   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2408   if (I.getType()->isIntOrIntVector()) {
2409     Value *W, *X, *Y, *Z;
2410     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2411         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2412       if (W != Y) {
2413         if (W == Z) {
2414           std::swap(Y, Z);
2415         } else if (Y == X) {
2416           std::swap(W, X);
2417         } else if (X == Z) {
2418           std::swap(Y, Z);
2419           std::swap(W, X);
2420         }
2421       }
2422
2423       if (W == Y) {
2424         Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
2425         return BinaryOperator::CreateMul(W, NewAdd);
2426       }
2427     }
2428   }
2429
2430   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2431     Value *X = 0;
2432     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2433       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2434
2435     // (X & FF00) + xx00  -> (X+xx00) & FF00
2436     if (LHS->hasOneUse() &&
2437         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2438       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2439       if (Anded == CRHS) {
2440         // See if all bits from the first bit set in the Add RHS up are included
2441         // in the mask.  First, get the rightmost bit.
2442         const APInt& AddRHSV = CRHS->getValue();
2443
2444         // Form a mask of all bits from the lowest bit added through the top.
2445         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2446
2447         // See if the and mask includes all of these bits.
2448         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2449
2450         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2451           // Okay, the xform is safe.  Insert the new add pronto.
2452           Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
2453           return BinaryOperator::CreateAnd(NewAdd, C2);
2454         }
2455       }
2456     }
2457
2458     // Try to fold constant add into select arguments.
2459     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2460       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2461         return R;
2462   }
2463
2464   // add (select X 0 (sub n A)) A  -->  select X A n
2465   {
2466     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2467     Value *A = RHS;
2468     if (!SI) {
2469       SI = dyn_cast<SelectInst>(RHS);
2470       A = LHS;
2471     }
2472     if (SI && SI->hasOneUse()) {
2473       Value *TV = SI->getTrueValue();
2474       Value *FV = SI->getFalseValue();
2475       Value *N;
2476
2477       // Can we fold the add into the argument of the select?
2478       // We check both true and false select arguments for a matching subtract.
2479       if (match(FV, m_Zero()) &&
2480           match(TV, m_Sub(m_Value(N), m_Specific(A))))
2481         // Fold the add into the true select value.
2482         return SelectInst::Create(SI->getCondition(), N, A);
2483       if (match(TV, m_Zero()) &&
2484           match(FV, m_Sub(m_Value(N), m_Specific(A))))
2485         // Fold the add into the false select value.
2486         return SelectInst::Create(SI->getCondition(), A, N);
2487     }
2488   }
2489
2490   // Check for (add (sext x), y), see if we can merge this into an
2491   // integer add followed by a sext.
2492   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2493     // (add (sext x), cst) --> (sext (add x, cst'))
2494     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2495       Constant *CI = 
2496         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2497       if (LHSConv->hasOneUse() &&
2498           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2499           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2500         // Insert the new, smaller add.
2501         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0), 
2502                                               CI, "addconv");
2503         return new SExtInst(NewAdd, I.getType());
2504       }
2505     }
2506     
2507     // (add (sext x), (sext y)) --> (sext (add int x, y))
2508     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2509       // Only do this if x/y have the same type, if at last one of them has a
2510       // single use (so we don't increase the number of sexts), and if the
2511       // integer add will not overflow.
2512       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2513           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2514           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2515                                    RHSConv->getOperand(0))) {
2516         // Insert the new integer add.
2517         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0), 
2518                                               RHSConv->getOperand(0), "addconv");
2519         return new SExtInst(NewAdd, I.getType());
2520       }
2521     }
2522   }
2523
2524   return Changed ? &I : 0;
2525 }
2526
2527 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2528   bool Changed = SimplifyCommutative(I);
2529   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2530
2531   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2532     // X + 0 --> X
2533     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2534       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2535                               (I.getType())->getValueAPF()))
2536         return ReplaceInstUsesWith(I, LHS);
2537     }
2538
2539     if (isa<PHINode>(LHS))
2540       if (Instruction *NV = FoldOpIntoPhi(I))
2541         return NV;
2542   }
2543
2544   // -A + B  -->  B - A
2545   // -A + -B  -->  -(A + B)
2546   if (Value *LHSV = dyn_castFNegVal(LHS))
2547     return BinaryOperator::CreateFSub(RHS, LHSV);
2548
2549   // A + -B  -->  A - B
2550   if (!isa<Constant>(RHS))
2551     if (Value *V = dyn_castFNegVal(RHS))
2552       return BinaryOperator::CreateFSub(LHS, V);
2553
2554   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2555   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2556     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2557       return ReplaceInstUsesWith(I, LHS);
2558
2559   // Check for (add double (sitofp x), y), see if we can merge this into an
2560   // integer add followed by a promotion.
2561   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2562     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2563     // ... if the constant fits in the integer value.  This is useful for things
2564     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2565     // requires a constant pool load, and generally allows the add to be better
2566     // instcombined.
2567     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2568       Constant *CI = 
2569       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2570       if (LHSConv->hasOneUse() &&
2571           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2572           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2573         // Insert the new integer add.
2574         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2575                                               CI, "addconv");
2576         return new SIToFPInst(NewAdd, I.getType());
2577       }
2578     }
2579     
2580     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2581     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2582       // Only do this if x/y have the same type, if at last one of them has a
2583       // single use (so we don't increase the number of int->fp conversions),
2584       // and if the integer add will not overflow.
2585       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2586           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2587           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2588                                    RHSConv->getOperand(0))) {
2589         // Insert the new integer add.
2590         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0), 
2591                                               RHSConv->getOperand(0),"addconv");
2592         return new SIToFPInst(NewAdd, I.getType());
2593       }
2594     }
2595   }
2596   
2597   return Changed ? &I : 0;
2598 }
2599
2600
2601 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2602 /// code necessary to compute the offset from the base pointer (without adding
2603 /// in the base pointer).  Return the result as a signed integer of intptr size.
2604 static Value *EmitGEPOffset(User *GEP, InstCombiner &IC) {
2605   TargetData &TD = *IC.getTargetData();
2606   gep_type_iterator GTI = gep_type_begin(GEP);
2607   const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
2608   Value *Result = Constant::getNullValue(IntPtrTy);
2609
2610   // Build a mask for high order bits.
2611   unsigned IntPtrWidth = TD.getPointerSizeInBits();
2612   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2613
2614   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
2615        ++i, ++GTI) {
2616     Value *Op = *i;
2617     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
2618     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
2619       if (OpC->isZero()) continue;
2620       
2621       // Handle a struct index, which adds its field offset to the pointer.
2622       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2623         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
2624         
2625         Result = IC.Builder->CreateAdd(Result,
2626                                        ConstantInt::get(IntPtrTy, Size),
2627                                        GEP->getName()+".offs");
2628         continue;
2629       }
2630       
2631       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2632       Constant *OC =
2633               ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
2634       Scale = ConstantExpr::getMul(OC, Scale);
2635       // Emit an add instruction.
2636       Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
2637       continue;
2638     }
2639     // Convert to correct type.
2640     if (Op->getType() != IntPtrTy)
2641       Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
2642     if (Size != 1) {
2643       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2644       // We'll let instcombine(mul) convert this to a shl if possible.
2645       Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
2646     }
2647
2648     // Emit an add instruction.
2649     Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
2650   }
2651   return Result;
2652 }
2653
2654
2655 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
2656 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
2657 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
2658 /// be complex, and scales are involved.  The above expression would also be
2659 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
2660 /// This later form is less amenable to optimization though, and we are allowed
2661 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
2662 ///
2663 /// If we can't emit an optimized form for this expression, this returns null.
2664 /// 
2665 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
2666                                           InstCombiner &IC) {
2667   TargetData &TD = *IC.getTargetData();
2668   gep_type_iterator GTI = gep_type_begin(GEP);
2669
2670   // Check to see if this gep only has a single variable index.  If so, and if
2671   // any constant indices are a multiple of its scale, then we can compute this
2672   // in terms of the scale of the variable index.  For example, if the GEP
2673   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
2674   // because the expression will cross zero at the same point.
2675   unsigned i, e = GEP->getNumOperands();
2676   int64_t Offset = 0;
2677   for (i = 1; i != e; ++i, ++GTI) {
2678     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2679       // Compute the aggregate offset of constant indices.
2680       if (CI->isZero()) continue;
2681
2682       // Handle a struct index, which adds its field offset to the pointer.
2683       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2684         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2685       } else {
2686         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2687         Offset += Size*CI->getSExtValue();
2688       }
2689     } else {
2690       // Found our variable index.
2691       break;
2692     }
2693   }
2694   
2695   // If there are no variable indices, we must have a constant offset, just
2696   // evaluate it the general way.
2697   if (i == e) return 0;
2698   
2699   Value *VariableIdx = GEP->getOperand(i);
2700   // Determine the scale factor of the variable element.  For example, this is
2701   // 4 if the variable index is into an array of i32.
2702   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
2703   
2704   // Verify that there are no other variable indices.  If so, emit the hard way.
2705   for (++i, ++GTI; i != e; ++i, ++GTI) {
2706     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
2707     if (!CI) return 0;
2708    
2709     // Compute the aggregate offset of constant indices.
2710     if (CI->isZero()) continue;
2711     
2712     // Handle a struct index, which adds its field offset to the pointer.
2713     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2714       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2715     } else {
2716       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2717       Offset += Size*CI->getSExtValue();
2718     }
2719   }
2720   
2721   // Okay, we know we have a single variable index, which must be a
2722   // pointer/array/vector index.  If there is no offset, life is simple, return
2723   // the index.
2724   unsigned IntPtrWidth = TD.getPointerSizeInBits();
2725   if (Offset == 0) {
2726     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
2727     // we don't need to bother extending: the extension won't affect where the
2728     // computation crosses zero.
2729     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
2730       VariableIdx = new TruncInst(VariableIdx, 
2731                                   TD.getIntPtrType(VariableIdx->getContext()),
2732                                   VariableIdx->getName(), &I);
2733     return VariableIdx;
2734   }
2735   
2736   // Otherwise, there is an index.  The computation we will do will be modulo
2737   // the pointer size, so get it.
2738   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2739   
2740   Offset &= PtrSizeMask;
2741   VariableScale &= PtrSizeMask;
2742
2743   // To do this transformation, any constant index must be a multiple of the
2744   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
2745   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
2746   // multiple of the variable scale.
2747   int64_t NewOffs = Offset / (int64_t)VariableScale;
2748   if (Offset != NewOffs*(int64_t)VariableScale)
2749     return 0;
2750
2751   // Okay, we can do this evaluation.  Start by converting the index to intptr.
2752   const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
2753   if (VariableIdx->getType() != IntPtrTy)
2754     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
2755                                               true /*SExt*/, 
2756                                               VariableIdx->getName(), &I);
2757   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
2758   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
2759 }
2760
2761
2762 /// Optimize pointer differences into the same array into a size.  Consider:
2763 ///  &A[10] - &A[0]: we should compile this to "10".  LHS/RHS are the pointer
2764 /// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2765 ///
2766 Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
2767                                                const Type *Ty) {
2768   assert(TD && "Must have target data info for this");
2769   
2770   // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
2771   // this.
2772   bool Swapped;
2773   GetElementPtrInst *GEP;
2774   
2775   if ((GEP = dyn_cast<GetElementPtrInst>(LHS)) &&
2776       GEP->getOperand(0) == RHS)
2777     Swapped = false;
2778   else if ((GEP = dyn_cast<GetElementPtrInst>(RHS)) &&
2779            GEP->getOperand(0) == LHS)
2780     Swapped = true;
2781   else
2782     return 0;
2783   
2784   // TODO: Could also optimize &A[i] - &A[j] -> "i-j".
2785   
2786   // Emit the offset of the GEP and an intptr_t.
2787   Value *Result = EmitGEPOffset(GEP, *this);
2788
2789   // If we have p - gep(p, ...)  then we have to negate the result.
2790   if (Swapped)
2791     Result = Builder->CreateNeg(Result, "diff.neg");
2792
2793   return Builder->CreateIntCast(Result, Ty, true);
2794 }
2795
2796
2797 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2798   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2799
2800   if (Op0 == Op1)                        // sub X, X  -> 0
2801     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2802
2803   // If this is a 'B = x-(-A)', change to B = x+A.  This preserves NSW/NUW.
2804   if (Value *V = dyn_castNegVal(Op1)) {
2805     BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
2806     Res->setHasNoSignedWrap(I.hasNoSignedWrap());
2807     Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
2808     return Res;
2809   }
2810
2811   if (isa<UndefValue>(Op0))
2812     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2813   if (isa<UndefValue>(Op1))
2814     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2815   if (I.getType() == Type::getInt1Ty(*Context))
2816     return BinaryOperator::CreateXor(Op0, Op1);
2817   
2818   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2819     // Replace (-1 - A) with (~A).
2820     if (C->isAllOnesValue())
2821       return BinaryOperator::CreateNot(Op1);
2822
2823     // C - ~X == X + (1+C)
2824     Value *X = 0;
2825     if (match(Op1, m_Not(m_Value(X))))
2826       return BinaryOperator::CreateAdd(X, AddOne(C));
2827
2828     // -(X >>u 31) -> (X >>s 31)
2829     // -(X >>s 31) -> (X >>u 31)
2830     if (C->isZero()) {
2831       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2832         if (SI->getOpcode() == Instruction::LShr) {
2833           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2834             // Check to see if we are shifting out everything but the sign bit.
2835             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2836                 SI->getType()->getPrimitiveSizeInBits()-1) {
2837               // Ok, the transformation is safe.  Insert AShr.
2838               return BinaryOperator::Create(Instruction::AShr, 
2839                                           SI->getOperand(0), CU, SI->getName());
2840             }
2841           }
2842         } else if (SI->getOpcode() == Instruction::AShr) {
2843           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2844             // Check to see if we are shifting out everything but the sign bit.
2845             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2846                 SI->getType()->getPrimitiveSizeInBits()-1) {
2847               // Ok, the transformation is safe.  Insert LShr. 
2848               return BinaryOperator::CreateLShr(
2849                                           SI->getOperand(0), CU, SI->getName());
2850             }
2851           }
2852         }
2853       }
2854     }
2855
2856     // Try to fold constant sub into select arguments.
2857     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2858       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2859         return R;
2860
2861     // C - zext(bool) -> bool ? C - 1 : C
2862     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2863       if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2864         return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2865   }
2866
2867   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2868     if (Op1I->getOpcode() == Instruction::Add) {
2869       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2870         return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2871                                          I.getName());
2872       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2873         return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2874                                          I.getName());
2875       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2876         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2877           // C1-(X+C2) --> (C1-C2)-X
2878           return BinaryOperator::CreateSub(
2879             ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2880       }
2881     }
2882
2883     if (Op1I->hasOneUse()) {
2884       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2885       // is not used by anyone else...
2886       //
2887       if (Op1I->getOpcode() == Instruction::Sub) {
2888         // Swap the two operands of the subexpr...
2889         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2890         Op1I->setOperand(0, IIOp1);
2891         Op1I->setOperand(1, IIOp0);
2892
2893         // Create the new top level add instruction...
2894         return BinaryOperator::CreateAdd(Op0, Op1);
2895       }
2896
2897       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2898       //
2899       if (Op1I->getOpcode() == Instruction::And &&
2900           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2901         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2902
2903         Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
2904         return BinaryOperator::CreateAnd(Op0, NewNot);
2905       }
2906
2907       // 0 - (X sdiv C)  -> (X sdiv -C)
2908       if (Op1I->getOpcode() == Instruction::SDiv)
2909         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2910           if (CSI->isZero())
2911             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2912               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2913                                           ConstantExpr::getNeg(DivRHS));
2914
2915       // X - X*C --> X * (1-C)
2916       ConstantInt *C2 = 0;
2917       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2918         Constant *CP1 = 
2919           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2920                                              C2);
2921         return BinaryOperator::CreateMul(Op0, CP1);
2922       }
2923     }
2924   }
2925
2926   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2927     if (Op0I->getOpcode() == Instruction::Add) {
2928       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2929         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2930       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2931         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2932     } else if (Op0I->getOpcode() == Instruction::Sub) {
2933       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2934         return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2935                                          I.getName());
2936     }
2937   }
2938
2939   ConstantInt *C1;
2940   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2941     if (X == Op1)  // X*C - X --> X * (C-1)
2942       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2943
2944     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2945     if (X == dyn_castFoldableMul(Op1, C2))
2946       return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2947   }
2948   
2949   // Optimize pointer differences into the same array into a size.  Consider:
2950   //  &A[10] - &A[0]: we should compile this to "10".
2951   if (TD) {
2952     if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(Op0))
2953       if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(Op1))
2954         if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2955                                                    RHS->getOperand(0),
2956                                                    I.getType()))
2957           return ReplaceInstUsesWith(I, Res);
2958     
2959     // trunc(p)-trunc(q) -> trunc(p-q)
2960     if (TruncInst *LHST = dyn_cast<TruncInst>(Op0))
2961       if (TruncInst *RHST = dyn_cast<TruncInst>(Op1))
2962         if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(LHST->getOperand(0)))
2963           if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(RHST->getOperand(0)))
2964             if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2965                                                        RHS->getOperand(0),
2966                                                        I.getType()))
2967               return ReplaceInstUsesWith(I, Res);
2968   }
2969   
2970   return 0;
2971 }
2972
2973 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2974   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2975
2976   // If this is a 'B = x-(-A)', change to B = x+A...
2977   if (Value *V = dyn_castFNegVal(Op1))
2978     return BinaryOperator::CreateFAdd(Op0, V);
2979
2980   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2981     if (Op1I->getOpcode() == Instruction::FAdd) {
2982       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2983         return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
2984                                           I.getName());
2985       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2986         return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
2987                                           I.getName());
2988     }
2989   }
2990
2991   return 0;
2992 }
2993
2994 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2995 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2996 /// TrueIfSigned if the result of the comparison is true when the input value is
2997 /// signed.
2998 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2999                            bool &TrueIfSigned) {
3000   switch (pred) {
3001   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
3002     TrueIfSigned = true;
3003     return RHS->isZero();
3004   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
3005     TrueIfSigned = true;
3006     return RHS->isAllOnesValue();
3007   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
3008     TrueIfSigned = false;
3009     return RHS->isAllOnesValue();
3010   case ICmpInst::ICMP_UGT:
3011     // True if LHS u> RHS and RHS == high-bit-mask - 1
3012     TrueIfSigned = true;
3013     return RHS->getValue() ==
3014       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
3015   case ICmpInst::ICMP_UGE: 
3016     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
3017     TrueIfSigned = true;
3018     return RHS->getValue().isSignBit();
3019   default:
3020     return false;
3021   }
3022 }
3023
3024 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
3025   bool Changed = SimplifyCommutative(I);
3026   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3027
3028   if (isa<UndefValue>(Op1))              // undef * X -> 0
3029     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3030
3031   // Simplify mul instructions with a constant RHS.
3032   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3033     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
3034
3035       // ((X << C1)*C2) == (X * (C2 << C1))
3036       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
3037         if (SI->getOpcode() == Instruction::Shl)
3038           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
3039             return BinaryOperator::CreateMul(SI->getOperand(0),
3040                                         ConstantExpr::getShl(CI, ShOp));
3041
3042       if (CI->isZero())
3043         return ReplaceInstUsesWith(I, Op1C);  // X * 0  == 0
3044       if (CI->equalsInt(1))                  // X * 1  == X
3045         return ReplaceInstUsesWith(I, Op0);
3046       if (CI->isAllOnesValue())              // X * -1 == 0 - X
3047         return BinaryOperator::CreateNeg(Op0, I.getName());
3048
3049       const APInt& Val = cast<ConstantInt>(CI)->getValue();
3050       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
3051         return BinaryOperator::CreateShl(Op0,
3052                  ConstantInt::get(Op0->getType(), Val.logBase2()));
3053       }
3054     } else if (isa<VectorType>(Op1C->getType())) {
3055       if (Op1C->isNullValue())
3056         return ReplaceInstUsesWith(I, Op1C);
3057
3058       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
3059         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
3060           return BinaryOperator::CreateNeg(Op0, I.getName());
3061
3062         // As above, vector X*splat(1.0) -> X in all defined cases.
3063         if (Constant *Splat = Op1V->getSplatValue()) {
3064           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
3065             if (CI->equalsInt(1))
3066               return ReplaceInstUsesWith(I, Op0);
3067         }
3068       }
3069     }
3070     
3071     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3072       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
3073           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
3074         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
3075         Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
3076         Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
3077         return BinaryOperator::CreateAdd(Add, C1C2);
3078         
3079       }
3080
3081     // Try to fold constant mul into select arguments.
3082     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3083       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3084         return R;
3085
3086     if (isa<PHINode>(Op0))
3087       if (Instruction *NV = FoldOpIntoPhi(I))
3088         return NV;
3089   }
3090
3091   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
3092     if (Value *Op1v = dyn_castNegVal(Op1))
3093       return BinaryOperator::CreateMul(Op0v, Op1v);
3094
3095   // (X / Y) *  Y = X - (X % Y)
3096   // (X / Y) * -Y = (X % Y) - X
3097   {
3098     Value *Op1C = Op1;
3099     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
3100     if (!BO ||
3101         (BO->getOpcode() != Instruction::UDiv && 
3102          BO->getOpcode() != Instruction::SDiv)) {
3103       Op1C = Op0;
3104       BO = dyn_cast<BinaryOperator>(Op1);
3105     }
3106     Value *Neg = dyn_castNegVal(Op1C);
3107     if (BO && BO->hasOneUse() &&
3108         (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
3109         (BO->getOpcode() == Instruction::UDiv ||
3110          BO->getOpcode() == Instruction::SDiv)) {
3111       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
3112
3113       // If the division is exact, X % Y is zero.
3114       if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
3115         if (SDiv->isExact()) {
3116           if (Op1BO == Op1C)
3117             return ReplaceInstUsesWith(I, Op0BO);
3118           return BinaryOperator::CreateNeg(Op0BO);
3119         }
3120
3121       Value *Rem;
3122       if (BO->getOpcode() == Instruction::UDiv)
3123         Rem = Builder->CreateURem(Op0BO, Op1BO);
3124       else
3125         Rem = Builder->CreateSRem(Op0BO, Op1BO);
3126       Rem->takeName(BO);
3127
3128       if (Op1BO == Op1C)
3129         return BinaryOperator::CreateSub(Op0BO, Rem);
3130       return BinaryOperator::CreateSub(Rem, Op0BO);
3131     }
3132   }
3133
3134   /// i1 mul -> i1 and.
3135   if (I.getType() == Type::getInt1Ty(*Context))
3136     return BinaryOperator::CreateAnd(Op0, Op1);
3137
3138   // X*(1 << Y) --> X << Y
3139   // (1 << Y)*X --> X << Y
3140   {
3141     Value *Y;
3142     if (match(Op0, m_Shl(m_One(), m_Value(Y))))
3143       return BinaryOperator::CreateShl(Op1, Y);
3144     if (match(Op1, m_Shl(m_One(), m_Value(Y))))
3145       return BinaryOperator::CreateShl(Op0, Y);
3146   }
3147   
3148   // If one of the operands of the multiply is a cast from a boolean value, then
3149   // we know the bool is either zero or one, so this is a 'masking' multiply.
3150   //   X * Y (where Y is 0 or 1) -> X & (0-Y)
3151   if (!isa<VectorType>(I.getType())) {
3152     // -2 is "-1 << 1" so it is all bits set except the low one.
3153     APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
3154     
3155     Value *BoolCast = 0, *OtherOp = 0;
3156     if (MaskedValueIsZero(Op0, Negative2))
3157       BoolCast = Op0, OtherOp = Op1;
3158     else if (MaskedValueIsZero(Op1, Negative2))
3159       BoolCast = Op1, OtherOp = Op0;
3160
3161     if (BoolCast) {
3162       Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
3163                                     BoolCast, "tmp");
3164       return BinaryOperator::CreateAnd(V, OtherOp);
3165     }
3166   }
3167
3168   return Changed ? &I : 0;
3169 }
3170
3171 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
3172   bool Changed = SimplifyCommutative(I);
3173   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3174
3175   // Simplify mul instructions with a constant RHS...
3176   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3177     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
3178       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
3179       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3180       if (Op1F->isExactlyValue(1.0))
3181         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
3182     } else if (isa<VectorType>(Op1C->getType())) {
3183       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
3184         // As above, vector X*splat(1.0) -> X in all defined cases.
3185         if (Constant *Splat = Op1V->getSplatValue()) {
3186           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
3187             if (F->isExactlyValue(1.0))
3188               return ReplaceInstUsesWith(I, Op0);
3189         }
3190       }
3191     }
3192
3193     // Try to fold constant mul into select arguments.
3194     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3195       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3196         return R;
3197
3198     if (isa<PHINode>(Op0))
3199       if (Instruction *NV = FoldOpIntoPhi(I))
3200         return NV;
3201   }
3202
3203   if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
3204     if (Value *Op1v = dyn_castFNegVal(Op1))
3205       return BinaryOperator::CreateFMul(Op0v, Op1v);
3206
3207   return Changed ? &I : 0;
3208 }
3209
3210 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
3211 /// instruction.
3212 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
3213   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
3214   
3215   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
3216   int NonNullOperand = -1;
3217   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3218     if (ST->isNullValue())
3219       NonNullOperand = 2;
3220   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
3221   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3222     if (ST->isNullValue())
3223       NonNullOperand = 1;
3224   
3225   if (NonNullOperand == -1)
3226     return false;
3227   
3228   Value *SelectCond = SI->getOperand(0);
3229   
3230   // Change the div/rem to use 'Y' instead of the select.
3231   I.setOperand(1, SI->getOperand(NonNullOperand));
3232   
3233   // Okay, we know we replace the operand of the div/rem with 'Y' with no
3234   // problem.  However, the select, or the condition of the select may have
3235   // multiple uses.  Based on our knowledge that the operand must be non-zero,
3236   // propagate the known value for the select into other uses of it, and
3237   // propagate a known value of the condition into its other users.
3238   
3239   // If the select and condition only have a single use, don't bother with this,
3240   // early exit.
3241   if (SI->use_empty() && SelectCond->hasOneUse())
3242     return true;
3243   
3244   // Scan the current block backward, looking for other uses of SI.
3245   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
3246   
3247   while (BBI != BBFront) {
3248     --BBI;
3249     // If we found a call to a function, we can't assume it will return, so
3250     // information from below it cannot be propagated above it.
3251     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
3252       break;
3253     
3254     // Replace uses of the select or its condition with the known values.
3255     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
3256          I != E; ++I) {
3257       if (*I == SI) {
3258         *I = SI->getOperand(NonNullOperand);
3259         Worklist.Add(BBI);
3260       } else if (*I == SelectCond) {
3261         *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
3262                                    ConstantInt::getFalse(*Context);
3263         Worklist.Add(BBI);
3264       }
3265     }
3266     
3267     // If we past the instruction, quit looking for it.
3268     if (&*BBI == SI)
3269       SI = 0;
3270     if (&*BBI == SelectCond)
3271       SelectCond = 0;
3272     
3273     // If we ran out of things to eliminate, break out of the loop.
3274     if (SelectCond == 0 && SI == 0)
3275       break;
3276     
3277   }
3278   return true;
3279 }
3280
3281
3282 /// This function implements the transforms on div instructions that work
3283 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3284 /// used by the visitors to those instructions.
3285 /// @brief Transforms common to all three div instructions
3286 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
3287   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3288
3289   // undef / X -> 0        for integer.
3290   // undef / X -> undef    for FP (the undef could be a snan).
3291   if (isa<UndefValue>(Op0)) {
3292     if (Op0->getType()->isFPOrFPVector())
3293       return ReplaceInstUsesWith(I, Op0);
3294     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3295   }
3296
3297   // X / undef -> undef
3298   if (isa<UndefValue>(Op1))
3299     return ReplaceInstUsesWith(I, Op1);
3300
3301   return 0;
3302 }
3303
3304 /// This function implements the transforms common to both integer division
3305 /// instructions (udiv and sdiv). It is called by the visitors to those integer
3306 /// division instructions.
3307 /// @brief Common integer divide transforms
3308 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3309   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3310
3311   // (sdiv X, X) --> 1     (udiv X, X) --> 1
3312   if (Op0 == Op1) {
3313     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
3314       Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
3315       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
3316       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
3317     }
3318
3319     Constant *CI = ConstantInt::get(I.getType(), 1);
3320     return ReplaceInstUsesWith(I, CI);
3321   }
3322   
3323   if (Instruction *Common = commonDivTransforms(I))
3324     return Common;
3325   
3326   // Handle cases involving: [su]div X, (select Cond, Y, Z)
3327   // This does not apply for fdiv.
3328   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3329     return &I;
3330
3331   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3332     // div X, 1 == X
3333     if (RHS->equalsInt(1))
3334       return ReplaceInstUsesWith(I, Op0);
3335
3336     // (X / C1) / C2  -> X / (C1*C2)
3337     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3338       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3339         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3340           if (MultiplyOverflows(RHS, LHSRHS,
3341                                 I.getOpcode()==Instruction::SDiv))
3342             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3343           else 
3344             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
3345                                       ConstantExpr::getMul(RHS, LHSRHS));
3346         }
3347
3348     if (!RHS->isZero()) { // avoid X udiv 0
3349       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3350         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3351           return R;
3352       if (isa<PHINode>(Op0))
3353         if (Instruction *NV = FoldOpIntoPhi(I))
3354           return NV;
3355     }
3356   }
3357
3358   // 0 / X == 0, we don't need to preserve faults!
3359   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3360     if (LHS->equalsInt(0))
3361       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3362
3363   // It can't be division by zero, hence it must be division by one.
3364   if (I.getType() == Type::getInt1Ty(*Context))
3365     return ReplaceInstUsesWith(I, Op0);
3366
3367   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3368     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3369       // div X, 1 == X
3370       if (X->isOne())
3371         return ReplaceInstUsesWith(I, Op0);
3372   }
3373
3374   return 0;
3375 }
3376
3377 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3378   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3379
3380   // Handle the integer div common cases
3381   if (Instruction *Common = commonIDivTransforms(I))
3382     return Common;
3383
3384   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3385     // X udiv C^2 -> X >> C
3386     // Check to see if this is an unsigned division with an exact power of 2,
3387     // if so, convert to a right shift.
3388     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3389       return BinaryOperator::CreateLShr(Op0, 
3390             ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3391
3392     // X udiv C, where C >= signbit
3393     if (C->getValue().isNegative()) {
3394       Value *IC = Builder->CreateICmpULT( Op0, C);
3395       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3396                                 ConstantInt::get(I.getType(), 1));
3397     }
3398   }
3399
3400   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3401   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3402     if (RHSI->getOpcode() == Instruction::Shl &&
3403         isa<ConstantInt>(RHSI->getOperand(0))) {
3404       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3405       if (C1.isPowerOf2()) {
3406         Value *N = RHSI->getOperand(1);
3407         const Type *NTy = N->getType();
3408         if (uint32_t C2 = C1.logBase2())
3409           N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
3410         return BinaryOperator::CreateLShr(Op0, N);
3411       }
3412     }
3413   }
3414   
3415   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3416   // where C1&C2 are powers of two.
3417   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3418     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3419       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3420         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3421         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3422           // Compute the shift amounts
3423           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3424           // Construct the "on true" case of the select
3425           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3426           Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
3427   
3428           // Construct the "on false" case of the select
3429           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3430           Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
3431
3432           // construct the select instruction and return it.
3433           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3434         }
3435       }
3436   return 0;
3437 }
3438
3439 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3440   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3441
3442   // Handle the integer div common cases
3443   if (Instruction *Common = commonIDivTransforms(I))
3444     return Common;
3445
3446   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3447     // sdiv X, -1 == -X
3448     if (RHS->isAllOnesValue())
3449       return BinaryOperator::CreateNeg(Op0);
3450
3451     // sdiv X, C  -->  ashr X, log2(C)
3452     if (cast<SDivOperator>(&I)->isExact() &&
3453         RHS->getValue().isNonNegative() &&
3454         RHS->getValue().isPowerOf2()) {
3455       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3456                                             RHS->getValue().exactLogBase2());
3457       return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3458     }
3459
3460     // -X/C  -->  X/-C  provided the negation doesn't overflow.
3461     if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3462       if (isa<Constant>(Sub->getOperand(0)) &&
3463           cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3464           Sub->hasNoSignedWrap())
3465         return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3466                                           ConstantExpr::getNeg(RHS));
3467   }
3468
3469   // If the sign bits of both operands are zero (i.e. we can prove they are
3470   // unsigned inputs), turn this into a udiv.
3471   if (I.getType()->isInteger()) {
3472     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3473     if (MaskedValueIsZero(Op0, Mask)) {
3474       if (MaskedValueIsZero(Op1, Mask)) {
3475         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3476         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3477       }
3478       ConstantInt *ShiftedInt;
3479       if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3480           ShiftedInt->getValue().isPowerOf2()) {
3481         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3482         // Safe because the only negative value (1 << Y) can take on is
3483         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3484         // the sign bit set.
3485         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3486       }
3487     }
3488   }
3489   
3490   return 0;
3491 }
3492
3493 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3494   return commonDivTransforms(I);
3495 }
3496
3497 /// This function implements the transforms on rem instructions that work
3498 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3499 /// is used by the visitors to those instructions.
3500 /// @brief Transforms common to all three rem instructions
3501 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3502   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3503
3504   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3505     if (I.getType()->isFPOrFPVector())
3506       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3507     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3508   }
3509   if (isa<UndefValue>(Op1))
3510     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3511
3512   // Handle cases involving: rem X, (select Cond, Y, Z)
3513   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3514     return &I;
3515
3516   return 0;
3517 }
3518
3519 /// This function implements the transforms common to both integer remainder
3520 /// instructions (urem and srem). It is called by the visitors to those integer
3521 /// remainder instructions.
3522 /// @brief Common integer remainder transforms
3523 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3524   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3525
3526   if (Instruction *common = commonRemTransforms(I))
3527     return common;
3528
3529   // 0 % X == 0 for integer, we don't need to preserve faults!
3530   if (Constant *LHS = dyn_cast<Constant>(Op0))
3531     if (LHS->isNullValue())
3532       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3533
3534   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3535     // X % 0 == undef, we don't need to preserve faults!
3536     if (RHS->equalsInt(0))
3537       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3538     
3539     if (RHS->equalsInt(1))  // X % 1 == 0
3540       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3541
3542     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3543       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3544         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3545           return R;
3546       } else if (isa<PHINode>(Op0I)) {
3547         if (Instruction *NV = FoldOpIntoPhi(I))
3548           return NV;
3549       }
3550
3551       // See if we can fold away this rem instruction.
3552       if (SimplifyDemandedInstructionBits(I))
3553         return &I;
3554     }
3555   }
3556
3557   return 0;
3558 }
3559
3560 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3561   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3562
3563   if (Instruction *common = commonIRemTransforms(I))
3564     return common;
3565   
3566   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3567     // X urem C^2 -> X and C
3568     // Check to see if this is an unsigned remainder with an exact power of 2,
3569     // if so, convert to a bitwise and.
3570     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3571       if (C->getValue().isPowerOf2())
3572         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3573   }
3574
3575   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3576     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3577     if (RHSI->getOpcode() == Instruction::Shl &&
3578         isa<ConstantInt>(RHSI->getOperand(0))) {
3579       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3580         Constant *N1 = Constant::getAllOnesValue(I.getType());
3581         Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
3582         return BinaryOperator::CreateAnd(Op0, Add);
3583       }
3584     }
3585   }
3586
3587   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3588   // where C1&C2 are powers of two.
3589   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3590     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3591       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3592         // STO == 0 and SFO == 0 handled above.
3593         if ((STO->getValue().isPowerOf2()) && 
3594             (SFO->getValue().isPowerOf2())) {
3595           Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3596                                               SI->getName()+".t");
3597           Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3598                                                SI->getName()+".f");
3599           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3600         }
3601       }
3602   }
3603   
3604   return 0;
3605 }
3606
3607 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3608   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3609
3610   // Handle the integer rem common cases
3611   if (Instruction *Common = commonIRemTransforms(I))
3612     return Common;
3613   
3614   if (Value *RHSNeg = dyn_castNegVal(Op1))
3615     if (!isa<Constant>(RHSNeg) ||
3616         (isa<ConstantInt>(RHSNeg) &&
3617          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3618       // X % -Y -> X % Y
3619       Worklist.AddValue(I.getOperand(1));
3620       I.setOperand(1, RHSNeg);
3621       return &I;
3622     }
3623
3624   // If the sign bits of both operands are zero (i.e. we can prove they are
3625   // unsigned inputs), turn this into a urem.
3626   if (I.getType()->isInteger()) {
3627     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3628     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3629       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3630       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3631     }
3632   }
3633
3634   // If it's a constant vector, flip any negative values positive.
3635   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3636     unsigned VWidth = RHSV->getNumOperands();
3637
3638     bool hasNegative = false;
3639     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3640       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3641         if (RHS->getValue().isNegative())
3642           hasNegative = true;
3643
3644     if (hasNegative) {
3645       std::vector<Constant *> Elts(VWidth);
3646       for (unsigned i = 0; i != VWidth; ++i) {
3647         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3648           if (RHS->getValue().isNegative())
3649             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3650           else
3651             Elts[i] = RHS;
3652         }
3653       }
3654
3655       Constant *NewRHSV = ConstantVector::get(Elts);
3656       if (NewRHSV != RHSV) {
3657         Worklist.AddValue(I.getOperand(1));
3658         I.setOperand(1, NewRHSV);
3659         return &I;
3660       }
3661     }
3662   }
3663
3664   return 0;
3665 }
3666
3667 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3668   return commonRemTransforms(I);
3669 }
3670
3671 // isOneBitSet - Return true if there is exactly one bit set in the specified
3672 // constant.
3673 static bool isOneBitSet(const ConstantInt *CI) {
3674   return CI->getValue().isPowerOf2();
3675 }
3676
3677 // isHighOnes - Return true if the constant is of the form 1+0+.
3678 // This is the same as lowones(~X).
3679 static bool isHighOnes(const ConstantInt *CI) {
3680   return (~CI->getValue() + 1).isPowerOf2();
3681 }
3682
3683 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3684 /// are carefully arranged to allow folding of expressions such as:
3685 ///
3686 ///      (A < B) | (A > B) --> (A != B)
3687 ///
3688 /// Note that this is only valid if the first and second predicates have the
3689 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3690 ///
3691 /// Three bits are used to represent the condition, as follows:
3692 ///   0  A > B
3693 ///   1  A == B
3694 ///   2  A < B
3695 ///
3696 /// <=>  Value  Definition
3697 /// 000     0   Always false
3698 /// 001     1   A >  B
3699 /// 010     2   A == B
3700 /// 011     3   A >= B
3701 /// 100     4   A <  B
3702 /// 101     5   A != B
3703 /// 110     6   A <= B
3704 /// 111     7   Always true
3705 ///  
3706 static unsigned getICmpCode(const ICmpInst *ICI) {
3707   switch (ICI->getPredicate()) {
3708     // False -> 0
3709   case ICmpInst::ICMP_UGT: return 1;  // 001
3710   case ICmpInst::ICMP_SGT: return 1;  // 001
3711   case ICmpInst::ICMP_EQ:  return 2;  // 010
3712   case ICmpInst::ICMP_UGE: return 3;  // 011
3713   case ICmpInst::ICMP_SGE: return 3;  // 011
3714   case ICmpInst::ICMP_ULT: return 4;  // 100
3715   case ICmpInst::ICMP_SLT: return 4;  // 100
3716   case ICmpInst::ICMP_NE:  return 5;  // 101
3717   case ICmpInst::ICMP_ULE: return 6;  // 110
3718   case ICmpInst::ICMP_SLE: return 6;  // 110
3719     // True -> 7
3720   default:
3721     llvm_unreachable("Invalid ICmp predicate!");
3722     return 0;
3723   }
3724 }
3725
3726 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3727 /// predicate into a three bit mask. It also returns whether it is an ordered
3728 /// predicate by reference.
3729 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3730   isOrdered = false;
3731   switch (CC) {
3732   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3733   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3734   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3735   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3736   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3737   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3738   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3739   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3740   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3741   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3742   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3743   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3744   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3745   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3746     // True -> 7
3747   default:
3748     // Not expecting FCMP_FALSE and FCMP_TRUE;
3749     llvm_unreachable("Unexpected FCmp predicate!");
3750     return 0;
3751   }
3752 }
3753
3754 /// getICmpValue - This is the complement of getICmpCode, which turns an
3755 /// opcode and two operands into either a constant true or false, or a brand 
3756 /// new ICmp instruction. The sign is passed in to determine which kind
3757 /// of predicate to use in the new icmp instruction.
3758 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3759                            LLVMContext *Context) {
3760   switch (code) {
3761   default: llvm_unreachable("Illegal ICmp code!");
3762   case  0: return ConstantInt::getFalse(*Context);
3763   case  1: 
3764     if (sign)
3765       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3766     else
3767       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3768   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3769   case  3: 
3770     if (sign)
3771       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3772     else
3773       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3774   case  4: 
3775     if (sign)
3776       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3777     else
3778       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3779   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3780   case  6: 
3781     if (sign)
3782       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3783     else
3784       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3785   case  7: return ConstantInt::getTrue(*Context);
3786   }
3787 }
3788
3789 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3790 /// opcode and two operands into either a FCmp instruction. isordered is passed
3791 /// in to determine which kind of predicate to use in the new fcmp instruction.
3792 static Value *getFCmpValue(bool isordered, unsigned code,
3793                            Value *LHS, Value *RHS, LLVMContext *Context) {
3794   switch (code) {
3795   default: llvm_unreachable("Illegal FCmp code!");
3796   case  0:
3797     if (isordered)
3798       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3799     else
3800       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3801   case  1: 
3802     if (isordered)
3803       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3804     else
3805       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3806   case  2: 
3807     if (isordered)
3808       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3809     else
3810       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3811   case  3: 
3812     if (isordered)
3813       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3814     else
3815       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3816   case  4: 
3817     if (isordered)
3818       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3819     else
3820       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3821   case  5: 
3822     if (isordered)
3823       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3824     else
3825       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3826   case  6: 
3827     if (isordered)
3828       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3829     else
3830       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3831   case  7: return ConstantInt::getTrue(*Context);
3832   }
3833 }
3834
3835 /// PredicatesFoldable - Return true if both predicates match sign or if at
3836 /// least one of them is an equality comparison (which is signless).
3837 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3838   return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3839          (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3840          (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
3841 }
3842
3843 namespace { 
3844 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3845 struct FoldICmpLogical {
3846   InstCombiner &IC;
3847   Value *LHS, *RHS;
3848   ICmpInst::Predicate pred;
3849   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3850     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3851       pred(ICI->getPredicate()) {}
3852   bool shouldApply(Value *V) const {
3853     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3854       if (PredicatesFoldable(pred, ICI->getPredicate()))
3855         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3856                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3857     return false;
3858   }
3859   Instruction *apply(Instruction &Log) const {
3860     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3861     if (ICI->getOperand(0) != LHS) {
3862       assert(ICI->getOperand(1) == LHS);
3863       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3864     }
3865
3866     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3867     unsigned LHSCode = getICmpCode(ICI);
3868     unsigned RHSCode = getICmpCode(RHSICI);
3869     unsigned Code;
3870     switch (Log.getOpcode()) {
3871     case Instruction::And: Code = LHSCode & RHSCode; break;
3872     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3873     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3874     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3875     }
3876
3877     bool isSigned = RHSICI->isSigned() || ICI->isSigned();
3878     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3879     if (Instruction *I = dyn_cast<Instruction>(RV))
3880       return I;
3881     // Otherwise, it's a constant boolean value...
3882     return IC.ReplaceInstUsesWith(Log, RV);
3883   }
3884 };
3885 } // end anonymous namespace
3886
3887 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3888 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3889 // guaranteed to be a binary operator.
3890 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3891                                     ConstantInt *OpRHS,
3892                                     ConstantInt *AndRHS,
3893                                     BinaryOperator &TheAnd) {
3894   Value *X = Op->getOperand(0);
3895   Constant *Together = 0;
3896   if (!Op->isShift())
3897     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3898
3899   switch (Op->getOpcode()) {
3900   case Instruction::Xor:
3901     if (Op->hasOneUse()) {
3902       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3903       Value *And = Builder->CreateAnd(X, AndRHS);
3904       And->takeName(Op);
3905       return BinaryOperator::CreateXor(And, Together);
3906     }
3907     break;
3908   case Instruction::Or:
3909     if (Together == AndRHS) // (X | C) & C --> C
3910       return ReplaceInstUsesWith(TheAnd, AndRHS);
3911
3912     if (Op->hasOneUse() && Together != OpRHS) {
3913       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3914       Value *Or = Builder->CreateOr(X, Together);
3915       Or->takeName(Op);
3916       return BinaryOperator::CreateAnd(Or, AndRHS);
3917     }
3918     break;
3919   case Instruction::Add:
3920     if (Op->hasOneUse()) {
3921       // Adding a one to a single bit bit-field should be turned into an XOR
3922       // of the bit.  First thing to check is to see if this AND is with a
3923       // single bit constant.
3924       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3925
3926       // If there is only one bit set...
3927       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3928         // Ok, at this point, we know that we are masking the result of the
3929         // ADD down to exactly one bit.  If the constant we are adding has
3930         // no bits set below this bit, then we can eliminate the ADD.
3931         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3932
3933         // Check to see if any bits below the one bit set in AndRHSV are set.
3934         if ((AddRHS & (AndRHSV-1)) == 0) {
3935           // If not, the only thing that can effect the output of the AND is
3936           // the bit specified by AndRHSV.  If that bit is set, the effect of
3937           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3938           // no effect.
3939           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3940             TheAnd.setOperand(0, X);
3941             return &TheAnd;
3942           } else {
3943             // Pull the XOR out of the AND.
3944             Value *NewAnd = Builder->CreateAnd(X, AndRHS);
3945             NewAnd->takeName(Op);
3946             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3947           }
3948         }
3949       }
3950     }
3951     break;
3952
3953   case Instruction::Shl: {
3954     // We know that the AND will not produce any of the bits shifted in, so if
3955     // the anded constant includes them, clear them now!
3956     //
3957     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3958     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3959     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3960     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3961
3962     if (CI->getValue() == ShlMask) { 
3963     // Masking out bits that the shift already masks
3964       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3965     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3966       TheAnd.setOperand(1, CI);
3967       return &TheAnd;
3968     }
3969     break;
3970   }
3971   case Instruction::LShr:
3972   {
3973     // We know that the AND will not produce any of the bits shifted in, so if
3974     // the anded constant includes them, clear them now!  This only applies to
3975     // unsigned shifts, because a signed shr may bring in set bits!
3976     //
3977     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3978     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3979     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3980     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3981
3982     if (CI->getValue() == ShrMask) {   
3983     // Masking out bits that the shift already masks.
3984       return ReplaceInstUsesWith(TheAnd, Op);
3985     } else if (CI != AndRHS) {
3986       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3987       return &TheAnd;
3988     }
3989     break;
3990   }
3991   case Instruction::AShr:
3992     // Signed shr.
3993     // See if this is shifting in some sign extension, then masking it out
3994     // with an and.
3995     if (Op->hasOneUse()) {
3996       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3997       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3998       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3999       Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
4000       if (C == AndRHS) {          // Masking out bits shifted in.
4001         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
4002         // Make the argument unsigned.
4003         Value *ShVal = Op->getOperand(0);
4004         ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
4005         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
4006       }
4007     }
4008     break;
4009   }
4010   return 0;
4011 }
4012
4013
4014 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
4015 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
4016 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
4017 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
4018 /// insert new instructions.
4019 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
4020                                            bool isSigned, bool Inside, 
4021                                            Instruction &IB) {
4022   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
4023             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
4024          "Lo is not <= Hi in range emission code!");
4025     
4026   if (Inside) {
4027     if (Lo == Hi)  // Trivially false.
4028       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
4029
4030     // V >= Min && V < Hi --> V < Hi
4031     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
4032       ICmpInst::Predicate pred = (isSigned ? 
4033         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
4034       return new ICmpInst(pred, V, Hi);
4035     }
4036
4037     // Emit V-Lo <u Hi-Lo
4038     Constant *NegLo = ConstantExpr::getNeg(Lo);
4039     Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
4040     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
4041     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
4042   }
4043
4044   if (Lo == Hi)  // Trivially true.
4045     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
4046
4047   // V < Min || V >= Hi -> V > Hi-1
4048   Hi = SubOne(cast<ConstantInt>(Hi));
4049   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
4050     ICmpInst::Predicate pred = (isSigned ? 
4051         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
4052     return new ICmpInst(pred, V, Hi);
4053   }
4054
4055   // Emit V-Lo >u Hi-1-Lo
4056   // Note that Hi has already had one subtracted from it, above.
4057   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
4058   Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
4059   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
4060   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
4061 }
4062
4063 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
4064 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
4065 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
4066 // not, since all 1s are not contiguous.
4067 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
4068   const APInt& V = Val->getValue();
4069   uint32_t BitWidth = Val->getType()->getBitWidth();
4070   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
4071
4072   // look for the first zero bit after the run of ones
4073   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
4074   // look for the first non-zero bit
4075   ME = V.getActiveBits(); 
4076   return true;
4077 }
4078
4079 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
4080 /// where isSub determines whether the operator is a sub.  If we can fold one of
4081 /// the following xforms:
4082 /// 
4083 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
4084 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4085 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4086 ///
4087 /// return (A +/- B).
4088 ///
4089 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
4090                                         ConstantInt *Mask, bool isSub,
4091                                         Instruction &I) {
4092   Instruction *LHSI = dyn_cast<Instruction>(LHS);
4093   if (!LHSI || LHSI->getNumOperands() != 2 ||
4094       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
4095
4096   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
4097
4098   switch (LHSI->getOpcode()) {
4099   default: return 0;
4100   case Instruction::And:
4101     if (ConstantExpr::getAnd(N, Mask) == Mask) {
4102       // If the AndRHS is a power of two minus one (0+1+), this is simple.
4103       if ((Mask->getValue().countLeadingZeros() + 
4104            Mask->getValue().countPopulation()) == 
4105           Mask->getValue().getBitWidth())
4106         break;
4107
4108       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4109       // part, we don't need any explicit masks to take them out of A.  If that
4110       // is all N is, ignore it.
4111       uint32_t MB = 0, ME = 0;
4112       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
4113         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
4114         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
4115         if (MaskedValueIsZero(RHS, Mask))
4116           break;
4117       }
4118     }
4119     return 0;
4120   case Instruction::Or:
4121   case Instruction::Xor:
4122     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
4123     if ((Mask->getValue().countLeadingZeros() + 
4124          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
4125         && ConstantExpr::getAnd(N, Mask)->isNullValue())
4126       break;
4127     return 0;
4128   }
4129   
4130   if (isSub)
4131     return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
4132   return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
4133 }
4134
4135 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
4136 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
4137                                           ICmpInst *LHS, ICmpInst *RHS) {
4138   // (icmp eq A, null) & (icmp eq B, null) -->
4139   //     (icmp eq (ptrtoint(A)|ptrtoint(B)), 0)
4140   if (TD &&
4141       LHS->getPredicate() == ICmpInst::ICMP_EQ &&
4142       RHS->getPredicate() == ICmpInst::ICMP_EQ &&
4143       isa<ConstantPointerNull>(LHS->getOperand(1)) &&
4144       isa<ConstantPointerNull>(RHS->getOperand(1))) {
4145     const Type *IntPtrTy = TD->getIntPtrType(I.getContext());
4146     Value *A = Builder->CreatePtrToInt(LHS->getOperand(0), IntPtrTy);
4147     Value *B = Builder->CreatePtrToInt(RHS->getOperand(0), IntPtrTy);
4148     Value *NewOr = Builder->CreateOr(A, B);
4149     return new ICmpInst(ICmpInst::ICMP_EQ, NewOr,
4150                         Constant::getNullValue(IntPtrTy));
4151   }
4152   
4153   Value *Val, *Val2;
4154   ConstantInt *LHSCst, *RHSCst;
4155   ICmpInst::Predicate LHSCC, RHSCC;
4156   
4157   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
4158   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4159                          m_ConstantInt(LHSCst))) ||
4160       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4161                          m_ConstantInt(RHSCst))))
4162     return 0;
4163   
4164   if (LHSCst == RHSCst && LHSCC == RHSCC) {
4165     // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
4166     // where C is a power of 2
4167     if (LHSCC == ICmpInst::ICMP_ULT &&
4168         LHSCst->getValue().isPowerOf2()) {
4169       Value *NewOr = Builder->CreateOr(Val, Val2);
4170       return new ICmpInst(LHSCC, NewOr, LHSCst);
4171     }
4172     
4173     // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
4174     if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
4175       Value *NewOr = Builder->CreateOr(Val, Val2);
4176       return new ICmpInst(LHSCC, NewOr, LHSCst);
4177     }
4178   }
4179   
4180   // From here on, we only handle:
4181   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
4182   if (Val != Val2) return 0;
4183   
4184   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4185   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4186       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4187       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4188       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4189     return 0;
4190   
4191   // We can't fold (ugt x, C) & (sgt x, C2).
4192   if (!PredicatesFoldable(LHSCC, RHSCC))
4193     return 0;
4194     
4195   // Ensure that the larger constant is on the RHS.
4196   bool ShouldSwap;
4197   if (CmpInst::isSigned(LHSCC) ||
4198       (ICmpInst::isEquality(LHSCC) && 
4199        CmpInst::isSigned(RHSCC)))
4200     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4201   else
4202     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4203     
4204   if (ShouldSwap) {
4205     std::swap(LHS, RHS);
4206     std::swap(LHSCst, RHSCst);
4207     std::swap(LHSCC, RHSCC);
4208   }
4209
4210   // At this point, we know we have have two icmp instructions
4211   // comparing a value against two constants and and'ing the result
4212   // together.  Because of the above check, we know that we only have
4213   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
4214   // (from the FoldICmpLogical check above), that the two constants 
4215   // are not equal and that the larger constant is on the RHS
4216   assert(LHSCst != RHSCst && "Compares not folded above?");
4217
4218   switch (LHSCC) {
4219   default: llvm_unreachable("Unknown integer condition code!");
4220   case ICmpInst::ICMP_EQ:
4221     switch (RHSCC) {
4222     default: llvm_unreachable("Unknown integer condition code!");
4223     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
4224     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
4225     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
4226       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4227     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
4228     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
4229     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
4230       return ReplaceInstUsesWith(I, LHS);
4231     }
4232   case ICmpInst::ICMP_NE:
4233     switch (RHSCC) {
4234     default: llvm_unreachable("Unknown integer condition code!");
4235     case ICmpInst::ICMP_ULT:
4236       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4237         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
4238       break;                        // (X != 13 & X u< 15) -> no change
4239     case ICmpInst::ICMP_SLT:
4240       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4241         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
4242       break;                        // (X != 13 & X s< 15) -> no change
4243     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
4244     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
4245     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
4246       return ReplaceInstUsesWith(I, RHS);
4247     case ICmpInst::ICMP_NE:
4248       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
4249         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4250         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4251         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4252                             ConstantInt::get(Add->getType(), 1));
4253       }
4254       break;                        // (X != 13 & X != 15) -> no change
4255     }
4256     break;
4257   case ICmpInst::ICMP_ULT:
4258     switch (RHSCC) {
4259     default: llvm_unreachable("Unknown integer condition code!");
4260     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
4261     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
4262       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4263     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
4264       break;
4265     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
4266     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
4267       return ReplaceInstUsesWith(I, LHS);
4268     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
4269       break;
4270     }
4271     break;
4272   case ICmpInst::ICMP_SLT:
4273     switch (RHSCC) {
4274     default: llvm_unreachable("Unknown integer condition code!");
4275     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
4276     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
4277       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4278     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
4279       break;
4280     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
4281     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
4282       return ReplaceInstUsesWith(I, LHS);
4283     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
4284       break;
4285     }
4286     break;
4287   case ICmpInst::ICMP_UGT:
4288     switch (RHSCC) {
4289     default: llvm_unreachable("Unknown integer condition code!");
4290     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
4291     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
4292       return ReplaceInstUsesWith(I, RHS);
4293     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
4294       break;
4295     case ICmpInst::ICMP_NE:
4296       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4297         return new ICmpInst(LHSCC, Val, RHSCst);
4298       break;                        // (X u> 13 & X != 15) -> no change
4299     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
4300       return InsertRangeTest(Val, AddOne(LHSCst),
4301                              RHSCst, false, true, I);
4302     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
4303       break;
4304     }
4305     break;
4306   case ICmpInst::ICMP_SGT:
4307     switch (RHSCC) {
4308     default: llvm_unreachable("Unknown integer condition code!");
4309     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
4310     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
4311       return ReplaceInstUsesWith(I, RHS);
4312     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
4313       break;
4314     case ICmpInst::ICMP_NE:
4315       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4316         return new ICmpInst(LHSCC, Val, RHSCst);
4317       break;                        // (X s> 13 & X != 15) -> no change
4318     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
4319       return InsertRangeTest(Val, AddOne(LHSCst),
4320                              RHSCst, true, true, I);
4321     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
4322       break;
4323     }
4324     break;
4325   }
4326  
4327   return 0;
4328 }
4329
4330 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4331                                           FCmpInst *RHS) {
4332   
4333   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4334       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4335     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4336     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4337       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4338         // If either of the constants are nans, then the whole thing returns
4339         // false.
4340         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4341           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4342         return new FCmpInst(FCmpInst::FCMP_ORD,
4343                             LHS->getOperand(0), RHS->getOperand(0));
4344       }
4345     
4346     // Handle vector zeros.  This occurs because the canonical form of
4347     // "fcmp ord x,x" is "fcmp ord x, 0".
4348     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4349         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4350       return new FCmpInst(FCmpInst::FCMP_ORD,
4351                           LHS->getOperand(0), RHS->getOperand(0));
4352     return 0;
4353   }
4354   
4355   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4356   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4357   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4358   
4359   
4360   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4361     // Swap RHS operands to match LHS.
4362     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4363     std::swap(Op1LHS, Op1RHS);
4364   }
4365   
4366   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4367     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4368     if (Op0CC == Op1CC)
4369       return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4370     
4371     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
4372       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4373     if (Op0CC == FCmpInst::FCMP_TRUE)
4374       return ReplaceInstUsesWith(I, RHS);
4375     if (Op1CC == FCmpInst::FCMP_TRUE)
4376       return ReplaceInstUsesWith(I, LHS);
4377     
4378     bool Op0Ordered;
4379     bool Op1Ordered;
4380     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4381     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4382     if (Op1Pred == 0) {
4383       std::swap(LHS, RHS);
4384       std::swap(Op0Pred, Op1Pred);
4385       std::swap(Op0Ordered, Op1Ordered);
4386     }
4387     if (Op0Pred == 0) {
4388       // uno && ueq -> uno && (uno || eq) -> ueq
4389       // ord && olt -> ord && (ord && lt) -> olt
4390       if (Op0Ordered == Op1Ordered)
4391         return ReplaceInstUsesWith(I, RHS);
4392       
4393       // uno && oeq -> uno && (ord && eq) -> false
4394       // uno && ord -> false
4395       if (!Op0Ordered)
4396         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4397       // ord && ueq -> ord && (uno || eq) -> oeq
4398       return cast<Instruction>(getFCmpValue(true, Op1Pred,
4399                                             Op0LHS, Op0RHS, Context));
4400     }
4401   }
4402
4403   return 0;
4404 }
4405
4406
4407 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4408   bool Changed = SimplifyCommutative(I);
4409   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4410
4411   if (Value *V = SimplifyAndInst(Op0, Op1, TD))
4412     return ReplaceInstUsesWith(I, V);
4413
4414   // See if we can simplify any instructions used by the instruction whose sole 
4415   // purpose is to compute bits we don't care about.
4416   if (SimplifyDemandedInstructionBits(I))
4417     return &I;
4418   
4419
4420   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4421     const APInt &AndRHSMask = AndRHS->getValue();
4422     APInt NotAndRHS(~AndRHSMask);
4423
4424     // Optimize a variety of ((val OP C1) & C2) combinations...
4425     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4426       Value *Op0LHS = Op0I->getOperand(0);
4427       Value *Op0RHS = Op0I->getOperand(1);
4428       switch (Op0I->getOpcode()) {
4429       default: break;
4430       case Instruction::Xor:
4431       case Instruction::Or:
4432         // If the mask is only needed on one incoming arm, push it up.
4433         if (!Op0I->hasOneUse()) break;
4434           
4435         if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4436           // Not masking anything out for the LHS, move to RHS.
4437           Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4438                                              Op0RHS->getName()+".masked");
4439           return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4440         }
4441         if (!isa<Constant>(Op0RHS) &&
4442             MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4443           // Not masking anything out for the RHS, move to LHS.
4444           Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4445                                              Op0LHS->getName()+".masked");
4446           return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
4447         }
4448
4449         break;
4450       case Instruction::Add:
4451         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4452         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4453         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4454         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4455           return BinaryOperator::CreateAnd(V, AndRHS);
4456         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4457           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4458         break;
4459
4460       case Instruction::Sub:
4461         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4462         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4463         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4464         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4465           return BinaryOperator::CreateAnd(V, AndRHS);
4466
4467         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4468         // has 1's for all bits that the subtraction with A might affect.
4469         if (Op0I->hasOneUse()) {
4470           uint32_t BitWidth = AndRHSMask.getBitWidth();
4471           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4472           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4473
4474           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4475           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4476               MaskedValueIsZero(Op0LHS, Mask)) {
4477             Value *NewNeg = Builder->CreateNeg(Op0RHS);
4478             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4479           }
4480         }
4481         break;
4482
4483       case Instruction::Shl:
4484       case Instruction::LShr:
4485         // (1 << x) & 1 --> zext(x == 0)
4486         // (1 >> x) & 1 --> zext(x == 0)
4487         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4488           Value *NewICmp =
4489             Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
4490           return new ZExtInst(NewICmp, I.getType());
4491         }
4492         break;
4493       }
4494
4495       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4496         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4497           return Res;
4498     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4499       // If this is an integer truncation or change from signed-to-unsigned, and
4500       // if the source is an and/or with immediate, transform it.  This
4501       // frequently occurs for bitfield accesses.
4502       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4503         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4504             CastOp->getNumOperands() == 2)
4505           if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
4506             if (CastOp->getOpcode() == Instruction::And) {
4507               // Change: and (cast (and X, C1) to T), C2
4508               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4509               // This will fold the two constants together, which may allow 
4510               // other simplifications.
4511               Value *NewCast = Builder->CreateTruncOrBitCast(
4512                 CastOp->getOperand(0), I.getType(), 
4513                 CastOp->getName()+".shrunk");
4514               // trunc_or_bitcast(C1)&C2
4515               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4516               C3 = ConstantExpr::getAnd(C3, AndRHS);
4517               return BinaryOperator::CreateAnd(NewCast, C3);
4518             } else if (CastOp->getOpcode() == Instruction::Or) {
4519               // Change: and (cast (or X, C1) to T), C2
4520               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4521               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4522               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4523                 // trunc(C1)&C2
4524                 return ReplaceInstUsesWith(I, AndRHS);
4525             }
4526           }
4527       }
4528     }
4529
4530     // Try to fold constant and into select arguments.
4531     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4532       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4533         return R;
4534     if (isa<PHINode>(Op0))
4535       if (Instruction *NV = FoldOpIntoPhi(I))
4536         return NV;
4537   }
4538
4539
4540   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4541   if (Value *Op0NotVal = dyn_castNotVal(Op0))
4542     if (Value *Op1NotVal = dyn_castNotVal(Op1))
4543       if (Op0->hasOneUse() && Op1->hasOneUse()) {
4544         Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4545                                       I.getName()+".demorgan");
4546         return BinaryOperator::CreateNot(Or);
4547       }
4548
4549   {
4550     Value *A = 0, *B = 0, *C = 0, *D = 0;
4551     // (A|B) & ~(A&B) -> A^B
4552     if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
4553         match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4554         ((A == C && B == D) || (A == D && B == C)))
4555       return BinaryOperator::CreateXor(A, B);
4556     
4557     // ~(A&B) & (A|B) -> A^B
4558     if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
4559         match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4560         ((A == C && B == D) || (A == D && B == C)))
4561       return BinaryOperator::CreateXor(A, B);
4562     
4563     if (Op0->hasOneUse() &&
4564         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4565       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4566         I.swapOperands();     // Simplify below
4567         std::swap(Op0, Op1);
4568       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4569         cast<BinaryOperator>(Op0)->swapOperands();
4570         I.swapOperands();     // Simplify below
4571         std::swap(Op0, Op1);
4572       }
4573     }
4574
4575     if (Op1->hasOneUse() &&
4576         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4577       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4578         cast<BinaryOperator>(Op1)->swapOperands();
4579         std::swap(A, B);
4580       }
4581       if (A == Op0)                                // A&(A^B) -> A & ~B
4582         return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
4583     }
4584
4585     // (A&((~A)|B)) -> A&B
4586     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4587         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4588       return BinaryOperator::CreateAnd(A, Op1);
4589     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4590         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4591       return BinaryOperator::CreateAnd(A, Op0);
4592   }
4593   
4594   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4595     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4596     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4597       return R;
4598
4599     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4600       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4601         return Res;
4602   }
4603
4604   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4605   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4606     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4607       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4608         const Type *SrcTy = Op0C->getOperand(0)->getType();
4609         if (SrcTy == Op1C->getOperand(0)->getType() &&
4610             SrcTy->isIntOrIntVector() &&
4611             // Only do this if the casts both really cause code to be generated.
4612             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4613                               I.getType(), TD) &&
4614             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4615                               I.getType(), TD)) {
4616           Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4617                                             Op1C->getOperand(0), I.getName());
4618           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4619         }
4620       }
4621     
4622   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4623   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4624     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4625       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4626           SI0->getOperand(1) == SI1->getOperand(1) &&
4627           (SI0->hasOneUse() || SI1->hasOneUse())) {
4628         Value *NewOp =
4629           Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4630                              SI0->getName());
4631         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4632                                       SI1->getOperand(1));
4633       }
4634   }
4635
4636   // If and'ing two fcmp, try combine them into one.
4637   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4638     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4639       if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4640         return Res;
4641   }
4642
4643   return Changed ? &I : 0;
4644 }
4645
4646 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4647 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4648 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4649 /// the expression came from the corresponding "byte swapped" byte in some other
4650 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4651 /// we know that the expression deposits the low byte of %X into the high byte
4652 /// of the bswap result and that all other bytes are zero.  This expression is
4653 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4654 /// match.
4655 ///
4656 /// This function returns true if the match was unsuccessful and false if so.
4657 /// On entry to the function the "OverallLeftShift" is a signed integer value
4658 /// indicating the number of bytes that the subexpression is later shifted.  For
4659 /// example, if the expression is later right shifted by 16 bits, the
4660 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4661 /// byte of ByteValues is actually being set.
4662 ///
4663 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4664 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4665 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4666 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4667 /// always in the local (OverallLeftShift) coordinate space.
4668 ///
4669 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4670                               SmallVector<Value*, 8> &ByteValues) {
4671   if (Instruction *I = dyn_cast<Instruction>(V)) {
4672     // If this is an or instruction, it may be an inner node of the bswap.
4673     if (I->getOpcode() == Instruction::Or) {
4674       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4675                                ByteValues) ||
4676              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4677                                ByteValues);
4678     }
4679   
4680     // If this is a logical shift by a constant multiple of 8, recurse with
4681     // OverallLeftShift and ByteMask adjusted.
4682     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4683       unsigned ShAmt = 
4684         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4685       // Ensure the shift amount is defined and of a byte value.
4686       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4687         return true;
4688
4689       unsigned ByteShift = ShAmt >> 3;
4690       if (I->getOpcode() == Instruction::Shl) {
4691         // X << 2 -> collect(X, +2)
4692         OverallLeftShift += ByteShift;
4693         ByteMask >>= ByteShift;
4694       } else {
4695         // X >>u 2 -> collect(X, -2)
4696         OverallLeftShift -= ByteShift;
4697         ByteMask <<= ByteShift;
4698         ByteMask &= (~0U >> (32-ByteValues.size()));
4699       }
4700
4701       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4702       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4703
4704       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4705                                ByteValues);
4706     }
4707
4708     // If this is a logical 'and' with a mask that clears bytes, clear the
4709     // corresponding bytes in ByteMask.
4710     if (I->getOpcode() == Instruction::And &&
4711         isa<ConstantInt>(I->getOperand(1))) {
4712       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4713       unsigned NumBytes = ByteValues.size();
4714       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4715       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4716       
4717       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4718         // If this byte is masked out by a later operation, we don't care what
4719         // the and mask is.
4720         if ((ByteMask & (1 << i)) == 0)
4721           continue;
4722         
4723         // If the AndMask is all zeros for this byte, clear the bit.
4724         APInt MaskB = AndMask & Byte;
4725         if (MaskB == 0) {
4726           ByteMask &= ~(1U << i);
4727           continue;
4728         }
4729         
4730         // If the AndMask is not all ones for this byte, it's not a bytezap.
4731         if (MaskB != Byte)
4732           return true;
4733
4734         // Otherwise, this byte is kept.
4735       }
4736
4737       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4738                                ByteValues);
4739     }
4740   }
4741   
4742   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4743   // the input value to the bswap.  Some observations: 1) if more than one byte
4744   // is demanded from this input, then it could not be successfully assembled
4745   // into a byteswap.  At least one of the two bytes would not be aligned with
4746   // their ultimate destination.
4747   if (!isPowerOf2_32(ByteMask)) return true;
4748   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4749   
4750   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4751   // is demanded, it needs to go into byte 0 of the result.  This means that the
4752   // byte needs to be shifted until it lands in the right byte bucket.  The
4753   // shift amount depends on the position: if the byte is coming from the high
4754   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4755   // low part, it must be shifted left.
4756   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4757   if (InputByteNo < ByteValues.size()/2) {
4758     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4759       return true;
4760   } else {
4761     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4762       return true;
4763   }
4764   
4765   // If the destination byte value is already defined, the values are or'd
4766   // together, which isn't a bswap (unless it's an or of the same bits).
4767   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4768     return true;
4769   ByteValues[DestByteNo] = V;
4770   return false;
4771 }
4772
4773 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4774 /// If so, insert the new bswap intrinsic and return it.
4775 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4776   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4777   if (!ITy || ITy->getBitWidth() % 16 || 
4778       // ByteMask only allows up to 32-byte values.
4779       ITy->getBitWidth() > 32*8) 
4780     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4781   
4782   /// ByteValues - For each byte of the result, we keep track of which value
4783   /// defines each byte.
4784   SmallVector<Value*, 8> ByteValues;
4785   ByteValues.resize(ITy->getBitWidth()/8);
4786     
4787   // Try to find all the pieces corresponding to the bswap.
4788   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4789   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4790     return 0;
4791   
4792   // Check to see if all of the bytes come from the same value.
4793   Value *V = ByteValues[0];
4794   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4795   
4796   // Check to make sure that all of the bytes come from the same value.
4797   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4798     if (ByteValues[i] != V)
4799       return 0;
4800   const Type *Tys[] = { ITy };
4801   Module *M = I.getParent()->getParent()->getParent();
4802   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4803   return CallInst::Create(F, V);
4804 }
4805
4806 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4807 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4808 /// we can simplify this expression to "cond ? C : D or B".
4809 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4810                                          Value *C, Value *D,
4811                                          LLVMContext *Context) {
4812   // If A is not a select of -1/0, this cannot match.
4813   Value *Cond = 0;
4814   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4815     return 0;
4816
4817   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4818   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4819     return SelectInst::Create(Cond, C, B);
4820   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4821     return SelectInst::Create(Cond, C, B);
4822   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4823   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4824     return SelectInst::Create(Cond, C, D);
4825   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4826     return SelectInst::Create(Cond, C, D);
4827   return 0;
4828 }
4829
4830 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4831 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4832                                          ICmpInst *LHS, ICmpInst *RHS) {
4833   // (icmp ne A, null) | (icmp ne B, null) -->
4834   //     (icmp ne (ptrtoint(A)|ptrtoint(B)), 0)
4835   if (TD &&
4836       LHS->getPredicate() == ICmpInst::ICMP_NE &&
4837       RHS->getPredicate() == ICmpInst::ICMP_NE &&
4838       isa<ConstantPointerNull>(LHS->getOperand(1)) &&
4839       isa<ConstantPointerNull>(RHS->getOperand(1))) {
4840     const Type *IntPtrTy = TD->getIntPtrType(I.getContext());
4841     Value *A = Builder->CreatePtrToInt(LHS->getOperand(0), IntPtrTy);
4842     Value *B = Builder->CreatePtrToInt(RHS->getOperand(0), IntPtrTy);
4843     Value *NewOr = Builder->CreateOr(A, B);
4844     return new ICmpInst(ICmpInst::ICMP_NE, NewOr,
4845                         Constant::getNullValue(IntPtrTy));
4846   }
4847   
4848   Value *Val, *Val2;
4849   ConstantInt *LHSCst, *RHSCst;
4850   ICmpInst::Predicate LHSCC, RHSCC;
4851   
4852   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4853   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4854       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4855     return 0;
4856
4857   
4858   // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
4859   if (LHSCst == RHSCst && LHSCC == RHSCC &&
4860       LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
4861     Value *NewOr = Builder->CreateOr(Val, Val2);
4862     return new ICmpInst(LHSCC, NewOr, LHSCst);
4863   }
4864   
4865   // From here on, we only handle:
4866   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4867   if (Val != Val2) return 0;
4868   
4869   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4870   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4871       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4872       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4873       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4874     return 0;
4875   
4876   // We can't fold (ugt x, C) | (sgt x, C2).
4877   if (!PredicatesFoldable(LHSCC, RHSCC))
4878     return 0;
4879   
4880   // Ensure that the larger constant is on the RHS.
4881   bool ShouldSwap;
4882   if (CmpInst::isSigned(LHSCC) ||
4883       (ICmpInst::isEquality(LHSCC) && 
4884        CmpInst::isSigned(RHSCC)))
4885     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4886   else
4887     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4888   
4889   if (ShouldSwap) {
4890     std::swap(LHS, RHS);
4891     std::swap(LHSCst, RHSCst);
4892     std::swap(LHSCC, RHSCC);
4893   }
4894   
4895   // At this point, we know we have have two icmp instructions
4896   // comparing a value against two constants and or'ing the result
4897   // together.  Because of the above check, we know that we only have
4898   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4899   // FoldICmpLogical check above), that the two constants are not
4900   // equal.
4901   assert(LHSCst != RHSCst && "Compares not folded above?");
4902
4903   switch (LHSCC) {
4904   default: llvm_unreachable("Unknown integer condition code!");
4905   case ICmpInst::ICMP_EQ:
4906     switch (RHSCC) {
4907     default: llvm_unreachable("Unknown integer condition code!");
4908     case ICmpInst::ICMP_EQ:
4909       if (LHSCst == SubOne(RHSCst)) {
4910         // (X == 13 | X == 14) -> X-13 <u 2
4911         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4912         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4913         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4914         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4915       }
4916       break;                         // (X == 13 | X == 15) -> no change
4917     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4918     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4919       break;
4920     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4921     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4922     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4923       return ReplaceInstUsesWith(I, RHS);
4924     }
4925     break;
4926   case ICmpInst::ICMP_NE:
4927     switch (RHSCC) {
4928     default: llvm_unreachable("Unknown integer condition code!");
4929     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4930     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4931     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4932       return ReplaceInstUsesWith(I, LHS);
4933     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4934     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4935     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4936       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4937     }
4938     break;
4939   case ICmpInst::ICMP_ULT:
4940     switch (RHSCC) {
4941     default: llvm_unreachable("Unknown integer condition code!");
4942     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4943       break;
4944     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4945       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4946       // this can cause overflow.
4947       if (RHSCst->isMaxValue(false))
4948         return ReplaceInstUsesWith(I, LHS);
4949       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4950                              false, false, I);
4951     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4952       break;
4953     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4954     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4955       return ReplaceInstUsesWith(I, RHS);
4956     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4957       break;
4958     }
4959     break;
4960   case ICmpInst::ICMP_SLT:
4961     switch (RHSCC) {
4962     default: llvm_unreachable("Unknown integer condition code!");
4963     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4964       break;
4965     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4966       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4967       // this can cause overflow.
4968       if (RHSCst->isMaxValue(true))
4969         return ReplaceInstUsesWith(I, LHS);
4970       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4971                              true, false, I);
4972     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4973       break;
4974     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4975     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4976       return ReplaceInstUsesWith(I, RHS);
4977     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4978       break;
4979     }
4980     break;
4981   case ICmpInst::ICMP_UGT:
4982     switch (RHSCC) {
4983     default: llvm_unreachable("Unknown integer condition code!");
4984     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4985     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4986       return ReplaceInstUsesWith(I, LHS);
4987     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4988       break;
4989     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4990     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4991       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4992     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4993       break;
4994     }
4995     break;
4996   case ICmpInst::ICMP_SGT:
4997     switch (RHSCC) {
4998     default: llvm_unreachable("Unknown integer condition code!");
4999     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
5000     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
5001       return ReplaceInstUsesWith(I, LHS);
5002     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
5003       break;
5004     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
5005     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
5006       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5007     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
5008       break;
5009     }
5010     break;
5011   }
5012   return 0;
5013 }
5014
5015 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
5016                                          FCmpInst *RHS) {
5017   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
5018       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
5019       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
5020     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
5021       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
5022         // If either of the constants are nans, then the whole thing returns
5023         // true.
5024         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
5025           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5026         
5027         // Otherwise, no need to compare the two constants, compare the
5028         // rest.
5029         return new FCmpInst(FCmpInst::FCMP_UNO,
5030                             LHS->getOperand(0), RHS->getOperand(0));
5031       }
5032     
5033     // Handle vector zeros.  This occurs because the canonical form of
5034     // "fcmp uno x,x" is "fcmp uno x, 0".
5035     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
5036         isa<ConstantAggregateZero>(RHS->getOperand(1)))
5037       return new FCmpInst(FCmpInst::FCMP_UNO,
5038                           LHS->getOperand(0), RHS->getOperand(0));
5039     
5040     return 0;
5041   }
5042   
5043   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
5044   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
5045   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
5046   
5047   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
5048     // Swap RHS operands to match LHS.
5049     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
5050     std::swap(Op1LHS, Op1RHS);
5051   }
5052   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
5053     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
5054     if (Op0CC == Op1CC)
5055       return new FCmpInst((FCmpInst::Predicate)Op0CC,
5056                           Op0LHS, Op0RHS);
5057     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
5058       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5059     if (Op0CC == FCmpInst::FCMP_FALSE)
5060       return ReplaceInstUsesWith(I, RHS);
5061     if (Op1CC == FCmpInst::FCMP_FALSE)
5062       return ReplaceInstUsesWith(I, LHS);
5063     bool Op0Ordered;
5064     bool Op1Ordered;
5065     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
5066     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
5067     if (Op0Ordered == Op1Ordered) {
5068       // If both are ordered or unordered, return a new fcmp with
5069       // or'ed predicates.
5070       Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
5071                                Op0LHS, Op0RHS, Context);
5072       if (Instruction *I = dyn_cast<Instruction>(RV))
5073         return I;
5074       // Otherwise, it's a constant boolean value...
5075       return ReplaceInstUsesWith(I, RV);
5076     }
5077   }
5078   return 0;
5079 }
5080
5081 /// FoldOrWithConstants - This helper function folds:
5082 ///
5083 ///     ((A | B) & C1) | (B & C2)
5084 ///
5085 /// into:
5086 /// 
5087 ///     (A & C1) | B
5088 ///
5089 /// when the XOR of the two constants is "all ones" (-1).
5090 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
5091                                                Value *A, Value *B, Value *C) {
5092   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
5093   if (!CI1) return 0;
5094
5095   Value *V1 = 0;
5096   ConstantInt *CI2 = 0;
5097   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
5098
5099   APInt Xor = CI1->getValue() ^ CI2->getValue();
5100   if (!Xor.isAllOnesValue()) return 0;
5101
5102   if (V1 == A || V1 == B) {
5103     Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
5104     return BinaryOperator::CreateOr(NewOp, V1);
5105   }
5106
5107   return 0;
5108 }
5109
5110 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
5111   bool Changed = SimplifyCommutative(I);
5112   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5113
5114   if (Value *V = SimplifyOrInst(Op0, Op1, TD))
5115     return ReplaceInstUsesWith(I, V);
5116   
5117   
5118   // See if we can simplify any instructions used by the instruction whose sole 
5119   // purpose is to compute bits we don't care about.
5120   if (SimplifyDemandedInstructionBits(I))
5121     return &I;
5122
5123   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5124     ConstantInt *C1 = 0; Value *X = 0;
5125     // (X & C1) | C2 --> (X | C2) & (C1|C2)
5126     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
5127         isOnlyUse(Op0)) {
5128       Value *Or = Builder->CreateOr(X, RHS);
5129       Or->takeName(Op0);
5130       return BinaryOperator::CreateAnd(Or, 
5131                ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
5132     }
5133
5134     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
5135     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
5136         isOnlyUse(Op0)) {
5137       Value *Or = Builder->CreateOr(X, RHS);
5138       Or->takeName(Op0);
5139       return BinaryOperator::CreateXor(Or,
5140                  ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
5141     }
5142
5143     // Try to fold constant and into select arguments.
5144     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5145       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5146         return R;
5147     if (isa<PHINode>(Op0))
5148       if (Instruction *NV = FoldOpIntoPhi(I))
5149         return NV;
5150   }
5151
5152   Value *A = 0, *B = 0;
5153   ConstantInt *C1 = 0, *C2 = 0;
5154
5155   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
5156   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
5157   if (match(Op0, m_Or(m_Value(), m_Value())) ||
5158       match(Op1, m_Or(m_Value(), m_Value())) ||
5159       (match(Op0, m_Shift(m_Value(), m_Value())) &&
5160        match(Op1, m_Shift(m_Value(), m_Value())))) {
5161     if (Instruction *BSwap = MatchBSwap(I))
5162       return BSwap;
5163   }
5164   
5165   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
5166   if (Op0->hasOneUse() &&
5167       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
5168       MaskedValueIsZero(Op1, C1->getValue())) {
5169     Value *NOr = Builder->CreateOr(A, Op1);
5170     NOr->takeName(Op0);
5171     return BinaryOperator::CreateXor(NOr, C1);
5172   }
5173
5174   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
5175   if (Op1->hasOneUse() &&
5176       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
5177       MaskedValueIsZero(Op0, C1->getValue())) {
5178     Value *NOr = Builder->CreateOr(A, Op0);
5179     NOr->takeName(Op0);
5180     return BinaryOperator::CreateXor(NOr, C1);
5181   }
5182
5183   // (A & C)|(B & D)
5184   Value *C = 0, *D = 0;
5185   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
5186       match(Op1, m_And(m_Value(B), m_Value(D)))) {
5187     Value *V1 = 0, *V2 = 0, *V3 = 0;
5188     C1 = dyn_cast<ConstantInt>(C);
5189     C2 = dyn_cast<ConstantInt>(D);
5190     if (C1 && C2) {  // (A & C1)|(B & C2)
5191       // If we have: ((V + N) & C1) | (V & C2)
5192       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
5193       // replace with V+N.
5194       if (C1->getValue() == ~C2->getValue()) {
5195         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
5196             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
5197           // Add commutes, try both ways.
5198           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
5199             return ReplaceInstUsesWith(I, A);
5200           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
5201             return ReplaceInstUsesWith(I, A);
5202         }
5203         // Or commutes, try both ways.
5204         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
5205             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
5206           // Add commutes, try both ways.
5207           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
5208             return ReplaceInstUsesWith(I, B);
5209           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
5210             return ReplaceInstUsesWith(I, B);
5211         }
5212       }
5213       V1 = 0; V2 = 0; V3 = 0;
5214     }
5215     
5216     // Check to see if we have any common things being and'ed.  If so, find the
5217     // terms for V1 & (V2|V3).
5218     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
5219       if (A == B)      // (A & C)|(A & D) == A & (C|D)
5220         V1 = A, V2 = C, V3 = D;
5221       else if (A == D) // (A & C)|(B & A) == A & (B|C)
5222         V1 = A, V2 = B, V3 = C;
5223       else if (C == B) // (A & C)|(C & D) == C & (A|D)
5224         V1 = C, V2 = A, V3 = D;
5225       else if (C == D) // (A & C)|(B & C) == C & (A|B)
5226         V1 = C, V2 = A, V3 = B;
5227       
5228       if (V1) {
5229         Value *Or = Builder->CreateOr(V2, V3, "tmp");
5230         return BinaryOperator::CreateAnd(V1, Or);
5231       }
5232     }
5233
5234     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
5235     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
5236       return Match;
5237     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
5238       return Match;
5239     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
5240       return Match;
5241     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
5242       return Match;
5243
5244     // ((A&~B)|(~A&B)) -> A^B
5245     if ((match(C, m_Not(m_Specific(D))) &&
5246          match(B, m_Not(m_Specific(A)))))
5247       return BinaryOperator::CreateXor(A, D);
5248     // ((~B&A)|(~A&B)) -> A^B
5249     if ((match(A, m_Not(m_Specific(D))) &&
5250          match(B, m_Not(m_Specific(C)))))
5251       return BinaryOperator::CreateXor(C, D);
5252     // ((A&~B)|(B&~A)) -> A^B
5253     if ((match(C, m_Not(m_Specific(B))) &&
5254          match(D, m_Not(m_Specific(A)))))
5255       return BinaryOperator::CreateXor(A, B);
5256     // ((~B&A)|(B&~A)) -> A^B
5257     if ((match(A, m_Not(m_Specific(B))) &&
5258          match(D, m_Not(m_Specific(C)))))
5259       return BinaryOperator::CreateXor(C, B);
5260   }
5261   
5262   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
5263   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
5264     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
5265       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
5266           SI0->getOperand(1) == SI1->getOperand(1) &&
5267           (SI0->hasOneUse() || SI1->hasOneUse())) {
5268         Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
5269                                          SI0->getName());
5270         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
5271                                       SI1->getOperand(1));
5272       }
5273   }
5274
5275   // ((A|B)&1)|(B&-2) -> (A&1) | B
5276   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5277       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
5278     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
5279     if (Ret) return Ret;
5280   }
5281   // (B&-2)|((A|B)&1) -> (A&1) | B
5282   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5283       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
5284     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
5285     if (Ret) return Ret;
5286   }
5287
5288   // (~A | ~B) == (~(A & B)) - De Morgan's Law
5289   if (Value *Op0NotVal = dyn_castNotVal(Op0))
5290     if (Value *Op1NotVal = dyn_castNotVal(Op1))
5291       if (Op0->hasOneUse() && Op1->hasOneUse()) {
5292         Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
5293                                         I.getName()+".demorgan");
5294         return BinaryOperator::CreateNot(And);
5295       }
5296
5297   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5298   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
5299     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5300       return R;
5301
5302     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5303       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5304         return Res;
5305   }
5306     
5307   // fold (or (cast A), (cast B)) -> (cast (or A, B))
5308   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5309     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5310       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
5311         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5312             !isa<ICmpInst>(Op1C->getOperand(0))) {
5313           const Type *SrcTy = Op0C->getOperand(0)->getType();
5314           if (SrcTy == Op1C->getOperand(0)->getType() &&
5315               SrcTy->isIntOrIntVector() &&
5316               // Only do this if the casts both really cause code to be
5317               // generated.
5318               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5319                                 I.getType(), TD) &&
5320               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5321                                 I.getType(), TD)) {
5322             Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5323                                              Op1C->getOperand(0), I.getName());
5324             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5325           }
5326         }
5327       }
5328   }
5329   
5330     
5331   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
5332   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
5333     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5334       if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5335         return Res;
5336   }
5337
5338   return Changed ? &I : 0;
5339 }
5340
5341 namespace {
5342
5343 // XorSelf - Implements: X ^ X --> 0
5344 struct XorSelf {
5345   Value *RHS;
5346   XorSelf(Value *rhs) : RHS(rhs) {}
5347   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5348   Instruction *apply(BinaryOperator &Xor) const {
5349     return &Xor;
5350   }
5351 };
5352
5353 }
5354
5355 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5356   bool Changed = SimplifyCommutative(I);
5357   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5358
5359   if (isa<UndefValue>(Op1)) {
5360     if (isa<UndefValue>(Op0))
5361       // Handle undef ^ undef -> 0 special case. This is a common
5362       // idiom (misuse).
5363       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5364     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5365   }
5366
5367   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5368   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
5369     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5370     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5371   }
5372   
5373   // See if we can simplify any instructions used by the instruction whose sole 
5374   // purpose is to compute bits we don't care about.
5375   if (SimplifyDemandedInstructionBits(I))
5376     return &I;
5377   if (isa<VectorType>(I.getType()))
5378     if (isa<ConstantAggregateZero>(Op1))
5379       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5380
5381   // Is this a ~ operation?
5382   if (Value *NotOp = dyn_castNotVal(&I)) {
5383     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5384       if (Op0I->getOpcode() == Instruction::And || 
5385           Op0I->getOpcode() == Instruction::Or) {
5386         // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5387         // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5388         if (dyn_castNotVal(Op0I->getOperand(1)))
5389           Op0I->swapOperands();
5390         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5391           Value *NotY =
5392             Builder->CreateNot(Op0I->getOperand(1),
5393                                Op0I->getOperand(1)->getName()+".not");
5394           if (Op0I->getOpcode() == Instruction::And)
5395             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5396           return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5397         }
5398         
5399         // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5400         // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5401         if (isFreeToInvert(Op0I->getOperand(0)) && 
5402             isFreeToInvert(Op0I->getOperand(1))) {
5403           Value *NotX =
5404             Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5405           Value *NotY =
5406             Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5407           if (Op0I->getOpcode() == Instruction::And)
5408             return BinaryOperator::CreateOr(NotX, NotY);
5409           return BinaryOperator::CreateAnd(NotX, NotY);
5410         }
5411       }
5412     }
5413   }
5414   
5415   
5416   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5417     if (RHS->isOne() && Op0->hasOneUse()) {
5418       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5419       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5420         return new ICmpInst(ICI->getInversePredicate(),
5421                             ICI->getOperand(0), ICI->getOperand(1));
5422
5423       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5424         return new FCmpInst(FCI->getInversePredicate(),
5425                             FCI->getOperand(0), FCI->getOperand(1));
5426     }
5427
5428     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5429     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5430       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5431         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5432           Instruction::CastOps Opcode = Op0C->getOpcode();
5433           if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5434               (RHS == ConstantExpr::getCast(Opcode, 
5435                                             ConstantInt::getTrue(*Context),
5436                                             Op0C->getDestTy()))) {
5437             CI->setPredicate(CI->getInversePredicate());
5438             return CastInst::Create(Opcode, CI, Op0C->getType());
5439           }
5440         }
5441       }
5442     }
5443
5444     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5445       // ~(c-X) == X-c-1 == X+(-c-1)
5446       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5447         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5448           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5449           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5450                                       ConstantInt::get(I.getType(), 1));
5451           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5452         }
5453           
5454       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5455         if (Op0I->getOpcode() == Instruction::Add) {
5456           // ~(X-c) --> (-c-1)-X
5457           if (RHS->isAllOnesValue()) {
5458             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5459             return BinaryOperator::CreateSub(
5460                            ConstantExpr::getSub(NegOp0CI,
5461                                       ConstantInt::get(I.getType(), 1)),
5462                                       Op0I->getOperand(0));
5463           } else if (RHS->getValue().isSignBit()) {
5464             // (X + C) ^ signbit -> (X + C + signbit)
5465             Constant *C = ConstantInt::get(*Context,
5466                                            RHS->getValue() + Op0CI->getValue());
5467             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5468
5469           }
5470         } else if (Op0I->getOpcode() == Instruction::Or) {
5471           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5472           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5473             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5474             // Anything in both C1 and C2 is known to be zero, remove it from
5475             // NewRHS.
5476             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5477             NewRHS = ConstantExpr::getAnd(NewRHS, 
5478                                        ConstantExpr::getNot(CommonBits));
5479             Worklist.Add(Op0I);
5480             I.setOperand(0, Op0I->getOperand(0));
5481             I.setOperand(1, NewRHS);
5482             return &I;
5483           }
5484         }
5485       }
5486     }
5487
5488     // Try to fold constant and into select arguments.
5489     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5490       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5491         return R;
5492     if (isa<PHINode>(Op0))
5493       if (Instruction *NV = FoldOpIntoPhi(I))
5494         return NV;
5495   }
5496
5497   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5498     if (X == Op1)
5499       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5500
5501   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5502     if (X == Op0)
5503       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5504
5505   
5506   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5507   if (Op1I) {
5508     Value *A, *B;
5509     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5510       if (A == Op0) {              // B^(B|A) == (A|B)^B
5511         Op1I->swapOperands();
5512         I.swapOperands();
5513         std::swap(Op0, Op1);
5514       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5515         I.swapOperands();     // Simplified below.
5516         std::swap(Op0, Op1);
5517       }
5518     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5519       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5520     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5521       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5522     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && 
5523                Op1I->hasOneUse()){
5524       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5525         Op1I->swapOperands();
5526         std::swap(A, B);
5527       }
5528       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5529         I.swapOperands();     // Simplified below.
5530         std::swap(Op0, Op1);
5531       }
5532     }
5533   }
5534   
5535   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5536   if (Op0I) {
5537     Value *A, *B;
5538     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5539         Op0I->hasOneUse()) {
5540       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5541         std::swap(A, B);
5542       if (B == Op1)                                  // (A|B)^B == A & ~B
5543         return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
5544     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5545       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5546     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5547       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5548     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && 
5549                Op0I->hasOneUse()){
5550       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5551         std::swap(A, B);
5552       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5553           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5554         return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
5555       }
5556     }
5557   }
5558   
5559   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5560   if (Op0I && Op1I && Op0I->isShift() && 
5561       Op0I->getOpcode() == Op1I->getOpcode() && 
5562       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5563       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5564     Value *NewOp =
5565       Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5566                          Op0I->getName());
5567     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5568                                   Op1I->getOperand(1));
5569   }
5570     
5571   if (Op0I && Op1I) {
5572     Value *A, *B, *C, *D;
5573     // (A & B)^(A | B) -> A ^ B
5574     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5575         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5576       if ((A == C && B == D) || (A == D && B == C)) 
5577         return BinaryOperator::CreateXor(A, B);
5578     }
5579     // (A | B)^(A & B) -> A ^ B
5580     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5581         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5582       if ((A == C && B == D) || (A == D && B == C)) 
5583         return BinaryOperator::CreateXor(A, B);
5584     }
5585     
5586     // (A & B)^(C & D)
5587     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5588         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5589         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5590       // (X & Y)^(X & Y) -> (Y^Z) & X
5591       Value *X = 0, *Y = 0, *Z = 0;
5592       if (A == C)
5593         X = A, Y = B, Z = D;
5594       else if (A == D)
5595         X = A, Y = B, Z = C;
5596       else if (B == C)
5597         X = B, Y = A, Z = D;
5598       else if (B == D)
5599         X = B, Y = A, Z = C;
5600       
5601       if (X) {
5602         Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
5603         return BinaryOperator::CreateAnd(NewOp, X);
5604       }
5605     }
5606   }
5607     
5608   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5609   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5610     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5611       return R;
5612
5613   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5614   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5615     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5616       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5617         const Type *SrcTy = Op0C->getOperand(0)->getType();
5618         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5619             // Only do this if the casts both really cause code to be generated.
5620             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5621                               I.getType(), TD) &&
5622             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5623                               I.getType(), TD)) {
5624           Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5625                                             Op1C->getOperand(0), I.getName());
5626           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5627         }
5628       }
5629   }
5630
5631   return Changed ? &I : 0;
5632 }
5633
5634 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5635                                    LLVMContext *Context) {
5636   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5637 }
5638
5639 static bool HasAddOverflow(ConstantInt *Result,
5640                            ConstantInt *In1, ConstantInt *In2,
5641                            bool IsSigned) {
5642   if (IsSigned)
5643     if (In2->getValue().isNegative())
5644       return Result->getValue().sgt(In1->getValue());
5645     else
5646       return Result->getValue().slt(In1->getValue());
5647   else
5648     return Result->getValue().ult(In1->getValue());
5649 }
5650
5651 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5652 /// overflowed for this type.
5653 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5654                             Constant *In2, LLVMContext *Context,
5655                             bool IsSigned = false) {
5656   Result = ConstantExpr::getAdd(In1, In2);
5657
5658   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5659     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5660       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5661       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5662                          ExtractElement(In1, Idx, Context),
5663                          ExtractElement(In2, Idx, Context),
5664                          IsSigned))
5665         return true;
5666     }
5667     return false;
5668   }
5669
5670   return HasAddOverflow(cast<ConstantInt>(Result),
5671                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5672                         IsSigned);
5673 }
5674
5675 static bool HasSubOverflow(ConstantInt *Result,
5676                            ConstantInt *In1, ConstantInt *In2,
5677                            bool IsSigned) {
5678   if (IsSigned)
5679     if (In2->getValue().isNegative())
5680       return Result->getValue().slt(In1->getValue());
5681     else
5682       return Result->getValue().sgt(In1->getValue());
5683   else
5684     return Result->getValue().ugt(In1->getValue());
5685 }
5686
5687 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5688 /// overflowed for this type.
5689 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5690                             Constant *In2, LLVMContext *Context,
5691                             bool IsSigned = false) {
5692   Result = ConstantExpr::getSub(In1, In2);
5693
5694   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5695     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5696       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5697       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5698                          ExtractElement(In1, Idx, Context),
5699                          ExtractElement(In2, Idx, Context),
5700                          IsSigned))
5701         return true;
5702     }
5703     return false;
5704   }
5705
5706   return HasSubOverflow(cast<ConstantInt>(Result),
5707                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5708                         IsSigned);
5709 }
5710
5711
5712 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5713 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5714 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5715                                        ICmpInst::Predicate Cond,
5716                                        Instruction &I) {
5717   // Look through bitcasts.
5718   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5719     RHS = BCI->getOperand(0);
5720
5721   Value *PtrBase = GEPLHS->getOperand(0);
5722   if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5723     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5724     // This transformation (ignoring the base and scales) is valid because we
5725     // know pointers can't overflow since the gep is inbounds.  See if we can
5726     // output an optimized form.
5727     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5728     
5729     // If not, synthesize the offset the hard way.
5730     if (Offset == 0)
5731       Offset = EmitGEPOffset(GEPLHS, *this);
5732     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5733                         Constant::getNullValue(Offset->getType()));
5734   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5735     // If the base pointers are different, but the indices are the same, just
5736     // compare the base pointer.
5737     if (PtrBase != GEPRHS->getOperand(0)) {
5738       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5739       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5740                         GEPRHS->getOperand(0)->getType();
5741       if (IndicesTheSame)
5742         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5743           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5744             IndicesTheSame = false;
5745             break;
5746           }
5747
5748       // If all indices are the same, just compare the base pointers.
5749       if (IndicesTheSame)
5750         return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5751                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5752
5753       // Otherwise, the base pointers are different and the indices are
5754       // different, bail out.
5755       return 0;
5756     }
5757
5758     // If one of the GEPs has all zero indices, recurse.
5759     bool AllZeros = true;
5760     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5761       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5762           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5763         AllZeros = false;
5764         break;
5765       }
5766     if (AllZeros)
5767       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5768                           ICmpInst::getSwappedPredicate(Cond), I);
5769
5770     // If the other GEP has all zero indices, recurse.
5771     AllZeros = true;
5772     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5773       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5774           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5775         AllZeros = false;
5776         break;
5777       }
5778     if (AllZeros)
5779       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5780
5781     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5782       // If the GEPs only differ by one index, compare it.
5783       unsigned NumDifferences = 0;  // Keep track of # differences.
5784       unsigned DiffOperand = 0;     // The operand that differs.
5785       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5786         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5787           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5788                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5789             // Irreconcilable differences.
5790             NumDifferences = 2;
5791             break;
5792           } else {
5793             if (NumDifferences++) break;
5794             DiffOperand = i;
5795           }
5796         }
5797
5798       if (NumDifferences == 0)   // SAME GEP?
5799         return ReplaceInstUsesWith(I, // No comparison is needed here.
5800                                    ConstantInt::get(Type::getInt1Ty(*Context),
5801                                              ICmpInst::isTrueWhenEqual(Cond)));
5802
5803       else if (NumDifferences == 1) {
5804         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5805         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5806         // Make sure we do a signed comparison here.
5807         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5808       }
5809     }
5810
5811     // Only lower this if the icmp is the only user of the GEP or if we expect
5812     // the result to fold to a constant!
5813     if (TD &&
5814         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5815         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5816       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5817       Value *L = EmitGEPOffset(GEPLHS, *this);
5818       Value *R = EmitGEPOffset(GEPRHS, *this);
5819       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5820     }
5821   }
5822   return 0;
5823 }
5824
5825 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5826 ///
5827 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5828                                                 Instruction *LHSI,
5829                                                 Constant *RHSC) {
5830   if (!isa<ConstantFP>(RHSC)) return 0;
5831   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5832   
5833   // Get the width of the mantissa.  We don't want to hack on conversions that
5834   // might lose information from the integer, e.g. "i64 -> float"
5835   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5836   if (MantissaWidth == -1) return 0;  // Unknown.
5837   
5838   // Check to see that the input is converted from an integer type that is small
5839   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5840   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5841   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5842   
5843   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5844   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5845   if (LHSUnsigned)
5846     ++InputSize;
5847   
5848   // If the conversion would lose info, don't hack on this.
5849   if ((int)InputSize > MantissaWidth)
5850     return 0;
5851   
5852   // Otherwise, we can potentially simplify the comparison.  We know that it
5853   // will always come through as an integer value and we know the constant is
5854   // not a NAN (it would have been previously simplified).
5855   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5856   
5857   ICmpInst::Predicate Pred;
5858   switch (I.getPredicate()) {
5859   default: llvm_unreachable("Unexpected predicate!");
5860   case FCmpInst::FCMP_UEQ:
5861   case FCmpInst::FCMP_OEQ:
5862     Pred = ICmpInst::ICMP_EQ;
5863     break;
5864   case FCmpInst::FCMP_UGT:
5865   case FCmpInst::FCMP_OGT:
5866     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5867     break;
5868   case FCmpInst::FCMP_UGE:
5869   case FCmpInst::FCMP_OGE:
5870     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5871     break;
5872   case FCmpInst::FCMP_ULT:
5873   case FCmpInst::FCMP_OLT:
5874     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5875     break;
5876   case FCmpInst::FCMP_ULE:
5877   case FCmpInst::FCMP_OLE:
5878     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5879     break;
5880   case FCmpInst::FCMP_UNE:
5881   case FCmpInst::FCMP_ONE:
5882     Pred = ICmpInst::ICMP_NE;
5883     break;
5884   case FCmpInst::FCMP_ORD:
5885     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5886   case FCmpInst::FCMP_UNO:
5887     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5888   }
5889   
5890   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5891   
5892   // Now we know that the APFloat is a normal number, zero or inf.
5893   
5894   // See if the FP constant is too large for the integer.  For example,
5895   // comparing an i8 to 300.0.
5896   unsigned IntWidth = IntTy->getScalarSizeInBits();
5897   
5898   if (!LHSUnsigned) {
5899     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5900     // and large values.
5901     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5902     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5903                           APFloat::rmNearestTiesToEven);
5904     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5905       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5906           Pred == ICmpInst::ICMP_SLE)
5907         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5908       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5909     }
5910   } else {
5911     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5912     // +INF and large values.
5913     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5914     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5915                           APFloat::rmNearestTiesToEven);
5916     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5917       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5918           Pred == ICmpInst::ICMP_ULE)
5919         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5920       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5921     }
5922   }
5923   
5924   if (!LHSUnsigned) {
5925     // See if the RHS value is < SignedMin.
5926     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5927     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5928                           APFloat::rmNearestTiesToEven);
5929     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5930       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5931           Pred == ICmpInst::ICMP_SGE)
5932         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5933       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5934     }
5935   }
5936
5937   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5938   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5939   // casting the FP value to the integer value and back, checking for equality.
5940   // Don't do this for zero, because -0.0 is not fractional.
5941   Constant *RHSInt = LHSUnsigned
5942     ? ConstantExpr::getFPToUI(RHSC, IntTy)
5943     : ConstantExpr::getFPToSI(RHSC, IntTy);
5944   if (!RHS.isZero()) {
5945     bool Equal = LHSUnsigned
5946       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5947       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5948     if (!Equal) {
5949       // If we had a comparison against a fractional value, we have to adjust
5950       // the compare predicate and sometimes the value.  RHSC is rounded towards
5951       // zero at this point.
5952       switch (Pred) {
5953       default: llvm_unreachable("Unexpected integer comparison!");
5954       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5955         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5956       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5957         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5958       case ICmpInst::ICMP_ULE:
5959         // (float)int <= 4.4   --> int <= 4
5960         // (float)int <= -4.4  --> false
5961         if (RHS.isNegative())
5962           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5963         break;
5964       case ICmpInst::ICMP_SLE:
5965         // (float)int <= 4.4   --> int <= 4
5966         // (float)int <= -4.4  --> int < -4
5967         if (RHS.isNegative())
5968           Pred = ICmpInst::ICMP_SLT;
5969         break;
5970       case ICmpInst::ICMP_ULT:
5971         // (float)int < -4.4   --> false
5972         // (float)int < 4.4    --> int <= 4
5973         if (RHS.isNegative())
5974           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5975         Pred = ICmpInst::ICMP_ULE;
5976         break;
5977       case ICmpInst::ICMP_SLT:
5978         // (float)int < -4.4   --> int < -4
5979         // (float)int < 4.4    --> int <= 4
5980         if (!RHS.isNegative())
5981           Pred = ICmpInst::ICMP_SLE;
5982         break;
5983       case ICmpInst::ICMP_UGT:
5984         // (float)int > 4.4    --> int > 4
5985         // (float)int > -4.4   --> true
5986         if (RHS.isNegative())
5987           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5988         break;
5989       case ICmpInst::ICMP_SGT:
5990         // (float)int > 4.4    --> int > 4
5991         // (float)int > -4.4   --> int >= -4
5992         if (RHS.isNegative())
5993           Pred = ICmpInst::ICMP_SGE;
5994         break;
5995       case ICmpInst::ICMP_UGE:
5996         // (float)int >= -4.4   --> true
5997         // (float)int >= 4.4    --> int > 4
5998         if (!RHS.isNegative())
5999           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6000         Pred = ICmpInst::ICMP_UGT;
6001         break;
6002       case ICmpInst::ICMP_SGE:
6003         // (float)int >= -4.4   --> int >= -4
6004         // (float)int >= 4.4    --> int > 4
6005         if (!RHS.isNegative())
6006           Pred = ICmpInst::ICMP_SGT;
6007         break;
6008       }
6009     }
6010   }
6011
6012   // Lower this FP comparison into an appropriate integer version of the
6013   // comparison.
6014   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
6015 }
6016
6017 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
6018   bool Changed = false;
6019   
6020   /// Orders the operands of the compare so that they are listed from most
6021   /// complex to least complex.  This puts constants before unary operators,
6022   /// before binary operators.
6023   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6024     I.swapOperands();
6025     Changed = true;
6026   }
6027
6028   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6029   
6030   if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
6031     return ReplaceInstUsesWith(I, V);
6032
6033   // Simplify 'fcmp pred X, X'
6034   if (Op0 == Op1) {
6035     switch (I.getPredicate()) {
6036     default: llvm_unreachable("Unknown predicate!");
6037     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
6038     case FCmpInst::FCMP_ULT:    // True if unordered or less than
6039     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
6040     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
6041       // Canonicalize these to be 'fcmp uno %X, 0.0'.
6042       I.setPredicate(FCmpInst::FCMP_UNO);
6043       I.setOperand(1, Constant::getNullValue(Op0->getType()));
6044       return &I;
6045       
6046     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
6047     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
6048     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
6049     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
6050       // Canonicalize these to be 'fcmp ord %X, 0.0'.
6051       I.setPredicate(FCmpInst::FCMP_ORD);
6052       I.setOperand(1, Constant::getNullValue(Op0->getType()));
6053       return &I;
6054     }
6055   }
6056     
6057   // Handle fcmp with constant RHS
6058   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6059     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6060       switch (LHSI->getOpcode()) {
6061       case Instruction::PHI:
6062         // Only fold fcmp into the PHI if the phi and fcmp are in the same
6063         // block.  If in the same block, we're encouraging jump threading.  If
6064         // not, we are just pessimizing the code by making an i1 phi.
6065         if (LHSI->getParent() == I.getParent())
6066           if (Instruction *NV = FoldOpIntoPhi(I, true))
6067             return NV;
6068         break;
6069       case Instruction::SIToFP:
6070       case Instruction::UIToFP:
6071         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
6072           return NV;
6073         break;
6074       case Instruction::Select:
6075         // If either operand of the select is a constant, we can fold the
6076         // comparison into the select arms, which will cause one to be
6077         // constant folded and the select turned into a bitwise or.
6078         Value *Op1 = 0, *Op2 = 0;
6079         if (LHSI->hasOneUse()) {
6080           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6081             // Fold the known value into the constant operand.
6082             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
6083             // Insert a new FCmp of the other select operand.
6084             Op2 = Builder->CreateFCmp(I.getPredicate(),
6085                                       LHSI->getOperand(2), RHSC, I.getName());
6086           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6087             // Fold the known value into the constant operand.
6088             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
6089             // Insert a new FCmp of the other select operand.
6090             Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
6091                                       RHSC, I.getName());
6092           }
6093         }
6094
6095         if (Op1)
6096           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6097         break;
6098       }
6099   }
6100
6101   return Changed ? &I : 0;
6102 }
6103
6104 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
6105   bool Changed = false;
6106   
6107   /// Orders the operands of the compare so that they are listed from most
6108   /// complex to least complex.  This puts constants before unary operators,
6109   /// before binary operators.
6110   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6111     I.swapOperands();
6112     Changed = true;
6113   }
6114   
6115   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6116   
6117   if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
6118     return ReplaceInstUsesWith(I, V);
6119   
6120   const Type *Ty = Op0->getType();
6121
6122   // icmp's with boolean values can always be turned into bitwise operations
6123   if (Ty == Type::getInt1Ty(*Context)) {
6124     switch (I.getPredicate()) {
6125     default: llvm_unreachable("Invalid icmp instruction!");
6126     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
6127       Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
6128       return BinaryOperator::CreateNot(Xor);
6129     }
6130     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
6131       return BinaryOperator::CreateXor(Op0, Op1);
6132
6133     case ICmpInst::ICMP_UGT:
6134       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
6135       // FALL THROUGH
6136     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
6137       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
6138       return BinaryOperator::CreateAnd(Not, Op1);
6139     }
6140     case ICmpInst::ICMP_SGT:
6141       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
6142       // FALL THROUGH
6143     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
6144       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
6145       return BinaryOperator::CreateAnd(Not, Op0);
6146     }
6147     case ICmpInst::ICMP_UGE:
6148       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6149       // FALL THROUGH
6150     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6151       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
6152       return BinaryOperator::CreateOr(Not, Op1);
6153     }
6154     case ICmpInst::ICMP_SGE:
6155       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6156       // FALL THROUGH
6157     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6158       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
6159       return BinaryOperator::CreateOr(Not, Op0);
6160     }
6161     }
6162   }
6163
6164   unsigned BitWidth = 0;
6165   if (TD)
6166     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6167   else if (Ty->isIntOrIntVector())
6168     BitWidth = Ty->getScalarSizeInBits();
6169
6170   bool isSignBit = false;
6171
6172   // See if we are doing a comparison with a constant.
6173   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6174     Value *A = 0, *B = 0;
6175     
6176     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6177     if (I.isEquality() && CI->isNullValue() &&
6178         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
6179       // (icmp cond A B) if cond is equality
6180       return new ICmpInst(I.getPredicate(), A, B);
6181     }
6182     
6183     // If we have an icmp le or icmp ge instruction, turn it into the
6184     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6185     // them being folded in the code below.  The SimplifyICmpInst code has
6186     // already handled the edge cases for us, so we just assert on them.
6187     switch (I.getPredicate()) {
6188     default: break;
6189     case ICmpInst::ICMP_ULE:
6190       assert(!CI->isMaxValue(false));                 // A <=u MAX -> TRUE
6191       return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
6192                           AddOne(CI));
6193     case ICmpInst::ICMP_SLE:
6194       assert(!CI->isMaxValue(true));                  // A <=s MAX -> TRUE
6195       return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6196                           AddOne(CI));
6197     case ICmpInst::ICMP_UGE:
6198       assert(!CI->isMinValue(false));                  // A >=u MIN -> TRUE
6199       return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
6200                           SubOne(CI));
6201     case ICmpInst::ICMP_SGE:
6202       assert(!CI->isMinValue(true));                   // A >=s MIN -> TRUE
6203       return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6204                           SubOne(CI));
6205     }
6206     
6207     // If this comparison is a normal comparison, it demands all
6208     // bits, if it is a sign bit comparison, it only demands the sign bit.
6209     bool UnusedBit;
6210     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6211   }
6212
6213   // See if we can fold the comparison based on range information we can get
6214   // by checking whether bits are known to be zero or one in the input.
6215   if (BitWidth != 0) {
6216     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6217     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6218
6219     if (SimplifyDemandedBits(I.getOperandUse(0),
6220                              isSignBit ? APInt::getSignBit(BitWidth)
6221                                        : APInt::getAllOnesValue(BitWidth),
6222                              Op0KnownZero, Op0KnownOne, 0))
6223       return &I;
6224     if (SimplifyDemandedBits(I.getOperandUse(1),
6225                              APInt::getAllOnesValue(BitWidth),
6226                              Op1KnownZero, Op1KnownOne, 0))
6227       return &I;
6228
6229     // Given the known and unknown bits, compute a range that the LHS could be
6230     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6231     // EQ and NE we use unsigned values.
6232     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6233     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6234     if (I.isSigned()) {
6235       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6236                                              Op0Min, Op0Max);
6237       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6238                                              Op1Min, Op1Max);
6239     } else {
6240       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6241                                                Op0Min, Op0Max);
6242       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6243                                                Op1Min, Op1Max);
6244     }
6245
6246     // If Min and Max are known to be the same, then SimplifyDemandedBits
6247     // figured out that the LHS is a constant.  Just constant fold this now so
6248     // that code below can assume that Min != Max.
6249     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6250       return new ICmpInst(I.getPredicate(),
6251                           ConstantInt::get(*Context, Op0Min), Op1);
6252     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6253       return new ICmpInst(I.getPredicate(), Op0,
6254                           ConstantInt::get(*Context, Op1Min));
6255
6256     // Based on the range information we know about the LHS, see if we can
6257     // simplify this comparison.  For example, (x&4) < 8  is always true.
6258     switch (I.getPredicate()) {
6259     default: llvm_unreachable("Unknown icmp opcode!");
6260     case ICmpInst::ICMP_EQ:
6261       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6262         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6263       break;
6264     case ICmpInst::ICMP_NE:
6265       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6266         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6267       break;
6268     case ICmpInst::ICMP_ULT:
6269       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6270         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6271       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6272         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6273       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6274         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6275       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6276         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6277           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6278                               SubOne(CI));
6279
6280         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6281         if (CI->isMinValue(true))
6282           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6283                            Constant::getAllOnesValue(Op0->getType()));
6284       }
6285       break;
6286     case ICmpInst::ICMP_UGT:
6287       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6288         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6289       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6290         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6291
6292       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6293         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6294       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6295         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6296           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6297                               AddOne(CI));
6298
6299         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6300         if (CI->isMaxValue(true))
6301           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6302                               Constant::getNullValue(Op0->getType()));
6303       }
6304       break;
6305     case ICmpInst::ICMP_SLT:
6306       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6307         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6308       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6309         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6310       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6311         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6312       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6313         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6314           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6315                               SubOne(CI));
6316       }
6317       break;
6318     case ICmpInst::ICMP_SGT:
6319       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6320         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6321       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6322         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6323
6324       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6325         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6326       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6327         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6328           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6329                               AddOne(CI));
6330       }
6331       break;
6332     case ICmpInst::ICMP_SGE:
6333       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6334       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6335         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6336       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6337         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6338       break;
6339     case ICmpInst::ICMP_SLE:
6340       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6341       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6342         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6343       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6344         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6345       break;
6346     case ICmpInst::ICMP_UGE:
6347       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6348       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6349         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6350       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6351         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6352       break;
6353     case ICmpInst::ICMP_ULE:
6354       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6355       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6356         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6357       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6358         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6359       break;
6360     }
6361
6362     // Turn a signed comparison into an unsigned one if both operands
6363     // are known to have the same sign.
6364     if (I.isSigned() &&
6365         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6366          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6367       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6368   }
6369
6370   // Test if the ICmpInst instruction is used exclusively by a select as
6371   // part of a minimum or maximum operation. If so, refrain from doing
6372   // any other folding. This helps out other analyses which understand
6373   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6374   // and CodeGen. And in this case, at least one of the comparison
6375   // operands has at least one user besides the compare (the select),
6376   // which would often largely negate the benefit of folding anyway.
6377   if (I.hasOneUse())
6378     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6379       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6380           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6381         return 0;
6382
6383   // See if we are doing a comparison between a constant and an instruction that
6384   // can be folded into the comparison.
6385   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6386     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6387     // instruction, see if that instruction also has constants so that the 
6388     // instruction can be folded into the icmp 
6389     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6390       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6391         return Res;
6392   }
6393
6394   // Handle icmp with constant (but not simple integer constant) RHS
6395   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6396     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6397       switch (LHSI->getOpcode()) {
6398       case Instruction::GetElementPtr:
6399         if (RHSC->isNullValue()) {
6400           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6401           bool isAllZeros = true;
6402           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6403             if (!isa<Constant>(LHSI->getOperand(i)) ||
6404                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6405               isAllZeros = false;
6406               break;
6407             }
6408           if (isAllZeros)
6409             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6410                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6411         }
6412         break;
6413
6414       case Instruction::PHI:
6415         // Only fold icmp into the PHI if the phi and icmp are in the same
6416         // block.  If in the same block, we're encouraging jump threading.  If
6417         // not, we are just pessimizing the code by making an i1 phi.
6418         if (LHSI->getParent() == I.getParent())
6419           if (Instruction *NV = FoldOpIntoPhi(I, true))
6420             return NV;
6421         break;
6422       case Instruction::Select: {
6423         // If either operand of the select is a constant, we can fold the
6424         // comparison into the select arms, which will cause one to be
6425         // constant folded and the select turned into a bitwise or.
6426         Value *Op1 = 0, *Op2 = 0;
6427         if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
6428           Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6429         if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
6430           Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6431
6432         // We only want to perform this transformation if it will not lead to
6433         // additional code. This is true if either both sides of the select
6434         // fold to a constant (in which case the icmp is replaced with a select
6435         // which will usually simplify) or this is the only user of the
6436         // select (in which case we are trading a select+icmp for a simpler
6437         // select+icmp).
6438         if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
6439           if (!Op1)
6440             Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6441                                       RHSC, I.getName());
6442           if (!Op2)
6443             Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6444                                       RHSC, I.getName());
6445           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6446         }
6447         break;
6448       }
6449       case Instruction::Call:
6450         // If we have (malloc != null), and if the malloc has a single use, we
6451         // can assume it is successful and remove the malloc.
6452         if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6453             isa<ConstantPointerNull>(RHSC)) {
6454           // Need to explicitly erase malloc call here, instead of adding it to
6455           // Worklist, because it won't get DCE'd from the Worklist since
6456           // isInstructionTriviallyDead() returns false for function calls.
6457           // It is OK to replace LHSI/MallocCall with Undef because the 
6458           // instruction that uses it will be erased via Worklist.
6459           if (extractMallocCall(LHSI)) {
6460             LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6461             EraseInstFromFunction(*LHSI);
6462             return ReplaceInstUsesWith(I,
6463                                      ConstantInt::get(Type::getInt1Ty(*Context),
6464                                                       !I.isTrueWhenEqual()));
6465           }
6466           if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6467             if (MallocCall->hasOneUse()) {
6468               MallocCall->replaceAllUsesWith(
6469                                         UndefValue::get(MallocCall->getType()));
6470               EraseInstFromFunction(*MallocCall);
6471               Worklist.Add(LHSI); // The malloc's bitcast use.
6472               return ReplaceInstUsesWith(I,
6473                                      ConstantInt::get(Type::getInt1Ty(*Context),
6474                                                       !I.isTrueWhenEqual()));
6475             }
6476         }
6477         break;
6478       }
6479   }
6480
6481   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6482   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6483     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6484       return NI;
6485   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6486     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6487                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6488       return NI;
6489
6490   // Test to see if the operands of the icmp are casted versions of other
6491   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6492   // now.
6493   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6494     if (isa<PointerType>(Op0->getType()) && 
6495         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6496       // We keep moving the cast from the left operand over to the right
6497       // operand, where it can often be eliminated completely.
6498       Op0 = CI->getOperand(0);
6499
6500       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6501       // so eliminate it as well.
6502       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6503         Op1 = CI2->getOperand(0);
6504
6505       // If Op1 is a constant, we can fold the cast into the constant.
6506       if (Op0->getType() != Op1->getType()) {
6507         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6508           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6509         } else {
6510           // Otherwise, cast the RHS right before the icmp
6511           Op1 = Builder->CreateBitCast(Op1, Op0->getType());
6512         }
6513       }
6514       return new ICmpInst(I.getPredicate(), Op0, Op1);
6515     }
6516   }
6517   
6518   if (isa<CastInst>(Op0)) {
6519     // Handle the special case of: icmp (cast bool to X), <cst>
6520     // This comes up when you have code like
6521     //   int X = A < B;
6522     //   if (X) ...
6523     // For generality, we handle any zero-extension of any operand comparison
6524     // with a constant or another cast from the same type.
6525     if (isa<Constant>(Op1) || isa<CastInst>(Op1))
6526       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6527         return R;
6528   }
6529   
6530   // See if it's the same type of instruction on the left and right.
6531   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6532     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6533       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6534           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6535         switch (Op0I->getOpcode()) {
6536         default: break;
6537         case Instruction::Add:
6538         case Instruction::Sub:
6539         case Instruction::Xor:
6540           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6541             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6542                                 Op1I->getOperand(0));
6543           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6544           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6545             if (CI->getValue().isSignBit()) {
6546               ICmpInst::Predicate Pred = I.isSigned()
6547                                              ? I.getUnsignedPredicate()
6548                                              : I.getSignedPredicate();
6549               return new ICmpInst(Pred, Op0I->getOperand(0),
6550                                   Op1I->getOperand(0));
6551             }
6552             
6553             if (CI->getValue().isMaxSignedValue()) {
6554               ICmpInst::Predicate Pred = I.isSigned()
6555                                              ? I.getUnsignedPredicate()
6556                                              : I.getSignedPredicate();
6557               Pred = I.getSwappedPredicate(Pred);
6558               return new ICmpInst(Pred, Op0I->getOperand(0),
6559                                   Op1I->getOperand(0));
6560             }
6561           }
6562           break;
6563         case Instruction::Mul:
6564           if (!I.isEquality())
6565             break;
6566
6567           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6568             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6569             // Mask = -1 >> count-trailing-zeros(Cst).
6570             if (!CI->isZero() && !CI->isOne()) {
6571               const APInt &AP = CI->getValue();
6572               ConstantInt *Mask = ConstantInt::get(*Context, 
6573                                       APInt::getLowBitsSet(AP.getBitWidth(),
6574                                                            AP.getBitWidth() -
6575                                                       AP.countTrailingZeros()));
6576               Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6577               Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
6578               return new ICmpInst(I.getPredicate(), And1, And2);
6579             }
6580           }
6581           break;
6582         }
6583       }
6584     }
6585   }
6586   
6587   // ~x < ~y --> y < x
6588   { Value *A, *B;
6589     if (match(Op0, m_Not(m_Value(A))) &&
6590         match(Op1, m_Not(m_Value(B))))
6591       return new ICmpInst(I.getPredicate(), B, A);
6592   }
6593   
6594   if (I.isEquality()) {
6595     Value *A, *B, *C, *D;
6596     
6597     // -x == -y --> x == y
6598     if (match(Op0, m_Neg(m_Value(A))) &&
6599         match(Op1, m_Neg(m_Value(B))))
6600       return new ICmpInst(I.getPredicate(), A, B);
6601     
6602     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6603       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6604         Value *OtherVal = A == Op1 ? B : A;
6605         return new ICmpInst(I.getPredicate(), OtherVal,
6606                             Constant::getNullValue(A->getType()));
6607       }
6608
6609       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6610         // A^c1 == C^c2 --> A == C^(c1^c2)
6611         ConstantInt *C1, *C2;
6612         if (match(B, m_ConstantInt(C1)) &&
6613             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6614           Constant *NC = 
6615                    ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6616           Value *Xor = Builder->CreateXor(C, NC, "tmp");
6617           return new ICmpInst(I.getPredicate(), A, Xor);
6618         }
6619         
6620         // A^B == A^D -> B == D
6621         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6622         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6623         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6624         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6625       }
6626     }
6627     
6628     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6629         (A == Op0 || B == Op0)) {
6630       // A == (A^B)  ->  B == 0
6631       Value *OtherVal = A == Op0 ? B : A;
6632       return new ICmpInst(I.getPredicate(), OtherVal,
6633                           Constant::getNullValue(A->getType()));
6634     }
6635
6636     // (A-B) == A  ->  B == 0
6637     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6638       return new ICmpInst(I.getPredicate(), B, 
6639                           Constant::getNullValue(B->getType()));
6640
6641     // A == (A-B)  ->  B == 0
6642     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6643       return new ICmpInst(I.getPredicate(), B,
6644                           Constant::getNullValue(B->getType()));
6645     
6646     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6647     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6648         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6649         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6650       Value *X = 0, *Y = 0, *Z = 0;
6651       
6652       if (A == C) {
6653         X = B; Y = D; Z = A;
6654       } else if (A == D) {
6655         X = B; Y = C; Z = A;
6656       } else if (B == C) {
6657         X = A; Y = D; Z = B;
6658       } else if (B == D) {
6659         X = A; Y = C; Z = B;
6660       }
6661       
6662       if (X) {   // Build (X^Y) & Z
6663         Op1 = Builder->CreateXor(X, Y, "tmp");
6664         Op1 = Builder->CreateAnd(Op1, Z, "tmp");
6665         I.setOperand(0, Op1);
6666         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6667         return &I;
6668       }
6669     }
6670   }
6671   
6672   {
6673     Value *X; ConstantInt *Cst;
6674     // icmp X+Cst, X
6675     if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
6676       return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0);
6677
6678     // icmp X, X+Cst
6679     if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
6680       return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1);
6681   }
6682   return Changed ? &I : 0;
6683 }
6684
6685 /// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
6686 Instruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI,
6687                                             Value *X, ConstantInt *CI,
6688                                             ICmpInst::Predicate Pred,
6689                                             Value *TheAdd) {
6690   // If we have X+0, exit early (simplifying logic below) and let it get folded
6691   // elsewhere.   icmp X+0, X  -> icmp X, X
6692   if (CI->isZero()) {
6693     bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
6694     return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6695   }
6696   
6697   // (X+4) == X -> false.
6698   if (Pred == ICmpInst::ICMP_EQ)
6699     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
6700
6701   // (X+4) != X -> true.
6702   if (Pred == ICmpInst::ICMP_NE)
6703     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
6704
6705   // If this is an instruction (as opposed to constantexpr) get NUW/NSW info.
6706   bool isNUW = false, isNSW = false;
6707   if (BinaryOperator *Add = dyn_cast<BinaryOperator>(TheAdd)) {
6708     isNUW = Add->hasNoUnsignedWrap();
6709     isNSW = Add->hasNoSignedWrap();
6710   }      
6711   
6712   // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
6713   // so the values can never be equal.  Similiarly for all other "or equals"
6714   // operators.
6715   
6716   // (X+1) <u X        --> X >u (MAXUINT-1)        --> X != 255
6717   // (X+2) <u X        --> X >u (MAXUINT-2)        --> X > 253
6718   // (X+MAXUINT) <u X  --> X >u (MAXUINT-MAXUINT)  --> X != 0
6719   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
6720     // If this is an NUW add, then this is always false.
6721     if (isNUW)
6722       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext())); 
6723     
6724     Value *R = ConstantExpr::getSub(ConstantInt::get(CI->getType(), -1ULL), CI);
6725     return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
6726   }
6727   
6728   // (X+1) >u X        --> X <u (0-1)        --> X != 255
6729   // (X+2) >u X        --> X <u (0-2)        --> X <u 254
6730   // (X+MAXUINT) >u X  --> X <u (0-MAXUINT)  --> X <u 1  --> X == 0
6731   if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
6732     // If this is an NUW add, then this is always true.
6733     if (isNUW)
6734       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext())); 
6735     return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
6736   }
6737   
6738   unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
6739   ConstantInt *SMax = ConstantInt::get(X->getContext(),
6740                                        APInt::getSignedMaxValue(BitWidth));
6741
6742   // (X+ 1) <s X       --> X >s (MAXSINT-1)          --> X == 127
6743   // (X+ 2) <s X       --> X >s (MAXSINT-2)          --> X >s 125
6744   // (X+MAXSINT) <s X  --> X >s (MAXSINT-MAXSINT)    --> X >s 0
6745   // (X+MINSINT) <s X  --> X >s (MAXSINT-MINSINT)    --> X >s -1
6746   // (X+ -2) <s X      --> X >s (MAXSINT- -2)        --> X >s 126
6747   // (X+ -1) <s X      --> X >s (MAXSINT- -1)        --> X != 127
6748   if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
6749     // If this is an NSW add, then we have two cases: if the constant is
6750     // positive, then this is always false, if negative, this is always true.
6751     if (isNSW) {
6752       bool isTrue = CI->getValue().isNegative();
6753       return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6754     }
6755     
6756     return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
6757   }
6758   
6759   // (X+ 1) >s X       --> X <s (MAXSINT-(1-1))       --> X != 127
6760   // (X+ 2) >s X       --> X <s (MAXSINT-(2-1))       --> X <s 126
6761   // (X+MAXSINT) >s X  --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
6762   // (X+MINSINT) >s X  --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
6763   // (X+ -2) >s X      --> X <s (MAXSINT-(-2-1))      --> X <s -126
6764   // (X+ -1) >s X      --> X <s (MAXSINT-(-1-1))      --> X == -128
6765   
6766   // If this is an NSW add, then we have two cases: if the constant is
6767   // positive, then this is always true, if negative, this is always false.
6768   if (isNSW) {
6769     bool isTrue = !CI->getValue().isNegative();
6770     return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6771   }
6772   
6773   assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
6774   Constant *C = ConstantInt::get(X->getContext(), CI->getValue()-1);
6775   return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
6776 }
6777
6778 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6779 /// and CmpRHS are both known to be integer constants.
6780 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6781                                           ConstantInt *DivRHS) {
6782   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6783   const APInt &CmpRHSV = CmpRHS->getValue();
6784   
6785   // FIXME: If the operand types don't match the type of the divide 
6786   // then don't attempt this transform. The code below doesn't have the
6787   // logic to deal with a signed divide and an unsigned compare (and
6788   // vice versa). This is because (x /s C1) <s C2  produces different 
6789   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6790   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6791   // work. :(  The if statement below tests that condition and bails 
6792   // if it finds it. 
6793   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6794   if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
6795     return 0;
6796   if (DivRHS->isZero())
6797     return 0; // The ProdOV computation fails on divide by zero.
6798   if (DivIsSigned && DivRHS->isAllOnesValue())
6799     return 0; // The overflow computation also screws up here
6800   if (DivRHS->isOne())
6801     return 0; // Not worth bothering, and eliminates some funny cases
6802               // with INT_MIN.
6803
6804   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6805   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6806   // C2 (CI). By solving for X we can turn this into a range check 
6807   // instead of computing a divide. 
6808   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6809
6810   // Determine if the product overflows by seeing if the product is
6811   // not equal to the divide. Make sure we do the same kind of divide
6812   // as in the LHS instruction that we're folding. 
6813   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6814                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6815
6816   // Get the ICmp opcode
6817   ICmpInst::Predicate Pred = ICI.getPredicate();
6818
6819   // Figure out the interval that is being checked.  For example, a comparison
6820   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6821   // Compute this interval based on the constants involved and the signedness of
6822   // the compare/divide.  This computes a half-open interval, keeping track of
6823   // whether either value in the interval overflows.  After analysis each
6824   // overflow variable is set to 0 if it's corresponding bound variable is valid
6825   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6826   int LoOverflow = 0, HiOverflow = 0;
6827   Constant *LoBound = 0, *HiBound = 0;
6828   
6829   if (!DivIsSigned) {  // udiv
6830     // e.g. X/5 op 3  --> [15, 20)
6831     LoBound = Prod;
6832     HiOverflow = LoOverflow = ProdOV;
6833     if (!HiOverflow)
6834       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6835   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6836     if (CmpRHSV == 0) {       // (X / pos) op 0
6837       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6838       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6839       HiBound = DivRHS;
6840     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6841       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6842       HiOverflow = LoOverflow = ProdOV;
6843       if (!HiOverflow)
6844         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6845     } else {                       // (X / pos) op neg
6846       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6847       HiBound = AddOne(Prod);
6848       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6849       if (!LoOverflow) {
6850         ConstantInt* DivNeg =
6851                          cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6852         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6853                                      true) ? -1 : 0;
6854        }
6855     }
6856   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6857     if (CmpRHSV == 0) {       // (X / neg) op 0
6858       // e.g. X/-5 op 0  --> [-4, 5)
6859       LoBound = AddOne(DivRHS);
6860       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6861       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6862         HiOverflow = 1;            // [INTMIN+1, overflow)
6863         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6864       }
6865     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6866       // e.g. X/-5 op 3  --> [-19, -14)
6867       HiBound = AddOne(Prod);
6868       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6869       if (!LoOverflow)
6870         LoOverflow = AddWithOverflow(LoBound, HiBound,
6871                                      DivRHS, Context, true) ? -1 : 0;
6872     } else {                       // (X / neg) op neg
6873       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6874       LoOverflow = HiOverflow = ProdOV;
6875       if (!HiOverflow)
6876         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6877     }
6878     
6879     // Dividing by a negative swaps the condition.  LT <-> GT
6880     Pred = ICmpInst::getSwappedPredicate(Pred);
6881   }
6882
6883   Value *X = DivI->getOperand(0);
6884   switch (Pred) {
6885   default: llvm_unreachable("Unhandled icmp opcode!");
6886   case ICmpInst::ICMP_EQ:
6887     if (LoOverflow && HiOverflow)
6888       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6889     else if (HiOverflow)
6890       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6891                           ICmpInst::ICMP_UGE, X, LoBound);
6892     else if (LoOverflow)
6893       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6894                           ICmpInst::ICMP_ULT, X, HiBound);
6895     else
6896       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6897   case ICmpInst::ICMP_NE:
6898     if (LoOverflow && HiOverflow)
6899       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6900     else if (HiOverflow)
6901       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6902                           ICmpInst::ICMP_ULT, X, LoBound);
6903     else if (LoOverflow)
6904       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6905                           ICmpInst::ICMP_UGE, X, HiBound);
6906     else
6907       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6908   case ICmpInst::ICMP_ULT:
6909   case ICmpInst::ICMP_SLT:
6910     if (LoOverflow == +1)   // Low bound is greater than input range.
6911       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6912     if (LoOverflow == -1)   // Low bound is less than input range.
6913       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6914     return new ICmpInst(Pred, X, LoBound);
6915   case ICmpInst::ICMP_UGT:
6916   case ICmpInst::ICMP_SGT:
6917     if (HiOverflow == +1)       // High bound greater than input range.
6918       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6919     else if (HiOverflow == -1)  // High bound less than input range.
6920       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6921     if (Pred == ICmpInst::ICMP_UGT)
6922       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6923     else
6924       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6925   }
6926 }
6927
6928
6929 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6930 ///
6931 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6932                                                           Instruction *LHSI,
6933                                                           ConstantInt *RHS) {
6934   const APInt &RHSV = RHS->getValue();
6935   
6936   switch (LHSI->getOpcode()) {
6937   case Instruction::Trunc:
6938     if (ICI.isEquality() && LHSI->hasOneUse()) {
6939       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6940       // of the high bits truncated out of x are known.
6941       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6942              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6943       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6944       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6945       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6946       
6947       // If all the high bits are known, we can do this xform.
6948       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6949         // Pull in the high bits from known-ones set.
6950         APInt NewRHS(RHS->getValue());
6951         NewRHS.zext(SrcBits);
6952         NewRHS |= KnownOne;
6953         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6954                             ConstantInt::get(*Context, NewRHS));
6955       }
6956     }
6957     break;
6958       
6959   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6960     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6961       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6962       // fold the xor.
6963       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6964           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6965         Value *CompareVal = LHSI->getOperand(0);
6966         
6967         // If the sign bit of the XorCST is not set, there is no change to
6968         // the operation, just stop using the Xor.
6969         if (!XorCST->getValue().isNegative()) {
6970           ICI.setOperand(0, CompareVal);
6971           Worklist.Add(LHSI);
6972           return &ICI;
6973         }
6974         
6975         // Was the old condition true if the operand is positive?
6976         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6977         
6978         // If so, the new one isn't.
6979         isTrueIfPositive ^= true;
6980         
6981         if (isTrueIfPositive)
6982           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
6983                               SubOne(RHS));
6984         else
6985           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
6986                               AddOne(RHS));
6987       }
6988
6989       if (LHSI->hasOneUse()) {
6990         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6991         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6992           const APInt &SignBit = XorCST->getValue();
6993           ICmpInst::Predicate Pred = ICI.isSigned()
6994                                          ? ICI.getUnsignedPredicate()
6995                                          : ICI.getSignedPredicate();
6996           return new ICmpInst(Pred, LHSI->getOperand(0),
6997                               ConstantInt::get(*Context, RHSV ^ SignBit));
6998         }
6999
7000         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
7001         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
7002           const APInt &NotSignBit = XorCST->getValue();
7003           ICmpInst::Predicate Pred = ICI.isSigned()
7004                                          ? ICI.getUnsignedPredicate()
7005                                          : ICI.getSignedPredicate();
7006           Pred = ICI.getSwappedPredicate(Pred);
7007           return new ICmpInst(Pred, LHSI->getOperand(0),
7008                               ConstantInt::get(*Context, RHSV ^ NotSignBit));
7009         }
7010       }
7011     }
7012     break;
7013   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
7014     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
7015         LHSI->getOperand(0)->hasOneUse()) {
7016       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
7017       
7018       // If the LHS is an AND of a truncating cast, we can widen the
7019       // and/compare to be the input width without changing the value
7020       // produced, eliminating a cast.
7021       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
7022         // We can do this transformation if either the AND constant does not
7023         // have its sign bit set or if it is an equality comparison. 
7024         // Extending a relational comparison when we're checking the sign
7025         // bit would not work.
7026         if (Cast->hasOneUse() &&
7027             (ICI.isEquality() ||
7028              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
7029           uint32_t BitWidth = 
7030             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
7031           APInt NewCST = AndCST->getValue();
7032           NewCST.zext(BitWidth);
7033           APInt NewCI = RHSV;
7034           NewCI.zext(BitWidth);
7035           Value *NewAnd = 
7036             Builder->CreateAnd(Cast->getOperand(0),
7037                            ConstantInt::get(*Context, NewCST), LHSI->getName());
7038           return new ICmpInst(ICI.getPredicate(), NewAnd,
7039                               ConstantInt::get(*Context, NewCI));
7040         }
7041       }
7042       
7043       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
7044       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
7045       // happens a LOT in code produced by the C front-end, for bitfield
7046       // access.
7047       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
7048       if (Shift && !Shift->isShift())
7049         Shift = 0;
7050       
7051       ConstantInt *ShAmt;
7052       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
7053       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
7054       const Type *AndTy = AndCST->getType();          // Type of the and.
7055       
7056       // We can fold this as long as we can't shift unknown bits
7057       // into the mask.  This can only happen with signed shift
7058       // rights, as they sign-extend.
7059       if (ShAmt) {
7060         bool CanFold = Shift->isLogicalShift();
7061         if (!CanFold) {
7062           // To test for the bad case of the signed shr, see if any
7063           // of the bits shifted in could be tested after the mask.
7064           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
7065           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
7066           
7067           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
7068           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
7069                AndCST->getValue()) == 0)
7070             CanFold = true;
7071         }
7072         
7073         if (CanFold) {
7074           Constant *NewCst;
7075           if (Shift->getOpcode() == Instruction::Shl)
7076             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
7077           else
7078             NewCst = ConstantExpr::getShl(RHS, ShAmt);
7079           
7080           // Check to see if we are shifting out any of the bits being
7081           // compared.
7082           if (ConstantExpr::get(Shift->getOpcode(),
7083                                        NewCst, ShAmt) != RHS) {
7084             // If we shifted bits out, the fold is not going to work out.
7085             // As a special case, check to see if this means that the
7086             // result is always true or false now.
7087             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7088               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7089             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7090               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7091           } else {
7092             ICI.setOperand(1, NewCst);
7093             Constant *NewAndCST;
7094             if (Shift->getOpcode() == Instruction::Shl)
7095               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
7096             else
7097               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
7098             LHSI->setOperand(1, NewAndCST);
7099             LHSI->setOperand(0, Shift->getOperand(0));
7100             Worklist.Add(Shift); // Shift is dead.
7101             return &ICI;
7102           }
7103         }
7104       }
7105       
7106       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
7107       // preferable because it allows the C<<Y expression to be hoisted out
7108       // of a loop if Y is invariant and X is not.
7109       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
7110           ICI.isEquality() && !Shift->isArithmeticShift() &&
7111           !isa<Constant>(Shift->getOperand(0))) {
7112         // Compute C << Y.
7113         Value *NS;
7114         if (Shift->getOpcode() == Instruction::LShr) {
7115           NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
7116         } else {
7117           // Insert a logical shift.
7118           NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
7119         }
7120         
7121         // Compute X & (C << Y).
7122         Value *NewAnd = 
7123           Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
7124         
7125         ICI.setOperand(0, NewAnd);
7126         return &ICI;
7127       }
7128     }
7129     break;
7130     
7131   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
7132     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7133     if (!ShAmt) break;
7134     
7135     uint32_t TypeBits = RHSV.getBitWidth();
7136     
7137     // Check that the shift amount is in range.  If not, don't perform
7138     // undefined shifts.  When the shift is visited it will be
7139     // simplified.
7140     if (ShAmt->uge(TypeBits))
7141       break;
7142     
7143     if (ICI.isEquality()) {
7144       // If we are comparing against bits always shifted out, the
7145       // comparison cannot succeed.
7146       Constant *Comp =
7147         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
7148                                                                  ShAmt);
7149       if (Comp != RHS) {// Comparing against a bit that we know is zero.
7150         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7151         Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
7152         return ReplaceInstUsesWith(ICI, Cst);
7153       }
7154       
7155       if (LHSI->hasOneUse()) {
7156         // Otherwise strength reduce the shift into an and.
7157         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
7158         Constant *Mask =
7159           ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits, 
7160                                                        TypeBits-ShAmtVal));
7161         
7162         Value *And =
7163           Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
7164         return new ICmpInst(ICI.getPredicate(), And,
7165                             ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
7166       }
7167     }
7168     
7169     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
7170     bool TrueIfSigned = false;
7171     if (LHSI->hasOneUse() &&
7172         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
7173       // (X << 31) <s 0  --> (X&1) != 0
7174       Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
7175                                            (TypeBits-ShAmt->getZExtValue()-1));
7176       Value *And =
7177         Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
7178       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
7179                           And, Constant::getNullValue(And->getType()));
7180     }
7181     break;
7182   }
7183     
7184   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
7185   case Instruction::AShr: {
7186     // Only handle equality comparisons of shift-by-constant.
7187     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7188     if (!ShAmt || !ICI.isEquality()) break;
7189
7190     // Check that the shift amount is in range.  If not, don't perform
7191     // undefined shifts.  When the shift is visited it will be
7192     // simplified.
7193     uint32_t TypeBits = RHSV.getBitWidth();
7194     if (ShAmt->uge(TypeBits))
7195       break;
7196     
7197     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
7198       
7199     // If we are comparing against bits always shifted out, the
7200     // comparison cannot succeed.
7201     APInt Comp = RHSV << ShAmtVal;
7202     if (LHSI->getOpcode() == Instruction::LShr)
7203       Comp = Comp.lshr(ShAmtVal);
7204     else
7205       Comp = Comp.ashr(ShAmtVal);
7206     
7207     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7208       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7209       Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
7210       return ReplaceInstUsesWith(ICI, Cst);
7211     }
7212     
7213     // Otherwise, check to see if the bits shifted out are known to be zero.
7214     // If so, we can compare against the unshifted value:
7215     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
7216     if (LHSI->hasOneUse() &&
7217         MaskedValueIsZero(LHSI->getOperand(0), 
7218                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
7219       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
7220                           ConstantExpr::getShl(RHS, ShAmt));
7221     }
7222       
7223     if (LHSI->hasOneUse()) {
7224       // Otherwise strength reduce the shift into an and.
7225       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7226       Constant *Mask = ConstantInt::get(*Context, Val);
7227       
7228       Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7229                                       Mask, LHSI->getName()+".mask");
7230       return new ICmpInst(ICI.getPredicate(), And,
7231                           ConstantExpr::getShl(RHS, ShAmt));
7232     }
7233     break;
7234   }
7235     
7236   case Instruction::SDiv:
7237   case Instruction::UDiv:
7238     // Fold: icmp pred ([us]div X, C1), C2 -> range test
7239     // Fold this div into the comparison, producing a range check. 
7240     // Determine, based on the divide type, what the range is being 
7241     // checked.  If there is an overflow on the low or high side, remember 
7242     // it, otherwise compute the range [low, hi) bounding the new value.
7243     // See: InsertRangeTest above for the kinds of replacements possible.
7244     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7245       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7246                                           DivRHS))
7247         return R;
7248     break;
7249
7250   case Instruction::Add:
7251     // Fold: icmp pred (add X, C1), C2
7252     if (!ICI.isEquality()) {
7253       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7254       if (!LHSC) break;
7255       const APInt &LHSV = LHSC->getValue();
7256
7257       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7258                             .subtract(LHSV);
7259
7260       if (ICI.isSigned()) {
7261         if (CR.getLower().isSignBit()) {
7262           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7263                               ConstantInt::get(*Context, CR.getUpper()));
7264         } else if (CR.getUpper().isSignBit()) {
7265           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7266                               ConstantInt::get(*Context, CR.getLower()));
7267         }
7268       } else {
7269         if (CR.getLower().isMinValue()) {
7270           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7271                               ConstantInt::get(*Context, CR.getUpper()));
7272         } else if (CR.getUpper().isMinValue()) {
7273           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7274                               ConstantInt::get(*Context, CR.getLower()));
7275         }
7276       }
7277     }
7278     break;
7279   }
7280   
7281   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7282   if (ICI.isEquality()) {
7283     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7284     
7285     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7286     // the second operand is a constant, simplify a bit.
7287     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7288       switch (BO->getOpcode()) {
7289       case Instruction::SRem:
7290         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7291         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7292           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7293           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7294             Value *NewRem =
7295               Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7296                                   BO->getName());
7297             return new ICmpInst(ICI.getPredicate(), NewRem,
7298                                 Constant::getNullValue(BO->getType()));
7299           }
7300         }
7301         break;
7302       case Instruction::Add:
7303         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7304         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7305           if (BO->hasOneUse())
7306             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7307                                 ConstantExpr::getSub(RHS, BOp1C));
7308         } else if (RHSV == 0) {
7309           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7310           // efficiently invertible, or if the add has just this one use.
7311           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7312           
7313           if (Value *NegVal = dyn_castNegVal(BOp1))
7314             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
7315           else if (Value *NegVal = dyn_castNegVal(BOp0))
7316             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
7317           else if (BO->hasOneUse()) {
7318             Value *Neg = Builder->CreateNeg(BOp1);
7319             Neg->takeName(BO);
7320             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
7321           }
7322         }
7323         break;
7324       case Instruction::Xor:
7325         // For the xor case, we can xor two constants together, eliminating
7326         // the explicit xor.
7327         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7328           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
7329                               ConstantExpr::getXor(RHS, BOC));
7330         
7331         // FALLTHROUGH
7332       case Instruction::Sub:
7333         // Replace (([sub|xor] A, B) != 0) with (A != B)
7334         if (RHSV == 0)
7335           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7336                               BO->getOperand(1));
7337         break;
7338         
7339       case Instruction::Or:
7340         // If bits are being or'd in that are not present in the constant we
7341         // are comparing against, then the comparison could never succeed!
7342         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7343           Constant *NotCI = ConstantExpr::getNot(RHS);
7344           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7345             return ReplaceInstUsesWith(ICI,
7346                                        ConstantInt::get(Type::getInt1Ty(*Context), 
7347                                        isICMP_NE));
7348         }
7349         break;
7350         
7351       case Instruction::And:
7352         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7353           // If bits are being compared against that are and'd out, then the
7354           // comparison can never succeed!
7355           if ((RHSV & ~BOC->getValue()) != 0)
7356             return ReplaceInstUsesWith(ICI,
7357                                        ConstantInt::get(Type::getInt1Ty(*Context),
7358                                        isICMP_NE));
7359           
7360           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7361           if (RHS == BOC && RHSV.isPowerOf2())
7362             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7363                                 ICmpInst::ICMP_NE, LHSI,
7364                                 Constant::getNullValue(RHS->getType()));
7365           
7366           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7367           if (BOC->getValue().isSignBit()) {
7368             Value *X = BO->getOperand(0);
7369             Constant *Zero = Constant::getNullValue(X->getType());
7370             ICmpInst::Predicate pred = isICMP_NE ? 
7371               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7372             return new ICmpInst(pred, X, Zero);
7373           }
7374           
7375           // ((X & ~7) == 0) --> X < 8
7376           if (RHSV == 0 && isHighOnes(BOC)) {
7377             Value *X = BO->getOperand(0);
7378             Constant *NegX = ConstantExpr::getNeg(BOC);
7379             ICmpInst::Predicate pred = isICMP_NE ? 
7380               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7381             return new ICmpInst(pred, X, NegX);
7382           }
7383         }
7384       default: break;
7385       }
7386     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7387       // Handle icmp {eq|ne} <intrinsic>, intcst.
7388       if (II->getIntrinsicID() == Intrinsic::bswap) {
7389         Worklist.Add(II);
7390         ICI.setOperand(0, II->getOperand(1));
7391         ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7392         return &ICI;
7393       }
7394     }
7395   }
7396   return 0;
7397 }
7398
7399 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7400 /// We only handle extending casts so far.
7401 ///
7402 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7403   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7404   Value *LHSCIOp        = LHSCI->getOperand(0);
7405   const Type *SrcTy     = LHSCIOp->getType();
7406   const Type *DestTy    = LHSCI->getType();
7407   Value *RHSCIOp;
7408
7409   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7410   // integer type is the same size as the pointer type.
7411   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7412       TD->getPointerSizeInBits() ==
7413          cast<IntegerType>(DestTy)->getBitWidth()) {
7414     Value *RHSOp = 0;
7415     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7416       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7417     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7418       RHSOp = RHSC->getOperand(0);
7419       // If the pointer types don't match, insert a bitcast.
7420       if (LHSCIOp->getType() != RHSOp->getType())
7421         RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
7422     }
7423
7424     if (RHSOp)
7425       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7426   }
7427   
7428   // The code below only handles extension cast instructions, so far.
7429   // Enforce this.
7430   if (LHSCI->getOpcode() != Instruction::ZExt &&
7431       LHSCI->getOpcode() != Instruction::SExt)
7432     return 0;
7433
7434   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7435   bool isSignedCmp = ICI.isSigned();
7436
7437   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7438     // Not an extension from the same type?
7439     RHSCIOp = CI->getOperand(0);
7440     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7441       return 0;
7442     
7443     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7444     // and the other is a zext), then we can't handle this.
7445     if (CI->getOpcode() != LHSCI->getOpcode())
7446       return 0;
7447
7448     // Deal with equality cases early.
7449     if (ICI.isEquality())
7450       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7451
7452     // A signed comparison of sign extended values simplifies into a
7453     // signed comparison.
7454     if (isSignedCmp && isSignedExt)
7455       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7456
7457     // The other three cases all fold into an unsigned comparison.
7458     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7459   }
7460
7461   // If we aren't dealing with a constant on the RHS, exit early
7462   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7463   if (!CI)
7464     return 0;
7465
7466   // Compute the constant that would happen if we truncated to SrcTy then
7467   // reextended to DestTy.
7468   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7469   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7470                                                 Res1, DestTy);
7471
7472   // If the re-extended constant didn't change...
7473   if (Res2 == CI) {
7474     // Deal with equality cases early.
7475     if (ICI.isEquality())
7476       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7477
7478     // A signed comparison of sign extended values simplifies into a
7479     // signed comparison.
7480     if (isSignedExt && isSignedCmp)
7481       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7482
7483     // The other three cases all fold into an unsigned comparison.
7484     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
7485   }
7486
7487   // The re-extended constant changed so the constant cannot be represented 
7488   // in the shorter type. Consequently, we cannot emit a simple comparison.
7489
7490   // First, handle some easy cases. We know the result cannot be equal at this
7491   // point so handle the ICI.isEquality() cases
7492   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7493     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7494   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7495     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7496
7497   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7498   // should have been folded away previously and not enter in here.
7499   Value *Result;
7500   if (isSignedCmp) {
7501     // We're performing a signed comparison.
7502     if (cast<ConstantInt>(CI)->getValue().isNegative())
7503       Result = ConstantInt::getFalse(*Context);          // X < (small) --> false
7504     else
7505       Result = ConstantInt::getTrue(*Context);           // X < (large) --> true
7506   } else {
7507     // We're performing an unsigned comparison.
7508     if (isSignedExt) {
7509       // We're performing an unsigned comp with a sign extended value.
7510       // This is true if the input is >= 0. [aka >s -1]
7511       Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7512       Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
7513     } else {
7514       // Unsigned extend & unsigned compare -> always true.
7515       Result = ConstantInt::getTrue(*Context);
7516     }
7517   }
7518
7519   // Finally, return the value computed.
7520   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7521       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7522     return ReplaceInstUsesWith(ICI, Result);
7523
7524   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7525           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7526          "ICmp should be folded!");
7527   if (Constant *CI = dyn_cast<Constant>(Result))
7528     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7529   return BinaryOperator::CreateNot(Result);
7530 }
7531
7532 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7533   return commonShiftTransforms(I);
7534 }
7535
7536 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7537   return commonShiftTransforms(I);
7538 }
7539
7540 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7541   if (Instruction *R = commonShiftTransforms(I))
7542     return R;
7543   
7544   Value *Op0 = I.getOperand(0);
7545   
7546   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7547   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7548     if (CSI->isAllOnesValue())
7549       return ReplaceInstUsesWith(I, CSI);
7550
7551   // See if we can turn a signed shr into an unsigned shr.
7552   if (MaskedValueIsZero(Op0,
7553                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7554     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7555
7556   // Arithmetic shifting an all-sign-bit value is a no-op.
7557   unsigned NumSignBits = ComputeNumSignBits(Op0);
7558   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7559     return ReplaceInstUsesWith(I, Op0);
7560
7561   return 0;
7562 }
7563
7564 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7565   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7566   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7567
7568   // shl X, 0 == X and shr X, 0 == X
7569   // shl 0, X == 0 and shr 0, X == 0
7570   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7571       Op0 == Constant::getNullValue(Op0->getType()))
7572     return ReplaceInstUsesWith(I, Op0);
7573   
7574   if (isa<UndefValue>(Op0)) {            
7575     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7576       return ReplaceInstUsesWith(I, Op0);
7577     else                                    // undef << X -> 0, undef >>u X -> 0
7578       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7579   }
7580   if (isa<UndefValue>(Op1)) {
7581     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7582       return ReplaceInstUsesWith(I, Op0);          
7583     else                                     // X << undef, X >>u undef -> 0
7584       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7585   }
7586
7587   // See if we can fold away this shift.
7588   if (SimplifyDemandedInstructionBits(I))
7589     return &I;
7590
7591   // Try to fold constant and into select arguments.
7592   if (isa<Constant>(Op0))
7593     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7594       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7595         return R;
7596
7597   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7598     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7599       return Res;
7600   return 0;
7601 }
7602
7603 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7604                                                BinaryOperator &I) {
7605   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7606
7607   // See if we can simplify any instructions used by the instruction whose sole 
7608   // purpose is to compute bits we don't care about.
7609   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7610   
7611   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7612   // a signed shift.
7613   //
7614   if (Op1->uge(TypeBits)) {
7615     if (I.getOpcode() != Instruction::AShr)
7616       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7617     else {
7618       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7619       return &I;
7620     }
7621   }
7622   
7623   // ((X*C1) << C2) == (X * (C1 << C2))
7624   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7625     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7626       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7627         return BinaryOperator::CreateMul(BO->getOperand(0),
7628                                         ConstantExpr::getShl(BOOp, Op1));
7629   
7630   // Try to fold constant and into select arguments.
7631   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7632     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7633       return R;
7634   if (isa<PHINode>(Op0))
7635     if (Instruction *NV = FoldOpIntoPhi(I))
7636       return NV;
7637   
7638   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7639   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7640     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7641     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7642     // place.  Don't try to do this transformation in this case.  Also, we
7643     // require that the input operand is a shift-by-constant so that we have
7644     // confidence that the shifts will get folded together.  We could do this
7645     // xform in more cases, but it is unlikely to be profitable.
7646     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7647         isa<ConstantInt>(TrOp->getOperand(1))) {
7648       // Okay, we'll do this xform.  Make the shift of shift.
7649       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7650       // (shift2 (shift1 & 0x00FF), c2)
7651       Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
7652
7653       // For logical shifts, the truncation has the effect of making the high
7654       // part of the register be zeros.  Emulate this by inserting an AND to
7655       // clear the top bits as needed.  This 'and' will usually be zapped by
7656       // other xforms later if dead.
7657       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7658       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7659       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7660       
7661       // The mask we constructed says what the trunc would do if occurring
7662       // between the shifts.  We want to know the effect *after* the second
7663       // shift.  We know that it is a logical shift by a constant, so adjust the
7664       // mask as appropriate.
7665       if (I.getOpcode() == Instruction::Shl)
7666         MaskV <<= Op1->getZExtValue();
7667       else {
7668         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7669         MaskV = MaskV.lshr(Op1->getZExtValue());
7670       }
7671
7672       // shift1 & 0x00FF
7673       Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7674                                       TI->getName());
7675
7676       // Return the value truncated to the interesting size.
7677       return new TruncInst(And, I.getType());
7678     }
7679   }
7680   
7681   if (Op0->hasOneUse()) {
7682     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7683       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7684       Value *V1, *V2;
7685       ConstantInt *CC;
7686       switch (Op0BO->getOpcode()) {
7687         default: break;
7688         case Instruction::Add:
7689         case Instruction::And:
7690         case Instruction::Or:
7691         case Instruction::Xor: {
7692           // These operators commute.
7693           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7694           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7695               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7696                     m_Specific(Op1)))) {
7697             Value *YS =         // (Y << C)
7698               Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7699             // (X + (Y << C))
7700             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7701                                             Op0BO->getOperand(1)->getName());
7702             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7703             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7704                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7705           }
7706           
7707           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7708           Value *Op0BOOp1 = Op0BO->getOperand(1);
7709           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7710               match(Op0BOOp1, 
7711                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7712                           m_ConstantInt(CC))) &&
7713               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7714             Value *YS =   // (Y << C)
7715               Builder->CreateShl(Op0BO->getOperand(0), Op1,
7716                                            Op0BO->getName());
7717             // X & (CC << C)
7718             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7719                                            V1->getName()+".mask");
7720             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7721           }
7722         }
7723           
7724         // FALL THROUGH.
7725         case Instruction::Sub: {
7726           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7727           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7728               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7729                     m_Specific(Op1)))) {
7730             Value *YS =  // (Y << C)
7731               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7732             // (X + (Y << C))
7733             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7734                                             Op0BO->getOperand(0)->getName());
7735             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7736             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7737                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7738           }
7739           
7740           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7741           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7742               match(Op0BO->getOperand(0),
7743                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7744                           m_ConstantInt(CC))) && V2 == Op1 &&
7745               cast<BinaryOperator>(Op0BO->getOperand(0))
7746                   ->getOperand(0)->hasOneUse()) {
7747             Value *YS = // (Y << C)
7748               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7749             // X & (CC << C)
7750             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7751                                            V1->getName()+".mask");
7752             
7753             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7754           }
7755           
7756           break;
7757         }
7758       }
7759       
7760       
7761       // If the operand is an bitwise operator with a constant RHS, and the
7762       // shift is the only use, we can pull it out of the shift.
7763       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7764         bool isValid = true;     // Valid only for And, Or, Xor
7765         bool highBitSet = false; // Transform if high bit of constant set?
7766         
7767         switch (Op0BO->getOpcode()) {
7768           default: isValid = false; break;   // Do not perform transform!
7769           case Instruction::Add:
7770             isValid = isLeftShift;
7771             break;
7772           case Instruction::Or:
7773           case Instruction::Xor:
7774             highBitSet = false;
7775             break;
7776           case Instruction::And:
7777             highBitSet = true;
7778             break;
7779         }
7780         
7781         // If this is a signed shift right, and the high bit is modified
7782         // by the logical operation, do not perform the transformation.
7783         // The highBitSet boolean indicates the value of the high bit of
7784         // the constant which would cause it to be modified for this
7785         // operation.
7786         //
7787         if (isValid && I.getOpcode() == Instruction::AShr)
7788           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7789         
7790         if (isValid) {
7791           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7792           
7793           Value *NewShift =
7794             Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
7795           NewShift->takeName(Op0BO);
7796           
7797           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7798                                         NewRHS);
7799         }
7800       }
7801     }
7802   }
7803   
7804   // Find out if this is a shift of a shift by a constant.
7805   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7806   if (ShiftOp && !ShiftOp->isShift())
7807     ShiftOp = 0;
7808   
7809   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7810     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7811     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7812     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7813     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7814     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7815     Value *X = ShiftOp->getOperand(0);
7816     
7817     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7818     
7819     const IntegerType *Ty = cast<IntegerType>(I.getType());
7820     
7821     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7822     if (I.getOpcode() == ShiftOp->getOpcode()) {
7823       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7824       // saturates.
7825       if (AmtSum >= TypeBits) {
7826         if (I.getOpcode() != Instruction::AShr)
7827           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7828         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7829       }
7830       
7831       return BinaryOperator::Create(I.getOpcode(), X,
7832                                     ConstantInt::get(Ty, AmtSum));
7833     }
7834     
7835     if (ShiftOp->getOpcode() == Instruction::LShr &&
7836         I.getOpcode() == Instruction::AShr) {
7837       if (AmtSum >= TypeBits)
7838         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7839       
7840       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7841       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7842     }
7843     
7844     if (ShiftOp->getOpcode() == Instruction::AShr &&
7845         I.getOpcode() == Instruction::LShr) {
7846       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7847       if (AmtSum >= TypeBits)
7848         AmtSum = TypeBits-1;
7849       
7850       Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7851
7852       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7853       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7854     }
7855     
7856     // Okay, if we get here, one shift must be left, and the other shift must be
7857     // right.  See if the amounts are equal.
7858     if (ShiftAmt1 == ShiftAmt2) {
7859       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7860       if (I.getOpcode() == Instruction::Shl) {
7861         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7862         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7863       }
7864       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7865       if (I.getOpcode() == Instruction::LShr) {
7866         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7867         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7868       }
7869       // We can simplify ((X << C) >>s C) into a trunc + sext.
7870       // NOTE: we could do this for any C, but that would make 'unusual' integer
7871       // types.  For now, just stick to ones well-supported by the code
7872       // generators.
7873       const Type *SExtType = 0;
7874       switch (Ty->getBitWidth() - ShiftAmt1) {
7875       case 1  :
7876       case 8  :
7877       case 16 :
7878       case 32 :
7879       case 64 :
7880       case 128:
7881         SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
7882         break;
7883       default: break;
7884       }
7885       if (SExtType)
7886         return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
7887       // Otherwise, we can't handle it yet.
7888     } else if (ShiftAmt1 < ShiftAmt2) {
7889       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7890       
7891       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7892       if (I.getOpcode() == Instruction::Shl) {
7893         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7894                ShiftOp->getOpcode() == Instruction::AShr);
7895         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7896         
7897         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7898         return BinaryOperator::CreateAnd(Shift,
7899                                          ConstantInt::get(*Context, Mask));
7900       }
7901       
7902       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7903       if (I.getOpcode() == Instruction::LShr) {
7904         assert(ShiftOp->getOpcode() == Instruction::Shl);
7905         Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7906         
7907         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7908         return BinaryOperator::CreateAnd(Shift,
7909                                          ConstantInt::get(*Context, Mask));
7910       }
7911       
7912       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7913     } else {
7914       assert(ShiftAmt2 < ShiftAmt1);
7915       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7916
7917       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7918       if (I.getOpcode() == Instruction::Shl) {
7919         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7920                ShiftOp->getOpcode() == Instruction::AShr);
7921         Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7922                                             ConstantInt::get(Ty, ShiftDiff));
7923         
7924         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7925         return BinaryOperator::CreateAnd(Shift,
7926                                          ConstantInt::get(*Context, Mask));
7927       }
7928       
7929       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7930       if (I.getOpcode() == Instruction::LShr) {
7931         assert(ShiftOp->getOpcode() == Instruction::Shl);
7932         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7933         
7934         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7935         return BinaryOperator::CreateAnd(Shift,
7936                                          ConstantInt::get(*Context, Mask));
7937       }
7938       
7939       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7940     }
7941   }
7942   return 0;
7943 }
7944
7945
7946 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7947 /// expression.  If so, decompose it, returning some value X, such that Val is
7948 /// X*Scale+Offset.
7949 ///
7950 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7951                                         int &Offset, LLVMContext *Context) {
7952   assert(Val->getType() == Type::getInt32Ty(*Context) && 
7953          "Unexpected allocation size type!");
7954   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7955     Offset = CI->getZExtValue();
7956     Scale  = 0;
7957     return ConstantInt::get(Type::getInt32Ty(*Context), 0);
7958   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7959     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7960       if (I->getOpcode() == Instruction::Shl) {
7961         // This is a value scaled by '1 << the shift amt'.
7962         Scale = 1U << RHS->getZExtValue();
7963         Offset = 0;
7964         return I->getOperand(0);
7965       } else if (I->getOpcode() == Instruction::Mul) {
7966         // This value is scaled by 'RHS'.
7967         Scale = RHS->getZExtValue();
7968         Offset = 0;
7969         return I->getOperand(0);
7970       } else if (I->getOpcode() == Instruction::Add) {
7971         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7972         // where C1 is divisible by C2.
7973         unsigned SubScale;
7974         Value *SubVal = 
7975           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7976                                     Offset, Context);
7977         Offset += RHS->getZExtValue();
7978         Scale = SubScale;
7979         return SubVal;
7980       }
7981     }
7982   }
7983
7984   // Otherwise, we can't look past this.
7985   Scale = 1;
7986   Offset = 0;
7987   return Val;
7988 }
7989
7990
7991 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7992 /// try to eliminate the cast by moving the type information into the alloc.
7993 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7994                                                    AllocaInst &AI) {
7995   const PointerType *PTy = cast<PointerType>(CI.getType());
7996   
7997   BuilderTy AllocaBuilder(*Builder);
7998   AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7999   
8000   // Remove any uses of AI that are dead.
8001   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
8002   
8003   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
8004     Instruction *User = cast<Instruction>(*UI++);
8005     if (isInstructionTriviallyDead(User)) {
8006       while (UI != E && *UI == User)
8007         ++UI; // If this instruction uses AI more than once, don't break UI.
8008       
8009       ++NumDeadInst;
8010       DEBUG(errs() << "IC: DCE: " << *User << '\n');
8011       EraseInstFromFunction(*User);
8012     }
8013   }
8014
8015   // This requires TargetData to get the alloca alignment and size information.
8016   if (!TD) return 0;
8017
8018   // Get the type really allocated and the type casted to.
8019   const Type *AllocElTy = AI.getAllocatedType();
8020   const Type *CastElTy = PTy->getElementType();
8021   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
8022
8023   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
8024   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
8025   if (CastElTyAlign < AllocElTyAlign) return 0;
8026
8027   // If the allocation has multiple uses, only promote it if we are strictly
8028   // increasing the alignment of the resultant allocation.  If we keep it the
8029   // same, we open the door to infinite loops of various kinds.  (A reference
8030   // from a dbg.declare doesn't count as a use for this purpose.)
8031   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
8032       CastElTyAlign == AllocElTyAlign) return 0;
8033
8034   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
8035   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
8036   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
8037
8038   // See if we can satisfy the modulus by pulling a scale out of the array
8039   // size argument.
8040   unsigned ArraySizeScale;
8041   int ArrayOffset;
8042   Value *NumElements = // See if the array size is a decomposable linear expr.
8043     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
8044                               ArrayOffset, Context);
8045  
8046   // If we can now satisfy the modulus, by using a non-1 scale, we really can
8047   // do the xform.
8048   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
8049       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
8050
8051   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
8052   Value *Amt = 0;
8053   if (Scale == 1) {
8054     Amt = NumElements;
8055   } else {
8056     Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
8057     // Insert before the alloca, not before the cast.
8058     Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
8059   }
8060   
8061   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
8062     Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
8063     Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
8064   }
8065   
8066   AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
8067   New->setAlignment(AI.getAlignment());
8068   New->takeName(&AI);
8069   
8070   // If the allocation has one real use plus a dbg.declare, just remove the
8071   // declare.
8072   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
8073     EraseInstFromFunction(*DI);
8074   }
8075   // If the allocation has multiple real uses, insert a cast and change all
8076   // things that used it to use the new cast.  This will also hack on CI, but it
8077   // will die soon.
8078   else if (!AI.hasOneUse()) {
8079     // New is the allocation instruction, pointer typed. AI is the original
8080     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
8081     Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
8082     AI.replaceAllUsesWith(NewCast);
8083   }
8084   return ReplaceInstUsesWith(CI, New);
8085 }
8086
8087 /// CanEvaluateInDifferentType - Return true if we can take the specified value
8088 /// and return it as type Ty without inserting any new casts and without
8089 /// changing the computed value.  This is used by code that tries to decide
8090 /// whether promoting or shrinking integer operations to wider or smaller types
8091 /// will allow us to eliminate a truncate or extend.
8092 ///
8093 /// This is a truncation operation if Ty is smaller than V->getType(), or an
8094 /// extension operation if Ty is larger.
8095 ///
8096 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
8097 /// should return true if trunc(V) can be computed by computing V in the smaller
8098 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
8099 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
8100 /// efficiently truncated.
8101 ///
8102 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
8103 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
8104 /// the final result.
8105 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
8106                                               unsigned CastOpc,
8107                                               int &NumCastsRemoved){
8108   // We can always evaluate constants in another type.
8109   if (isa<Constant>(V))
8110     return true;
8111   
8112   Instruction *I = dyn_cast<Instruction>(V);
8113   if (!I) return false;
8114   
8115   const Type *OrigTy = V->getType();
8116   
8117   // If this is an extension or truncate, we can often eliminate it.
8118   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
8119     // If this is a cast from the destination type, we can trivially eliminate
8120     // it, and this will remove a cast overall.
8121     if (I->getOperand(0)->getType() == Ty) {
8122       // If the first operand is itself a cast, and is eliminable, do not count
8123       // this as an eliminable cast.  We would prefer to eliminate those two
8124       // casts first.
8125       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
8126         ++NumCastsRemoved;
8127       return true;
8128     }
8129   }
8130
8131   // We can't extend or shrink something that has multiple uses: doing so would
8132   // require duplicating the instruction in general, which isn't profitable.
8133   if (!I->hasOneUse()) return false;
8134
8135   unsigned Opc = I->getOpcode();
8136   switch (Opc) {
8137   case Instruction::Add:
8138   case Instruction::Sub:
8139   case Instruction::Mul:
8140   case Instruction::And:
8141   case Instruction::Or:
8142   case Instruction::Xor:
8143     // These operators can all arbitrarily be extended or truncated.
8144     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8145                                       NumCastsRemoved) &&
8146            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8147                                       NumCastsRemoved);
8148
8149   case Instruction::UDiv:
8150   case Instruction::URem: {
8151     // UDiv and URem can be truncated if all the truncated bits are zero.
8152     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8153     uint32_t BitWidth = Ty->getScalarSizeInBits();
8154     if (BitWidth < OrigBitWidth) {
8155       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
8156       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
8157           MaskedValueIsZero(I->getOperand(1), Mask)) {
8158         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8159                                           NumCastsRemoved) &&
8160                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8161                                           NumCastsRemoved);
8162       }
8163     }
8164     break;
8165   }
8166   case Instruction::Shl:
8167     // If we are truncating the result of this SHL, and if it's a shift of a
8168     // constant amount, we can always perform a SHL in a smaller type.
8169     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8170       uint32_t BitWidth = Ty->getScalarSizeInBits();
8171       if (BitWidth < OrigTy->getScalarSizeInBits() &&
8172           CI->getLimitedValue(BitWidth) < BitWidth)
8173         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8174                                           NumCastsRemoved);
8175     }
8176     break;
8177   case Instruction::LShr:
8178     // If this is a truncate of a logical shr, we can truncate it to a smaller
8179     // lshr iff we know that the bits we would otherwise be shifting in are
8180     // already zeros.
8181     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8182       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8183       uint32_t BitWidth = Ty->getScalarSizeInBits();
8184       if (BitWidth < OrigBitWidth &&
8185           MaskedValueIsZero(I->getOperand(0),
8186             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8187           CI->getLimitedValue(BitWidth) < BitWidth) {
8188         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8189                                           NumCastsRemoved);
8190       }
8191     }
8192     break;
8193   case Instruction::ZExt:
8194   case Instruction::SExt:
8195   case Instruction::Trunc:
8196     // If this is the same kind of case as our original (e.g. zext+zext), we
8197     // can safely replace it.  Note that replacing it does not reduce the number
8198     // of casts in the input.
8199     if (Opc == CastOpc)
8200       return true;
8201
8202     // sext (zext ty1), ty2 -> zext ty2
8203     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8204       return true;
8205     break;
8206   case Instruction::Select: {
8207     SelectInst *SI = cast<SelectInst>(I);
8208     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8209                                       NumCastsRemoved) &&
8210            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8211                                       NumCastsRemoved);
8212   }
8213   case Instruction::PHI: {
8214     // We can change a phi if we can change all operands.
8215     PHINode *PN = cast<PHINode>(I);
8216     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8217       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8218                                       NumCastsRemoved))
8219         return false;
8220     return true;
8221   }
8222   default:
8223     // TODO: Can handle more cases here.
8224     break;
8225   }
8226   
8227   return false;
8228 }
8229
8230 /// EvaluateInDifferentType - Given an expression that 
8231 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8232 /// evaluate the expression.
8233 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
8234                                              bool isSigned) {
8235   if (Constant *C = dyn_cast<Constant>(V))
8236     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
8237
8238   // Otherwise, it must be an instruction.
8239   Instruction *I = cast<Instruction>(V);
8240   Instruction *Res = 0;
8241   unsigned Opc = I->getOpcode();
8242   switch (Opc) {
8243   case Instruction::Add:
8244   case Instruction::Sub:
8245   case Instruction::Mul:
8246   case Instruction::And:
8247   case Instruction::Or:
8248   case Instruction::Xor:
8249   case Instruction::AShr:
8250   case Instruction::LShr:
8251   case Instruction::Shl:
8252   case Instruction::UDiv:
8253   case Instruction::URem: {
8254     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8255     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8256     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8257     break;
8258   }    
8259   case Instruction::Trunc:
8260   case Instruction::ZExt:
8261   case Instruction::SExt:
8262     // If the source type of the cast is the type we're trying for then we can
8263     // just return the source.  There's no need to insert it because it is not
8264     // new.
8265     if (I->getOperand(0)->getType() == Ty)
8266       return I->getOperand(0);
8267     
8268     // Otherwise, must be the same type of cast, so just reinsert a new one.
8269     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
8270     break;
8271   case Instruction::Select: {
8272     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8273     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8274     Res = SelectInst::Create(I->getOperand(0), True, False);
8275     break;
8276   }
8277   case Instruction::PHI: {
8278     PHINode *OPN = cast<PHINode>(I);
8279     PHINode *NPN = PHINode::Create(Ty);
8280     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8281       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8282       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8283     }
8284     Res = NPN;
8285     break;
8286   }
8287   default: 
8288     // TODO: Can handle more cases here.
8289     llvm_unreachable("Unreachable!");
8290     break;
8291   }
8292   
8293   Res->takeName(I);
8294   return InsertNewInstBefore(Res, *I);
8295 }
8296
8297 /// @brief Implement the transforms common to all CastInst visitors.
8298 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8299   Value *Src = CI.getOperand(0);
8300
8301   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8302   // eliminate it now.
8303   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8304     if (Instruction::CastOps opc = 
8305         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8306       // The first cast (CSrc) is eliminable so we need to fix up or replace
8307       // the second cast (CI). CSrc will then have a good chance of being dead.
8308       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8309     }
8310   }
8311
8312   // If we are casting a select then fold the cast into the select
8313   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8314     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8315       return NV;
8316
8317   // If we are casting a PHI then fold the cast into the PHI
8318   if (isa<PHINode>(Src)) {
8319     // We don't do this if this would create a PHI node with an illegal type if
8320     // it is currently legal.
8321     if (!isa<IntegerType>(Src->getType()) ||
8322         !isa<IntegerType>(CI.getType()) ||
8323         ShouldChangeType(CI.getType(), Src->getType(), TD))
8324       if (Instruction *NV = FoldOpIntoPhi(CI))
8325         return NV;
8326   }
8327   
8328   return 0;
8329 }
8330
8331 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8332 /// or not there is a sequence of GEP indices into the type that will land us at
8333 /// the specified offset.  If so, fill them into NewIndices and return the
8334 /// resultant element type, otherwise return null.
8335 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8336                                        SmallVectorImpl<Value*> &NewIndices,
8337                                        const TargetData *TD,
8338                                        LLVMContext *Context) {
8339   if (!TD) return 0;
8340   if (!Ty->isSized()) return 0;
8341   
8342   // Start with the index over the outer type.  Note that the type size
8343   // might be zero (even if the offset isn't zero) if the indexed type
8344   // is something like [0 x {int, int}]
8345   const Type *IntPtrTy = TD->getIntPtrType(*Context);
8346   int64_t FirstIdx = 0;
8347   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8348     FirstIdx = Offset/TySize;
8349     Offset -= FirstIdx*TySize;
8350     
8351     // Handle hosts where % returns negative instead of values [0..TySize).
8352     if (Offset < 0) {
8353       --FirstIdx;
8354       Offset += TySize;
8355       assert(Offset >= 0);
8356     }
8357     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8358   }
8359   
8360   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8361     
8362   // Index into the types.  If we fail, set OrigBase to null.
8363   while (Offset) {
8364     // Indexing into tail padding between struct/array elements.
8365     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8366       return 0;
8367     
8368     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8369       const StructLayout *SL = TD->getStructLayout(STy);
8370       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8371              "Offset must stay within the indexed type");
8372       
8373       unsigned Elt = SL->getElementContainingOffset(Offset);
8374       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8375       
8376       Offset -= SL->getElementOffset(Elt);
8377       Ty = STy->getElementType(Elt);
8378     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8379       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8380       assert(EltSize && "Cannot index into a zero-sized array");
8381       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8382       Offset %= EltSize;
8383       Ty = AT->getElementType();
8384     } else {
8385       // Otherwise, we can't index into the middle of this atomic type, bail.
8386       return 0;
8387     }
8388   }
8389   
8390   return Ty;
8391 }
8392
8393 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8394 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8395   Value *Src = CI.getOperand(0);
8396   
8397   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8398     // If casting the result of a getelementptr instruction with no offset, turn
8399     // this into a cast of the original pointer!
8400     if (GEP->hasAllZeroIndices()) {
8401       // Changing the cast operand is usually not a good idea but it is safe
8402       // here because the pointer operand is being replaced with another 
8403       // pointer operand so the opcode doesn't need to change.
8404       Worklist.Add(GEP);
8405       CI.setOperand(0, GEP->getOperand(0));
8406       return &CI;
8407     }
8408     
8409     // If the GEP has a single use, and the base pointer is a bitcast, and the
8410     // GEP computes a constant offset, see if we can convert these three
8411     // instructions into fewer.  This typically happens with unions and other
8412     // non-type-safe code.
8413     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8414       if (GEP->hasAllConstantIndices()) {
8415         // We are guaranteed to get a constant from EmitGEPOffset.
8416         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, *this));
8417         int64_t Offset = OffsetV->getSExtValue();
8418         
8419         // Get the base pointer input of the bitcast, and the type it points to.
8420         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8421         const Type *GEPIdxTy =
8422           cast<PointerType>(OrigBase->getType())->getElementType();
8423         SmallVector<Value*, 8> NewIndices;
8424         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8425           // If we were able to index down into an element, create the GEP
8426           // and bitcast the result.  This eliminates one bitcast, potentially
8427           // two.
8428           Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8429             Builder->CreateInBoundsGEP(OrigBase,
8430                                        NewIndices.begin(), NewIndices.end()) :
8431             Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
8432           NGEP->takeName(GEP);
8433           
8434           if (isa<BitCastInst>(CI))
8435             return new BitCastInst(NGEP, CI.getType());
8436           assert(isa<PtrToIntInst>(CI));
8437           return new PtrToIntInst(NGEP, CI.getType());
8438         }
8439       }      
8440     }
8441   }
8442     
8443   return commonCastTransforms(CI);
8444 }
8445
8446 /// commonIntCastTransforms - This function implements the common transforms
8447 /// for trunc, zext, and sext.
8448 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8449   if (Instruction *Result = commonCastTransforms(CI))
8450     return Result;
8451
8452   Value *Src = CI.getOperand(0);
8453   const Type *SrcTy = Src->getType();
8454   const Type *DestTy = CI.getType();
8455   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8456   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8457
8458   // See if we can simplify any instructions used by the LHS whose sole 
8459   // purpose is to compute bits we don't care about.
8460   if (SimplifyDemandedInstructionBits(CI))
8461     return &CI;
8462
8463   // If the source isn't an instruction or has more than one use then we
8464   // can't do anything more. 
8465   Instruction *SrcI = dyn_cast<Instruction>(Src);
8466   if (!SrcI || !Src->hasOneUse())
8467     return 0;
8468
8469   // Attempt to propagate the cast into the instruction for int->int casts.
8470   int NumCastsRemoved = 0;
8471   // Only do this if the dest type is a simple type, don't convert the
8472   // expression tree to something weird like i93 unless the source is also
8473   // strange.
8474   if ((isa<VectorType>(DestTy) ||
8475        ShouldChangeType(SrcI->getType(), DestTy, TD)) &&
8476       CanEvaluateInDifferentType(SrcI, DestTy,
8477                                  CI.getOpcode(), NumCastsRemoved)) {
8478     // If this cast is a truncate, evaluting in a different type always
8479     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8480     // we need to do an AND to maintain the clear top-part of the computation,
8481     // so we require that the input have eliminated at least one cast.  If this
8482     // is a sign extension, we insert two new casts (to do the extension) so we
8483     // require that two casts have been eliminated.
8484     bool DoXForm = false;
8485     bool JustReplace = false;
8486     switch (CI.getOpcode()) {
8487     default:
8488       // All the others use floating point so we shouldn't actually 
8489       // get here because of the check above.
8490       llvm_unreachable("Unknown cast type");
8491     case Instruction::Trunc:
8492       DoXForm = true;
8493       break;
8494     case Instruction::ZExt: {
8495       DoXForm = NumCastsRemoved >= 1;
8496       
8497       if (!DoXForm && 0) {
8498         // If it's unnecessary to issue an AND to clear the high bits, it's
8499         // always profitable to do this xform.
8500         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8501         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8502         if (MaskedValueIsZero(TryRes, Mask))
8503           return ReplaceInstUsesWith(CI, TryRes);
8504         
8505         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8506           if (TryI->use_empty())
8507             EraseInstFromFunction(*TryI);
8508       }
8509       break;
8510     }
8511     case Instruction::SExt: {
8512       DoXForm = NumCastsRemoved >= 2;
8513       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8514         // If we do not have to emit the truncate + sext pair, then it's always
8515         // profitable to do this xform.
8516         //
8517         // It's not safe to eliminate the trunc + sext pair if one of the
8518         // eliminated cast is a truncate. e.g.
8519         // t2 = trunc i32 t1 to i16
8520         // t3 = sext i16 t2 to i32
8521         // !=
8522         // i32 t1
8523         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8524         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8525         if (NumSignBits > (DestBitSize - SrcBitSize))
8526           return ReplaceInstUsesWith(CI, TryRes);
8527         
8528         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8529           if (TryI->use_empty())
8530             EraseInstFromFunction(*TryI);
8531       }
8532       break;
8533     }
8534     }
8535     
8536     if (DoXForm) {
8537       DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8538             " to avoid cast: " << CI);
8539       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8540                                            CI.getOpcode() == Instruction::SExt);
8541       if (JustReplace)
8542         // Just replace this cast with the result.
8543         return ReplaceInstUsesWith(CI, Res);
8544
8545       assert(Res->getType() == DestTy);
8546       switch (CI.getOpcode()) {
8547       default: llvm_unreachable("Unknown cast type!");
8548       case Instruction::Trunc:
8549         // Just replace this cast with the result.
8550         return ReplaceInstUsesWith(CI, Res);
8551       case Instruction::ZExt: {
8552         assert(SrcBitSize < DestBitSize && "Not a zext?");
8553
8554         // If the high bits are already zero, just replace this cast with the
8555         // result.
8556         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8557         if (MaskedValueIsZero(Res, Mask))
8558           return ReplaceInstUsesWith(CI, Res);
8559
8560         // We need to emit an AND to clear the high bits.
8561         Constant *C = ConstantInt::get(*Context, 
8562                                  APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8563         return BinaryOperator::CreateAnd(Res, C);
8564       }
8565       case Instruction::SExt: {
8566         // If the high bits are already filled with sign bit, just replace this
8567         // cast with the result.
8568         unsigned NumSignBits = ComputeNumSignBits(Res);
8569         if (NumSignBits > (DestBitSize - SrcBitSize))
8570           return ReplaceInstUsesWith(CI, Res);
8571
8572         // We need to emit a cast to truncate, then a cast to sext.
8573         return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
8574       }
8575       }
8576     }
8577   }
8578   
8579   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8580   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8581
8582   switch (SrcI->getOpcode()) {
8583   case Instruction::Add:
8584   case Instruction::Mul:
8585   case Instruction::And:
8586   case Instruction::Or:
8587   case Instruction::Xor:
8588     // If we are discarding information, rewrite.
8589     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8590       // Don't insert two casts unless at least one can be eliminated.
8591       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8592           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8593         Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8594         Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8595         return BinaryOperator::Create(
8596             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8597       }
8598     }
8599
8600     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8601     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8602         SrcI->getOpcode() == Instruction::Xor &&
8603         Op1 == ConstantInt::getTrue(*Context) &&
8604         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8605       Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
8606       return BinaryOperator::CreateXor(New,
8607                                       ConstantInt::get(CI.getType(), 1));
8608     }
8609     break;
8610
8611   case Instruction::Shl: {
8612     // Canonicalize trunc inside shl, if we can.
8613     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8614     if (CI && DestBitSize < SrcBitSize &&
8615         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8616       Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8617       Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8618       return BinaryOperator::CreateShl(Op0c, Op1c);
8619     }
8620     break;
8621   }
8622   }
8623   return 0;
8624 }
8625
8626 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8627   if (Instruction *Result = commonIntCastTransforms(CI))
8628     return Result;
8629   
8630   Value *Src = CI.getOperand(0);
8631   const Type *Ty = CI.getType();
8632   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8633   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8634
8635   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8636   if (DestBitWidth == 1) {
8637     Constant *One = ConstantInt::get(Src->getType(), 1);
8638     Src = Builder->CreateAnd(Src, One, "tmp");
8639     Value *Zero = Constant::getNullValue(Src->getType());
8640     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8641   }
8642
8643   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8644   ConstantInt *ShAmtV = 0;
8645   Value *ShiftOp = 0;
8646   if (Src->hasOneUse() &&
8647       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8648     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8649     
8650     // Get a mask for the bits shifting in.
8651     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8652     if (MaskedValueIsZero(ShiftOp, Mask)) {
8653       if (ShAmt >= DestBitWidth)        // All zeros.
8654         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8655       
8656       // Okay, we can shrink this.  Truncate the input, then return a new
8657       // shift.
8658       Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
8659       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8660       return BinaryOperator::CreateLShr(V1, V2);
8661     }
8662   }
8663  
8664   return 0;
8665 }
8666
8667 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8668 /// in order to eliminate the icmp.
8669 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8670                                              bool DoXform) {
8671   // If we are just checking for a icmp eq of a single bit and zext'ing it
8672   // to an integer, then shift the bit to the appropriate place and then
8673   // cast to integer to avoid the comparison.
8674   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8675     const APInt &Op1CV = Op1C->getValue();
8676       
8677     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8678     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8679     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8680         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8681       if (!DoXform) return ICI;
8682
8683       Value *In = ICI->getOperand(0);
8684       Value *Sh = ConstantInt::get(In->getType(),
8685                                    In->getType()->getScalarSizeInBits()-1);
8686       In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
8687       if (In->getType() != CI.getType())
8688         In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
8689
8690       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8691         Constant *One = ConstantInt::get(In->getType(), 1);
8692         In = Builder->CreateXor(In, One, In->getName()+".not");
8693       }
8694
8695       return ReplaceInstUsesWith(CI, In);
8696     }
8697       
8698       
8699       
8700     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8701     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8702     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8703     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8704     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8705     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8706     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8707     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8708     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8709         // This only works for EQ and NE
8710         ICI->isEquality()) {
8711       // If Op1C some other power of two, convert:
8712       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8713       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8714       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8715       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8716         
8717       APInt KnownZeroMask(~KnownZero);
8718       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8719         if (!DoXform) return ICI;
8720
8721         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8722         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8723           // (X&4) == 2 --> false
8724           // (X&4) != 2 --> true
8725           Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8726           Res = ConstantExpr::getZExt(Res, CI.getType());
8727           return ReplaceInstUsesWith(CI, Res);
8728         }
8729           
8730         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8731         Value *In = ICI->getOperand(0);
8732         if (ShiftAmt) {
8733           // Perform a logical shr by shiftamt.
8734           // Insert the shift to put the result in the low bit.
8735           In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8736                                    In->getName()+".lobit");
8737         }
8738           
8739         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8740           Constant *One = ConstantInt::get(In->getType(), 1);
8741           In = Builder->CreateXor(In, One, "tmp");
8742         }
8743           
8744         if (CI.getType() == In->getType())
8745           return ReplaceInstUsesWith(CI, In);
8746         else
8747           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8748       }
8749     }
8750   }
8751
8752   // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
8753   // It is also profitable to transform icmp eq into not(xor(A, B)) because that
8754   // may lead to additional simplifications.
8755   if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
8756     if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
8757       uint32_t BitWidth = ITy->getBitWidth();
8758       Value *LHS = ICI->getOperand(0);
8759       Value *RHS = ICI->getOperand(1);
8760
8761       APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
8762       APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
8763       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8764       ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
8765       ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
8766
8767       if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
8768         APInt KnownBits = KnownZeroLHS | KnownOneLHS;
8769         APInt UnknownBit = ~KnownBits;
8770         if (UnknownBit.countPopulation() == 1) {
8771           if (!DoXform) return ICI;
8772
8773           Value *Result = Builder->CreateXor(LHS, RHS);
8774
8775           // Mask off any bits that are set and won't be shifted away.
8776           if (KnownOneLHS.uge(UnknownBit))
8777             Result = Builder->CreateAnd(Result,
8778                                         ConstantInt::get(ITy, UnknownBit));
8779
8780           // Shift the bit we're testing down to the lsb.
8781           Result = Builder->CreateLShr(
8782                Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
8783
8784           if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8785             Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
8786           Result->takeName(ICI);
8787           return ReplaceInstUsesWith(CI, Result);
8788         }
8789       }
8790     }
8791   }
8792
8793   return 0;
8794 }
8795
8796 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8797   // If one of the common conversion will work ..
8798   if (Instruction *Result = commonIntCastTransforms(CI))
8799     return Result;
8800
8801   Value *Src = CI.getOperand(0);
8802
8803   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8804   // types and if the sizes are just right we can convert this into a logical
8805   // 'and' which will be much cheaper than the pair of casts.
8806   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8807     // Get the sizes of the types involved.  We know that the intermediate type
8808     // will be smaller than A or C, but don't know the relation between A and C.
8809     Value *A = CSrc->getOperand(0);
8810     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8811     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8812     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8813     // If we're actually extending zero bits, then if
8814     // SrcSize <  DstSize: zext(a & mask)
8815     // SrcSize == DstSize: a & mask
8816     // SrcSize  > DstSize: trunc(a) & mask
8817     if (SrcSize < DstSize) {
8818       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8819       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8820       Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
8821       return new ZExtInst(And, CI.getType());
8822     }
8823     
8824     if (SrcSize == DstSize) {
8825       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8826       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8827                                                            AndValue));
8828     }
8829     if (SrcSize > DstSize) {
8830       Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
8831       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8832       return BinaryOperator::CreateAnd(Trunc, 
8833                                        ConstantInt::get(Trunc->getType(),
8834                                                                AndValue));
8835     }
8836   }
8837
8838   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8839     return transformZExtICmp(ICI, CI);
8840
8841   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8842   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8843     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8844     // of the (zext icmp) will be transformed.
8845     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8846     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8847     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8848         (transformZExtICmp(LHS, CI, false) ||
8849          transformZExtICmp(RHS, CI, false))) {
8850       Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8851       Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
8852       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8853     }
8854   }
8855
8856   // zext(trunc(t) & C) -> (t & zext(C)).
8857   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8858     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8859       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8860         Value *TI0 = TI->getOperand(0);
8861         if (TI0->getType() == CI.getType())
8862           return
8863             BinaryOperator::CreateAnd(TI0,
8864                                 ConstantExpr::getZExt(C, CI.getType()));
8865       }
8866
8867   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8868   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8869     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8870       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8871         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8872             And->getOperand(1) == C)
8873           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8874             Value *TI0 = TI->getOperand(0);
8875             if (TI0->getType() == CI.getType()) {
8876               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8877               Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
8878               return BinaryOperator::CreateXor(NewAnd, ZC);
8879             }
8880           }
8881
8882   return 0;
8883 }
8884
8885 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8886   if (Instruction *I = commonIntCastTransforms(CI))
8887     return I;
8888   
8889   Value *Src = CI.getOperand(0);
8890   
8891   // Canonicalize sign-extend from i1 to a select.
8892   if (Src->getType() == Type::getInt1Ty(*Context))
8893     return SelectInst::Create(Src,
8894                               Constant::getAllOnesValue(CI.getType()),
8895                               Constant::getNullValue(CI.getType()));
8896
8897   // See if the value being truncated is already sign extended.  If so, just
8898   // eliminate the trunc/sext pair.
8899   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8900     Value *Op = cast<User>(Src)->getOperand(0);
8901     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8902     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8903     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8904     unsigned NumSignBits = ComputeNumSignBits(Op);
8905
8906     if (OpBits == DestBits) {
8907       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8908       // bits, it is already ready.
8909       if (NumSignBits > DestBits-MidBits)
8910         return ReplaceInstUsesWith(CI, Op);
8911     } else if (OpBits < DestBits) {
8912       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8913       // bits, just sext from i32.
8914       if (NumSignBits > OpBits-MidBits)
8915         return new SExtInst(Op, CI.getType(), "tmp");
8916     } else {
8917       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8918       // bits, just truncate to i32.
8919       if (NumSignBits > OpBits-MidBits)
8920         return new TruncInst(Op, CI.getType(), "tmp");
8921     }
8922   }
8923
8924   // If the input is a shl/ashr pair of a same constant, then this is a sign
8925   // extension from a smaller value.  If we could trust arbitrary bitwidth
8926   // integers, we could turn this into a truncate to the smaller bit and then
8927   // use a sext for the whole extension.  Since we don't, look deeper and check
8928   // for a truncate.  If the source and dest are the same type, eliminate the
8929   // trunc and extend and just do shifts.  For example, turn:
8930   //   %a = trunc i32 %i to i8
8931   //   %b = shl i8 %a, 6
8932   //   %c = ashr i8 %b, 6
8933   //   %d = sext i8 %c to i32
8934   // into:
8935   //   %a = shl i32 %i, 30
8936   //   %d = ashr i32 %a, 30
8937   Value *A = 0;
8938   ConstantInt *BA = 0, *CA = 0;
8939   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8940                         m_ConstantInt(CA))) &&
8941       BA == CA && isa<TruncInst>(A)) {
8942     Value *I = cast<TruncInst>(A)->getOperand(0);
8943     if (I->getType() == CI.getType()) {
8944       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8945       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8946       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8947       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8948       I = Builder->CreateShl(I, ShAmtV, CI.getName());
8949       return BinaryOperator::CreateAShr(I, ShAmtV);
8950     }
8951   }
8952   
8953   return 0;
8954 }
8955
8956 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8957 /// in the specified FP type without changing its value.
8958 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8959                               LLVMContext *Context) {
8960   bool losesInfo;
8961   APFloat F = CFP->getValueAPF();
8962   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8963   if (!losesInfo)
8964     return ConstantFP::get(*Context, F);
8965   return 0;
8966 }
8967
8968 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8969 /// through it until we get the source value.
8970 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8971   if (Instruction *I = dyn_cast<Instruction>(V))
8972     if (I->getOpcode() == Instruction::FPExt)
8973       return LookThroughFPExtensions(I->getOperand(0), Context);
8974   
8975   // If this value is a constant, return the constant in the smallest FP type
8976   // that can accurately represent it.  This allows us to turn
8977   // (float)((double)X+2.0) into x+2.0f.
8978   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8979     if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
8980       return V;  // No constant folding of this.
8981     // See if the value can be truncated to float and then reextended.
8982     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8983       return V;
8984     if (CFP->getType() == Type::getDoubleTy(*Context))
8985       return V;  // Won't shrink.
8986     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8987       return V;
8988     // Don't try to shrink to various long double types.
8989   }
8990   
8991   return V;
8992 }
8993
8994 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8995   if (Instruction *I = commonCastTransforms(CI))
8996     return I;
8997   
8998   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8999   // smaller than the destination type, we can eliminate the truncate by doing
9000   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
9001   // many builtins (sqrt, etc).
9002   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
9003   if (OpI && OpI->hasOneUse()) {
9004     switch (OpI->getOpcode()) {
9005     default: break;
9006     case Instruction::FAdd:
9007     case Instruction::FSub:
9008     case Instruction::FMul:
9009     case Instruction::FDiv:
9010     case Instruction::FRem:
9011       const Type *SrcTy = OpI->getType();
9012       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
9013       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
9014       if (LHSTrunc->getType() != SrcTy && 
9015           RHSTrunc->getType() != SrcTy) {
9016         unsigned DstSize = CI.getType()->getScalarSizeInBits();
9017         // If the source types were both smaller than the destination type of
9018         // the cast, do this xform.
9019         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
9020             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
9021           LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
9022           RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
9023           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
9024         }
9025       }
9026       break;  
9027     }
9028   }
9029   return 0;
9030 }
9031
9032 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
9033   return commonCastTransforms(CI);
9034 }
9035
9036 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
9037   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
9038   if (OpI == 0)
9039     return commonCastTransforms(FI);
9040
9041   // fptoui(uitofp(X)) --> X
9042   // fptoui(sitofp(X)) --> X
9043   // This is safe if the intermediate type has enough bits in its mantissa to
9044   // accurately represent all values of X.  For example, do not do this with
9045   // i64->float->i64.  This is also safe for sitofp case, because any negative
9046   // 'X' value would cause an undefined result for the fptoui. 
9047   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
9048       OpI->getOperand(0)->getType() == FI.getType() &&
9049       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
9050                     OpI->getType()->getFPMantissaWidth())
9051     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
9052
9053   return commonCastTransforms(FI);
9054 }
9055
9056 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
9057   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
9058   if (OpI == 0)
9059     return commonCastTransforms(FI);
9060   
9061   // fptosi(sitofp(X)) --> X
9062   // fptosi(uitofp(X)) --> X
9063   // This is safe if the intermediate type has enough bits in its mantissa to
9064   // accurately represent all values of X.  For example, do not do this with
9065   // i64->float->i64.  This is also safe for sitofp case, because any negative
9066   // 'X' value would cause an undefined result for the fptoui. 
9067   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
9068       OpI->getOperand(0)->getType() == FI.getType() &&
9069       (int)FI.getType()->getScalarSizeInBits() <=
9070                     OpI->getType()->getFPMantissaWidth())
9071     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
9072   
9073   return commonCastTransforms(FI);
9074 }
9075
9076 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
9077   return commonCastTransforms(CI);
9078 }
9079
9080 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
9081   return commonCastTransforms(CI);
9082 }
9083
9084 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
9085   // If the destination integer type is smaller than the intptr_t type for
9086   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
9087   // trunc to be exposed to other transforms.  Don't do this for extending
9088   // ptrtoint's, because we don't know if the target sign or zero extends its
9089   // pointers.
9090   if (TD &&
9091       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
9092     Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
9093                                        TD->getIntPtrType(CI.getContext()),
9094                                        "tmp");
9095     return new TruncInst(P, CI.getType());
9096   }
9097   
9098   return commonPointerCastTransforms(CI);
9099 }
9100
9101 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
9102   // If the source integer type is larger than the intptr_t type for
9103   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
9104   // allows the trunc to be exposed to other transforms.  Don't do this for
9105   // extending inttoptr's, because we don't know if the target sign or zero
9106   // extends to pointers.
9107   if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
9108       TD->getPointerSizeInBits()) {
9109     Value *P = Builder->CreateTrunc(CI.getOperand(0),
9110                                     TD->getIntPtrType(CI.getContext()), "tmp");
9111     return new IntToPtrInst(P, CI.getType());
9112   }
9113   
9114   if (Instruction *I = commonCastTransforms(CI))
9115     return I;
9116
9117   return 0;
9118 }
9119
9120 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
9121   // If the operands are integer typed then apply the integer transforms,
9122   // otherwise just apply the common ones.
9123   Value *Src = CI.getOperand(0);
9124   const Type *SrcTy = Src->getType();
9125   const Type *DestTy = CI.getType();
9126
9127   if (isa<PointerType>(SrcTy)) {
9128     if (Instruction *I = commonPointerCastTransforms(CI))
9129       return I;
9130   } else {
9131     if (Instruction *Result = commonCastTransforms(CI))
9132       return Result;
9133   }
9134
9135
9136   // Get rid of casts from one type to the same type. These are useless and can
9137   // be replaced by the operand.
9138   if (DestTy == Src->getType())
9139     return ReplaceInstUsesWith(CI, Src);
9140
9141   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
9142     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
9143     const Type *DstElTy = DstPTy->getElementType();
9144     const Type *SrcElTy = SrcPTy->getElementType();
9145     
9146     // If the address spaces don't match, don't eliminate the bitcast, which is
9147     // required for changing types.
9148     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9149       return 0;
9150     
9151     // If we are casting a alloca to a pointer to a type of the same
9152     // size, rewrite the allocation instruction to allocate the "right" type.
9153     // There is no need to modify malloc calls because it is their bitcast that
9154     // needs to be cleaned up.
9155     if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
9156       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9157         return V;
9158     
9159     // If the source and destination are pointers, and this cast is equivalent
9160     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
9161     // This can enhance SROA and other transforms that want type-safe pointers.
9162     Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
9163     unsigned NumZeros = 0;
9164     while (SrcElTy != DstElTy && 
9165            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9166            SrcElTy->getNumContainedTypes() /* not "{}" */) {
9167       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9168       ++NumZeros;
9169     }
9170
9171     // If we found a path from the src to dest, create the getelementptr now.
9172     if (SrcElTy == DstElTy) {
9173       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
9174       return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
9175                                                ((Instruction*) NULL));
9176     }
9177   }
9178
9179   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9180     if (DestVTy->getNumElements() == 1) {
9181       if (!isa<VectorType>(SrcTy)) {
9182         Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
9183         return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
9184                             Constant::getNullValue(Type::getInt32Ty(*Context)));
9185       }
9186       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9187     }
9188   }
9189
9190   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9191     if (SrcVTy->getNumElements() == 1) {
9192       if (!isa<VectorType>(DestTy)) {
9193         Value *Elem = 
9194           Builder->CreateExtractElement(Src,
9195                             Constant::getNullValue(Type::getInt32Ty(*Context)));
9196         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9197       }
9198     }
9199   }
9200
9201   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9202     if (SVI->hasOneUse()) {
9203       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
9204       // a bitconvert to a vector with the same # elts.
9205       if (isa<VectorType>(DestTy) && 
9206           cast<VectorType>(DestTy)->getNumElements() ==
9207                 SVI->getType()->getNumElements() &&
9208           SVI->getType()->getNumElements() ==
9209             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9210         CastInst *Tmp;
9211         // If either of the operands is a cast from CI.getType(), then
9212         // evaluating the shuffle in the casted destination's type will allow
9213         // us to eliminate at least one cast.
9214         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
9215              Tmp->getOperand(0)->getType() == DestTy) ||
9216             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
9217              Tmp->getOperand(0)->getType() == DestTy)) {
9218           Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
9219           Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
9220           // Return a new shuffle vector.  Use the same element ID's, as we
9221           // know the vector types match #elts.
9222           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9223         }
9224       }
9225     }
9226   }
9227   return 0;
9228 }
9229
9230 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9231 ///   %C = or %A, %B
9232 ///   %D = select %cond, %C, %A
9233 /// into:
9234 ///   %C = select %cond, %B, 0
9235 ///   %D = or %A, %C
9236 ///
9237 /// Assuming that the specified instruction is an operand to the select, return
9238 /// a bitmask indicating which operands of this instruction are foldable if they
9239 /// equal the other incoming value of the select.
9240 ///
9241 static unsigned GetSelectFoldableOperands(Instruction *I) {
9242   switch (I->getOpcode()) {
9243   case Instruction::Add:
9244   case Instruction::Mul:
9245   case Instruction::And:
9246   case Instruction::Or:
9247   case Instruction::Xor:
9248     return 3;              // Can fold through either operand.
9249   case Instruction::Sub:   // Can only fold on the amount subtracted.
9250   case Instruction::Shl:   // Can only fold on the shift amount.
9251   case Instruction::LShr:
9252   case Instruction::AShr:
9253     return 1;
9254   default:
9255     return 0;              // Cannot fold
9256   }
9257 }
9258
9259 /// GetSelectFoldableConstant - For the same transformation as the previous
9260 /// function, return the identity constant that goes into the select.
9261 static Constant *GetSelectFoldableConstant(Instruction *I,
9262                                            LLVMContext *Context) {
9263   switch (I->getOpcode()) {
9264   default: llvm_unreachable("This cannot happen!");
9265   case Instruction::Add:
9266   case Instruction::Sub:
9267   case Instruction::Or:
9268   case Instruction::Xor:
9269   case Instruction::Shl:
9270   case Instruction::LShr:
9271   case Instruction::AShr:
9272     return Constant::getNullValue(I->getType());
9273   case Instruction::And:
9274     return Constant::getAllOnesValue(I->getType());
9275   case Instruction::Mul:
9276     return ConstantInt::get(I->getType(), 1);
9277   }
9278 }
9279
9280 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9281 /// have the same opcode and only one use each.  Try to simplify this.
9282 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9283                                           Instruction *FI) {
9284   if (TI->getNumOperands() == 1) {
9285     // If this is a non-volatile load or a cast from the same type,
9286     // merge.
9287     if (TI->isCast()) {
9288       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9289         return 0;
9290     } else {
9291       return 0;  // unknown unary op.
9292     }
9293
9294     // Fold this by inserting a select from the input values.
9295     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9296                                           FI->getOperand(0), SI.getName()+".v");
9297     InsertNewInstBefore(NewSI, SI);
9298     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9299                             TI->getType());
9300   }
9301
9302   // Only handle binary operators here.
9303   if (!isa<BinaryOperator>(TI))
9304     return 0;
9305
9306   // Figure out if the operations have any operands in common.
9307   Value *MatchOp, *OtherOpT, *OtherOpF;
9308   bool MatchIsOpZero;
9309   if (TI->getOperand(0) == FI->getOperand(0)) {
9310     MatchOp  = TI->getOperand(0);
9311     OtherOpT = TI->getOperand(1);
9312     OtherOpF = FI->getOperand(1);
9313     MatchIsOpZero = true;
9314   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9315     MatchOp  = TI->getOperand(1);
9316     OtherOpT = TI->getOperand(0);
9317     OtherOpF = FI->getOperand(0);
9318     MatchIsOpZero = false;
9319   } else if (!TI->isCommutative()) {
9320     return 0;
9321   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9322     MatchOp  = TI->getOperand(0);
9323     OtherOpT = TI->getOperand(1);
9324     OtherOpF = FI->getOperand(0);
9325     MatchIsOpZero = true;
9326   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9327     MatchOp  = TI->getOperand(1);
9328     OtherOpT = TI->getOperand(0);
9329     OtherOpF = FI->getOperand(1);
9330     MatchIsOpZero = true;
9331   } else {
9332     return 0;
9333   }
9334
9335   // If we reach here, they do have operations in common.
9336   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9337                                          OtherOpF, SI.getName()+".v");
9338   InsertNewInstBefore(NewSI, SI);
9339
9340   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9341     if (MatchIsOpZero)
9342       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9343     else
9344       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9345   }
9346   llvm_unreachable("Shouldn't get here");
9347   return 0;
9348 }
9349
9350 static bool isSelect01(Constant *C1, Constant *C2) {
9351   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9352   if (!C1I)
9353     return false;
9354   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9355   if (!C2I)
9356     return false;
9357   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9358 }
9359
9360 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9361 /// facilitate further optimization.
9362 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9363                                             Value *FalseVal) {
9364   // See the comment above GetSelectFoldableOperands for a description of the
9365   // transformation we are doing here.
9366   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9367     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9368         !isa<Constant>(FalseVal)) {
9369       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9370         unsigned OpToFold = 0;
9371         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9372           OpToFold = 1;
9373         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9374           OpToFold = 2;
9375         }
9376
9377         if (OpToFold) {
9378           Constant *C = GetSelectFoldableConstant(TVI, Context);
9379           Value *OOp = TVI->getOperand(2-OpToFold);
9380           // Avoid creating select between 2 constants unless it's selecting
9381           // between 0 and 1.
9382           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9383             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9384             InsertNewInstBefore(NewSel, SI);
9385             NewSel->takeName(TVI);
9386             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9387               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9388             llvm_unreachable("Unknown instruction!!");
9389           }
9390         }
9391       }
9392     }
9393   }
9394
9395   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9396     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9397         !isa<Constant>(TrueVal)) {
9398       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9399         unsigned OpToFold = 0;
9400         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9401           OpToFold = 1;
9402         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9403           OpToFold = 2;
9404         }
9405
9406         if (OpToFold) {
9407           Constant *C = GetSelectFoldableConstant(FVI, Context);
9408           Value *OOp = FVI->getOperand(2-OpToFold);
9409           // Avoid creating select between 2 constants unless it's selecting
9410           // between 0 and 1.
9411           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9412             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9413             InsertNewInstBefore(NewSel, SI);
9414             NewSel->takeName(FVI);
9415             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9416               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9417             llvm_unreachable("Unknown instruction!!");
9418           }
9419         }
9420       }
9421     }
9422   }
9423
9424   return 0;
9425 }
9426
9427 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9428 /// ICmpInst as its first operand.
9429 ///
9430 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9431                                                    ICmpInst *ICI) {
9432   bool Changed = false;
9433   ICmpInst::Predicate Pred = ICI->getPredicate();
9434   Value *CmpLHS = ICI->getOperand(0);
9435   Value *CmpRHS = ICI->getOperand(1);
9436   Value *TrueVal = SI.getTrueValue();
9437   Value *FalseVal = SI.getFalseValue();
9438
9439   // Check cases where the comparison is with a constant that
9440   // can be adjusted to fit the min/max idiom. We may edit ICI in
9441   // place here, so make sure the select is the only user.
9442   if (ICI->hasOneUse())
9443     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9444       switch (Pred) {
9445       default: break;
9446       case ICmpInst::ICMP_ULT:
9447       case ICmpInst::ICMP_SLT: {
9448         // X < MIN ? T : F  -->  F
9449         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9450           return ReplaceInstUsesWith(SI, FalseVal);
9451         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9452         Constant *AdjustedRHS = SubOne(CI);
9453         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9454             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9455           Pred = ICmpInst::getSwappedPredicate(Pred);
9456           CmpRHS = AdjustedRHS;
9457           std::swap(FalseVal, TrueVal);
9458           ICI->setPredicate(Pred);
9459           ICI->setOperand(1, CmpRHS);
9460           SI.setOperand(1, TrueVal);
9461           SI.setOperand(2, FalseVal);
9462           Changed = true;
9463         }
9464         break;
9465       }
9466       case ICmpInst::ICMP_UGT:
9467       case ICmpInst::ICMP_SGT: {
9468         // X > MAX ? T : F  -->  F
9469         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9470           return ReplaceInstUsesWith(SI, FalseVal);
9471         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9472         Constant *AdjustedRHS = AddOne(CI);
9473         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9474             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9475           Pred = ICmpInst::getSwappedPredicate(Pred);
9476           CmpRHS = AdjustedRHS;
9477           std::swap(FalseVal, TrueVal);
9478           ICI->setPredicate(Pred);
9479           ICI->setOperand(1, CmpRHS);
9480           SI.setOperand(1, TrueVal);
9481           SI.setOperand(2, FalseVal);
9482           Changed = true;
9483         }
9484         break;
9485       }
9486       }
9487
9488       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9489       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9490       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9491       if (match(TrueVal, m_ConstantInt<-1>()) &&
9492           match(FalseVal, m_ConstantInt<0>()))
9493         Pred = ICI->getPredicate();
9494       else if (match(TrueVal, m_ConstantInt<0>()) &&
9495                match(FalseVal, m_ConstantInt<-1>()))
9496         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9497       
9498       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9499         // If we are just checking for a icmp eq of a single bit and zext'ing it
9500         // to an integer, then shift the bit to the appropriate place and then
9501         // cast to integer to avoid the comparison.
9502         const APInt &Op1CV = CI->getValue();
9503     
9504         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9505         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9506         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9507             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9508           Value *In = ICI->getOperand(0);
9509           Value *Sh = ConstantInt::get(In->getType(),
9510                                        In->getType()->getScalarSizeInBits()-1);
9511           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9512                                                         In->getName()+".lobit"),
9513                                    *ICI);
9514           if (In->getType() != SI.getType())
9515             In = CastInst::CreateIntegerCast(In, SI.getType(),
9516                                              true/*SExt*/, "tmp", ICI);
9517     
9518           if (Pred == ICmpInst::ICMP_SGT)
9519             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9520                                        In->getName()+".not"), *ICI);
9521     
9522           return ReplaceInstUsesWith(SI, In);
9523         }
9524       }
9525     }
9526
9527   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9528     // Transform (X == Y) ? X : Y  -> Y
9529     if (Pred == ICmpInst::ICMP_EQ)
9530       return ReplaceInstUsesWith(SI, FalseVal);
9531     // Transform (X != Y) ? X : Y  -> X
9532     if (Pred == ICmpInst::ICMP_NE)
9533       return ReplaceInstUsesWith(SI, TrueVal);
9534     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9535
9536   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9537     // Transform (X == Y) ? Y : X  -> X
9538     if (Pred == ICmpInst::ICMP_EQ)
9539       return ReplaceInstUsesWith(SI, FalseVal);
9540     // Transform (X != Y) ? Y : X  -> Y
9541     if (Pred == ICmpInst::ICMP_NE)
9542       return ReplaceInstUsesWith(SI, TrueVal);
9543     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9544   }
9545   return Changed ? &SI : 0;
9546 }
9547
9548
9549 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9550 /// PHI node (but the two may be in different blocks).  See if the true/false
9551 /// values (V) are live in all of the predecessor blocks of the PHI.  For
9552 /// example, cases like this cannot be mapped:
9553 ///
9554 ///   X = phi [ C1, BB1], [C2, BB2]
9555 ///   Y = add
9556 ///   Z = select X, Y, 0
9557 ///
9558 /// because Y is not live in BB1/BB2.
9559 ///
9560 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9561                                                    const SelectInst &SI) {
9562   // If the value is a non-instruction value like a constant or argument, it
9563   // can always be mapped.
9564   const Instruction *I = dyn_cast<Instruction>(V);
9565   if (I == 0) return true;
9566   
9567   // If V is a PHI node defined in the same block as the condition PHI, we can
9568   // map the arguments.
9569   const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9570   
9571   if (const PHINode *VP = dyn_cast<PHINode>(I))
9572     if (VP->getParent() == CondPHI->getParent())
9573       return true;
9574   
9575   // Otherwise, if the PHI and select are defined in the same block and if V is
9576   // defined in a different block, then we can transform it.
9577   if (SI.getParent() == CondPHI->getParent() &&
9578       I->getParent() != CondPHI->getParent())
9579     return true;
9580   
9581   // Otherwise we have a 'hard' case and we can't tell without doing more
9582   // detailed dominator based analysis, punt.
9583   return false;
9584 }
9585
9586 /// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
9587 ///   SPF2(SPF1(A, B), C) 
9588 Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
9589                                         SelectPatternFlavor SPF1,
9590                                         Value *A, Value *B,
9591                                         Instruction &Outer,
9592                                         SelectPatternFlavor SPF2, Value *C) {
9593   if (C == A || C == B) {
9594     // MAX(MAX(A, B), B) -> MAX(A, B)
9595     // MIN(MIN(a, b), a) -> MIN(a, b)
9596     if (SPF1 == SPF2)
9597       return ReplaceInstUsesWith(Outer, Inner);
9598     
9599     // MAX(MIN(a, b), a) -> a
9600     // MIN(MAX(a, b), a) -> a
9601     if (SPF1 == SPF_SMIN && SPF2 == SPF_SMAX ||
9602         SPF1 == SPF_SMAX && SPF2 == SPF_SMIN ||
9603         SPF1 == SPF_UMIN && SPF2 == SPF_UMAX ||
9604         SPF1 == SPF_UMAX && SPF2 == SPF_UMIN)
9605       return ReplaceInstUsesWith(Outer, C);
9606   }
9607   
9608   // TODO: MIN(MIN(A, 23), 97)
9609   return 0;
9610 }
9611
9612
9613
9614
9615 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9616   Value *CondVal = SI.getCondition();
9617   Value *TrueVal = SI.getTrueValue();
9618   Value *FalseVal = SI.getFalseValue();
9619
9620   // select true, X, Y  -> X
9621   // select false, X, Y -> Y
9622   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9623     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9624
9625   // select C, X, X -> X
9626   if (TrueVal == FalseVal)
9627     return ReplaceInstUsesWith(SI, TrueVal);
9628
9629   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9630     return ReplaceInstUsesWith(SI, FalseVal);
9631   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9632     return ReplaceInstUsesWith(SI, TrueVal);
9633   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9634     if (isa<Constant>(TrueVal))
9635       return ReplaceInstUsesWith(SI, TrueVal);
9636     else
9637       return ReplaceInstUsesWith(SI, FalseVal);
9638   }
9639
9640   if (SI.getType() == Type::getInt1Ty(*Context)) {
9641     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9642       if (C->getZExtValue()) {
9643         // Change: A = select B, true, C --> A = or B, C
9644         return BinaryOperator::CreateOr(CondVal, FalseVal);
9645       } else {
9646         // Change: A = select B, false, C --> A = and !B, C
9647         Value *NotCond =
9648           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9649                                              "not."+CondVal->getName()), SI);
9650         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9651       }
9652     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9653       if (C->getZExtValue() == false) {
9654         // Change: A = select B, C, false --> A = and B, C
9655         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9656       } else {
9657         // Change: A = select B, C, true --> A = or !B, C
9658         Value *NotCond =
9659           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9660                                              "not."+CondVal->getName()), SI);
9661         return BinaryOperator::CreateOr(NotCond, TrueVal);
9662       }
9663     }
9664     
9665     // select a, b, a  -> a&b
9666     // select a, a, b  -> a|b
9667     if (CondVal == TrueVal)
9668       return BinaryOperator::CreateOr(CondVal, FalseVal);
9669     else if (CondVal == FalseVal)
9670       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9671   }
9672
9673   // Selecting between two integer constants?
9674   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9675     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9676       // select C, 1, 0 -> zext C to int
9677       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9678         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9679       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9680         // select C, 0, 1 -> zext !C to int
9681         Value *NotCond =
9682           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9683                                                "not."+CondVal->getName()), SI);
9684         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9685       }
9686
9687       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9688         // If one of the constants is zero (we know they can't both be) and we
9689         // have an icmp instruction with zero, and we have an 'and' with the
9690         // non-constant value, eliminate this whole mess.  This corresponds to
9691         // cases like this: ((X & 27) ? 27 : 0)
9692         if (TrueValC->isZero() || FalseValC->isZero())
9693           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9694               cast<Constant>(IC->getOperand(1))->isNullValue())
9695             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9696               if (ICA->getOpcode() == Instruction::And &&
9697                   isa<ConstantInt>(ICA->getOperand(1)) &&
9698                   (ICA->getOperand(1) == TrueValC ||
9699                    ICA->getOperand(1) == FalseValC) &&
9700                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9701                 // Okay, now we know that everything is set up, we just don't
9702                 // know whether we have a icmp_ne or icmp_eq and whether the 
9703                 // true or false val is the zero.
9704                 bool ShouldNotVal = !TrueValC->isZero();
9705                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9706                 Value *V = ICA;
9707                 if (ShouldNotVal)
9708                   V = InsertNewInstBefore(BinaryOperator::Create(
9709                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9710                 return ReplaceInstUsesWith(SI, V);
9711               }
9712       }
9713     }
9714
9715   // See if we are selecting two values based on a comparison of the two values.
9716   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9717     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9718       // Transform (X == Y) ? X : Y  -> Y
9719       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9720         // This is not safe in general for floating point:  
9721         // consider X== -0, Y== +0.
9722         // It becomes safe if either operand is a nonzero constant.
9723         ConstantFP *CFPt, *CFPf;
9724         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9725               !CFPt->getValueAPF().isZero()) ||
9726             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9727              !CFPf->getValueAPF().isZero()))
9728         return ReplaceInstUsesWith(SI, FalseVal);
9729       }
9730       // Transform (X != Y) ? X : Y  -> X
9731       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9732         return ReplaceInstUsesWith(SI, TrueVal);
9733       // NOTE: if we wanted to, this is where to detect MIN/MAX
9734
9735     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9736       // Transform (X == Y) ? Y : X  -> X
9737       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9738         // This is not safe in general for floating point:  
9739         // consider X== -0, Y== +0.
9740         // It becomes safe if either operand is a nonzero constant.
9741         ConstantFP *CFPt, *CFPf;
9742         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9743               !CFPt->getValueAPF().isZero()) ||
9744             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9745              !CFPf->getValueAPF().isZero()))
9746           return ReplaceInstUsesWith(SI, FalseVal);
9747       }
9748       // Transform (X != Y) ? Y : X  -> Y
9749       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9750         return ReplaceInstUsesWith(SI, TrueVal);
9751       // NOTE: if we wanted to, this is where to detect MIN/MAX
9752     }
9753     // NOTE: if we wanted to, this is where to detect ABS
9754   }
9755
9756   // See if we are selecting two values based on a comparison of the two values.
9757   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9758     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9759       return Result;
9760
9761   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9762     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9763       if (TI->hasOneUse() && FI->hasOneUse()) {
9764         Instruction *AddOp = 0, *SubOp = 0;
9765
9766         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9767         if (TI->getOpcode() == FI->getOpcode())
9768           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9769             return IV;
9770
9771         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9772         // even legal for FP.
9773         if ((TI->getOpcode() == Instruction::Sub &&
9774              FI->getOpcode() == Instruction::Add) ||
9775             (TI->getOpcode() == Instruction::FSub &&
9776              FI->getOpcode() == Instruction::FAdd)) {
9777           AddOp = FI; SubOp = TI;
9778         } else if ((FI->getOpcode() == Instruction::Sub &&
9779                     TI->getOpcode() == Instruction::Add) ||
9780                    (FI->getOpcode() == Instruction::FSub &&
9781                     TI->getOpcode() == Instruction::FAdd)) {
9782           AddOp = TI; SubOp = FI;
9783         }
9784
9785         if (AddOp) {
9786           Value *OtherAddOp = 0;
9787           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9788             OtherAddOp = AddOp->getOperand(1);
9789           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9790             OtherAddOp = AddOp->getOperand(0);
9791           }
9792
9793           if (OtherAddOp) {
9794             // So at this point we know we have (Y -> OtherAddOp):
9795             //        select C, (add X, Y), (sub X, Z)
9796             Value *NegVal;  // Compute -Z
9797             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9798               NegVal = ConstantExpr::getNeg(C);
9799             } else {
9800               NegVal = InsertNewInstBefore(
9801                     BinaryOperator::CreateNeg(SubOp->getOperand(1),
9802                                               "tmp"), SI);
9803             }
9804
9805             Value *NewTrueOp = OtherAddOp;
9806             Value *NewFalseOp = NegVal;
9807             if (AddOp != TI)
9808               std::swap(NewTrueOp, NewFalseOp);
9809             Instruction *NewSel =
9810               SelectInst::Create(CondVal, NewTrueOp,
9811                                  NewFalseOp, SI.getName() + ".p");
9812
9813             NewSel = InsertNewInstBefore(NewSel, SI);
9814             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9815           }
9816         }
9817       }
9818
9819   // See if we can fold the select into one of our operands.
9820   if (SI.getType()->isInteger()) {
9821     if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
9822       return FoldI;
9823     
9824     // MAX(MAX(a, b), a) -> MAX(a, b)
9825     // MIN(MIN(a, b), a) -> MIN(a, b)
9826     // MAX(MIN(a, b), a) -> a
9827     // MIN(MAX(a, b), a) -> a
9828     Value *LHS, *RHS, *LHS2, *RHS2;
9829     if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
9830       if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
9831         if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2, 
9832                                           SI, SPF, RHS))
9833           return R;
9834       if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
9835         if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
9836                                           SI, SPF, LHS))
9837           return R;
9838     }
9839
9840     // TODO.
9841     // ABS(-X) -> ABS(X)
9842     // ABS(ABS(X)) -> ABS(X)
9843   }
9844
9845   // See if we can fold the select into a phi node if the condition is a select.
9846   if (isa<PHINode>(SI.getCondition())) 
9847     // The true/false values have to be live in the PHI predecessor's blocks.
9848     if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
9849         CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
9850       if (Instruction *NV = FoldOpIntoPhi(SI))
9851         return NV;
9852
9853   if (BinaryOperator::isNot(CondVal)) {
9854     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9855     SI.setOperand(1, FalseVal);
9856     SI.setOperand(2, TrueVal);
9857     return &SI;
9858   }
9859
9860   return 0;
9861 }
9862
9863 /// EnforceKnownAlignment - If the specified pointer points to an object that
9864 /// we control, modify the object's alignment to PrefAlign. This isn't
9865 /// often possible though. If alignment is important, a more reliable approach
9866 /// is to simply align all global variables and allocation instructions to
9867 /// their preferred alignment from the beginning.
9868 ///
9869 static unsigned EnforceKnownAlignment(Value *V,
9870                                       unsigned Align, unsigned PrefAlign) {
9871
9872   User *U = dyn_cast<User>(V);
9873   if (!U) return Align;
9874
9875   switch (Operator::getOpcode(U)) {
9876   default: break;
9877   case Instruction::BitCast:
9878     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9879   case Instruction::GetElementPtr: {
9880     // If all indexes are zero, it is just the alignment of the base pointer.
9881     bool AllZeroOperands = true;
9882     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9883       if (!isa<Constant>(*i) ||
9884           !cast<Constant>(*i)->isNullValue()) {
9885         AllZeroOperands = false;
9886         break;
9887       }
9888
9889     if (AllZeroOperands) {
9890       // Treat this like a bitcast.
9891       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9892     }
9893     break;
9894   }
9895   }
9896
9897   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9898     // If there is a large requested alignment and we can, bump up the alignment
9899     // of the global.
9900     if (!GV->isDeclaration()) {
9901       if (GV->getAlignment() >= PrefAlign)
9902         Align = GV->getAlignment();
9903       else {
9904         GV->setAlignment(PrefAlign);
9905         Align = PrefAlign;
9906       }
9907     }
9908   } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9909     // If there is a requested alignment and if this is an alloca, round up.
9910     if (AI->getAlignment() >= PrefAlign)
9911       Align = AI->getAlignment();
9912     else {
9913       AI->setAlignment(PrefAlign);
9914       Align = PrefAlign;
9915     }
9916   }
9917
9918   return Align;
9919 }
9920
9921 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9922 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9923 /// and it is more than the alignment of the ultimate object, see if we can
9924 /// increase the alignment of the ultimate object, making this check succeed.
9925 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9926                                                   unsigned PrefAlign) {
9927   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9928                       sizeof(PrefAlign) * CHAR_BIT;
9929   APInt Mask = APInt::getAllOnesValue(BitWidth);
9930   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9931   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9932   unsigned TrailZ = KnownZero.countTrailingOnes();
9933   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9934
9935   if (PrefAlign > Align)
9936     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9937   
9938     // We don't need to make any adjustment.
9939   return Align;
9940 }
9941
9942 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9943   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9944   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9945   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9946   unsigned CopyAlign = MI->getAlignment();
9947
9948   if (CopyAlign < MinAlign) {
9949     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 
9950                                              MinAlign, false));
9951     return MI;
9952   }
9953   
9954   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9955   // load/store.
9956   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9957   if (MemOpLength == 0) return 0;
9958   
9959   // Source and destination pointer types are always "i8*" for intrinsic.  See
9960   // if the size is something we can handle with a single primitive load/store.
9961   // A single load+store correctly handles overlapping memory in the memmove
9962   // case.
9963   unsigned Size = MemOpLength->getZExtValue();
9964   if (Size == 0) return MI;  // Delete this mem transfer.
9965   
9966   if (Size > 8 || (Size&(Size-1)))
9967     return 0;  // If not 1/2/4/8 bytes, exit.
9968   
9969   // Use an integer load+store unless we can find something better.
9970   Type *NewPtrTy =
9971                 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
9972   
9973   // Memcpy forces the use of i8* for the source and destination.  That means
9974   // that if you're using memcpy to move one double around, you'll get a cast
9975   // from double* to i8*.  We'd much rather use a double load+store rather than
9976   // an i64 load+store, here because this improves the odds that the source or
9977   // dest address will be promotable.  See if we can find a better type than the
9978   // integer datatype.
9979   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9980     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9981     if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9982       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9983       // down through these levels if so.
9984       while (!SrcETy->isSingleValueType()) {
9985         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9986           if (STy->getNumElements() == 1)
9987             SrcETy = STy->getElementType(0);
9988           else
9989             break;
9990         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9991           if (ATy->getNumElements() == 1)
9992             SrcETy = ATy->getElementType();
9993           else
9994             break;
9995         } else
9996           break;
9997       }
9998       
9999       if (SrcETy->isSingleValueType())
10000         NewPtrTy = PointerType::getUnqual(SrcETy);
10001     }
10002   }
10003   
10004   
10005   // If the memcpy/memmove provides better alignment info than we can
10006   // infer, use it.
10007   SrcAlign = std::max(SrcAlign, CopyAlign);
10008   DstAlign = std::max(DstAlign, CopyAlign);
10009   
10010   Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
10011   Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
10012   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
10013   InsertNewInstBefore(L, *MI);
10014   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
10015
10016   // Set the size of the copy to 0, it will be deleted on the next iteration.
10017   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
10018   return MI;
10019 }
10020
10021 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
10022   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
10023   if (MI->getAlignment() < Alignment) {
10024     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
10025                                              Alignment, false));
10026     return MI;
10027   }
10028   
10029   // Extract the length and alignment and fill if they are constant.
10030   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
10031   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
10032   if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
10033     return 0;
10034   uint64_t Len = LenC->getZExtValue();
10035   Alignment = MI->getAlignment();
10036   
10037   // If the length is zero, this is a no-op
10038   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
10039   
10040   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
10041   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
10042     const Type *ITy = IntegerType::get(*Context, Len*8);  // n=1 -> i8.
10043     
10044     Value *Dest = MI->getDest();
10045     Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
10046
10047     // Alignment 0 is identity for alignment 1 for memset, but not store.
10048     if (Alignment == 0) Alignment = 1;
10049     
10050     // Extract the fill value and store.
10051     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
10052     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
10053                                       Dest, false, Alignment), *MI);
10054     
10055     // Set the size of the copy to 0, it will be deleted on the next iteration.
10056     MI->setLength(Constant::getNullValue(LenC->getType()));
10057     return MI;
10058   }
10059
10060   return 0;
10061 }
10062
10063
10064 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
10065 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
10066 /// the heavy lifting.
10067 ///
10068 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
10069   if (isFreeCall(&CI))
10070     return visitFree(CI);
10071
10072   // If the caller function is nounwind, mark the call as nounwind, even if the
10073   // callee isn't.
10074   if (CI.getParent()->getParent()->doesNotThrow() &&
10075       !CI.doesNotThrow()) {
10076     CI.setDoesNotThrow();
10077     return &CI;
10078   }
10079   
10080   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
10081   if (!II) return visitCallSite(&CI);
10082   
10083   // Intrinsics cannot occur in an invoke, so handle them here instead of in
10084   // visitCallSite.
10085   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
10086     bool Changed = false;
10087
10088     // memmove/cpy/set of zero bytes is a noop.
10089     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
10090       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
10091
10092       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
10093         if (CI->getZExtValue() == 1) {
10094           // Replace the instruction with just byte operations.  We would
10095           // transform other cases to loads/stores, but we don't know if
10096           // alignment is sufficient.
10097         }
10098     }
10099
10100     // If we have a memmove and the source operation is a constant global,
10101     // then the source and dest pointers can't alias, so we can change this
10102     // into a call to memcpy.
10103     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
10104       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
10105         if (GVSrc->isConstant()) {
10106           Module *M = CI.getParent()->getParent()->getParent();
10107           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
10108           const Type *Tys[1];
10109           Tys[0] = CI.getOperand(3)->getType();
10110           CI.setOperand(0, 
10111                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
10112           Changed = true;
10113         }
10114     }
10115
10116     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
10117       // memmove(x,x,size) -> noop.
10118       if (MTI->getSource() == MTI->getDest())
10119         return EraseInstFromFunction(CI);
10120     }
10121
10122     // If we can determine a pointer alignment that is bigger than currently
10123     // set, update the alignment.
10124     if (isa<MemTransferInst>(MI)) {
10125       if (Instruction *I = SimplifyMemTransfer(MI))
10126         return I;
10127     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
10128       if (Instruction *I = SimplifyMemSet(MSI))
10129         return I;
10130     }
10131           
10132     if (Changed) return II;
10133   }
10134   
10135   switch (II->getIntrinsicID()) {
10136   default: break;
10137   case Intrinsic::bswap:
10138     // bswap(bswap(x)) -> x
10139     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
10140       if (Operand->getIntrinsicID() == Intrinsic::bswap)
10141         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
10142     break;
10143   case Intrinsic::uadd_with_overflow: {
10144     Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
10145     const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
10146     uint32_t BitWidth = IT->getBitWidth();
10147     APInt Mask = APInt::getSignBit(BitWidth);
10148     APInt LHSKnownZero(BitWidth, 0);
10149     APInt LHSKnownOne(BitWidth, 0);
10150     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
10151     bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
10152     bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
10153
10154     if (LHSKnownNegative || LHSKnownPositive) {
10155       APInt RHSKnownZero(BitWidth, 0);
10156       APInt RHSKnownOne(BitWidth, 0);
10157       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
10158       bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
10159       bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
10160       if (LHSKnownNegative && RHSKnownNegative) {
10161         // The sign bit is set in both cases: this MUST overflow.
10162         // Create a simple add instruction, and insert it into the struct.
10163         Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
10164         Worklist.Add(Add);
10165         Constant *V[] = {
10166           UndefValue::get(LHS->getType()), ConstantInt::getTrue(*Context)
10167         };
10168         Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10169         return InsertValueInst::Create(Struct, Add, 0);
10170       }
10171       
10172       if (LHSKnownPositive && RHSKnownPositive) {
10173         // The sign bit is clear in both cases: this CANNOT overflow.
10174         // Create a simple add instruction, and insert it into the struct.
10175         Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
10176         Worklist.Add(Add);
10177         Constant *V[] = {
10178           UndefValue::get(LHS->getType()), ConstantInt::getFalse(*Context)
10179         };
10180         Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10181         return InsertValueInst::Create(Struct, Add, 0);
10182       }
10183     }
10184   }
10185   // FALL THROUGH uadd into sadd
10186   case Intrinsic::sadd_with_overflow:
10187     // Canonicalize constants into the RHS.
10188     if (isa<Constant>(II->getOperand(1)) &&
10189         !isa<Constant>(II->getOperand(2))) {
10190       Value *LHS = II->getOperand(1);
10191       II->setOperand(1, II->getOperand(2));
10192       II->setOperand(2, LHS);
10193       return II;
10194     }
10195
10196     // X + undef -> undef
10197     if (isa<UndefValue>(II->getOperand(2)))
10198       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10199       
10200     if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10201       // X + 0 -> {X, false}
10202       if (RHS->isZero()) {
10203         Constant *V[] = {
10204           UndefValue::get(II->getOperand(0)->getType()),
10205           ConstantInt::getFalse(*Context)
10206         };
10207         Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10208         return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10209       }
10210     }
10211     break;
10212   case Intrinsic::usub_with_overflow:
10213   case Intrinsic::ssub_with_overflow:
10214     // undef - X -> undef
10215     // X - undef -> undef
10216     if (isa<UndefValue>(II->getOperand(1)) ||
10217         isa<UndefValue>(II->getOperand(2)))
10218       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10219       
10220     if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10221       // X - 0 -> {X, false}
10222       if (RHS->isZero()) {
10223         Constant *V[] = {
10224           UndefValue::get(II->getOperand(1)->getType()),
10225           ConstantInt::getFalse(*Context)
10226         };
10227         Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10228         return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10229       }
10230     }
10231     break;
10232   case Intrinsic::umul_with_overflow:
10233   case Intrinsic::smul_with_overflow:
10234     // Canonicalize constants into the RHS.
10235     if (isa<Constant>(II->getOperand(1)) &&
10236         !isa<Constant>(II->getOperand(2))) {
10237       Value *LHS = II->getOperand(1);
10238       II->setOperand(1, II->getOperand(2));
10239       II->setOperand(2, LHS);
10240       return II;
10241     }
10242
10243     // X * undef -> undef
10244     if (isa<UndefValue>(II->getOperand(2)))
10245       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10246       
10247     if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
10248       // X*0 -> {0, false}
10249       if (RHSI->isZero())
10250         return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
10251       
10252       // X * 1 -> {X, false}
10253       if (RHSI->equalsInt(1)) {
10254         Constant *V[] = {
10255           UndefValue::get(II->getOperand(1)->getType()),
10256           ConstantInt::getFalse(*Context)
10257         };
10258         Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10259         return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10260       }
10261     }
10262     break;
10263   case Intrinsic::ppc_altivec_lvx:
10264   case Intrinsic::ppc_altivec_lvxl:
10265   case Intrinsic::x86_sse_loadu_ps:
10266   case Intrinsic::x86_sse2_loadu_pd:
10267   case Intrinsic::x86_sse2_loadu_dq:
10268     // Turn PPC lvx     -> load if the pointer is known aligned.
10269     // Turn X86 loadups -> load if the pointer is known aligned.
10270     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
10271       Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
10272                                          PointerType::getUnqual(II->getType()));
10273       return new LoadInst(Ptr);
10274     }
10275     break;
10276   case Intrinsic::ppc_altivec_stvx:
10277   case Intrinsic::ppc_altivec_stvxl:
10278     // Turn stvx -> store if the pointer is known aligned.
10279     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
10280       const Type *OpPtrTy = 
10281         PointerType::getUnqual(II->getOperand(1)->getType());
10282       Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
10283       return new StoreInst(II->getOperand(1), Ptr);
10284     }
10285     break;
10286   case Intrinsic::x86_sse_storeu_ps:
10287   case Intrinsic::x86_sse2_storeu_pd:
10288   case Intrinsic::x86_sse2_storeu_dq:
10289     // Turn X86 storeu -> store if the pointer is known aligned.
10290     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
10291       const Type *OpPtrTy = 
10292         PointerType::getUnqual(II->getOperand(2)->getType());
10293       Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
10294       return new StoreInst(II->getOperand(2), Ptr);
10295     }
10296     break;
10297     
10298   case Intrinsic::x86_sse_cvttss2si: {
10299     // These intrinsics only demands the 0th element of its input vector.  If
10300     // we can simplify the input based on that, do so now.
10301     unsigned VWidth =
10302       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
10303     APInt DemandedElts(VWidth, 1);
10304     APInt UndefElts(VWidth, 0);
10305     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
10306                                               UndefElts)) {
10307       II->setOperand(1, V);
10308       return II;
10309     }
10310     break;
10311   }
10312     
10313   case Intrinsic::ppc_altivec_vperm:
10314     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
10315     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
10316       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
10317       
10318       // Check that all of the elements are integer constants or undefs.
10319       bool AllEltsOk = true;
10320       for (unsigned i = 0; i != 16; ++i) {
10321         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
10322             !isa<UndefValue>(Mask->getOperand(i))) {
10323           AllEltsOk = false;
10324           break;
10325         }
10326       }
10327       
10328       if (AllEltsOk) {
10329         // Cast the input vectors to byte vectors.
10330         Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
10331         Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
10332         Value *Result = UndefValue::get(Op0->getType());
10333         
10334         // Only extract each element once.
10335         Value *ExtractedElts[32];
10336         memset(ExtractedElts, 0, sizeof(ExtractedElts));
10337         
10338         for (unsigned i = 0; i != 16; ++i) {
10339           if (isa<UndefValue>(Mask->getOperand(i)))
10340             continue;
10341           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
10342           Idx &= 31;  // Match the hardware behavior.
10343           
10344           if (ExtractedElts[Idx] == 0) {
10345             ExtractedElts[Idx] = 
10346               Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1, 
10347                   ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
10348                                             "tmp");
10349           }
10350         
10351           // Insert this value into the result vector.
10352           Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
10353                          ConstantInt::get(Type::getInt32Ty(*Context), i, false),
10354                                                 "tmp");
10355         }
10356         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
10357       }
10358     }
10359     break;
10360
10361   case Intrinsic::stackrestore: {
10362     // If the save is right next to the restore, remove the restore.  This can
10363     // happen when variable allocas are DCE'd.
10364     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10365       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10366         BasicBlock::iterator BI = SS;
10367         if (&*++BI == II)
10368           return EraseInstFromFunction(CI);
10369       }
10370     }
10371     
10372     // Scan down this block to see if there is another stack restore in the
10373     // same block without an intervening call/alloca.
10374     BasicBlock::iterator BI = II;
10375     TerminatorInst *TI = II->getParent()->getTerminator();
10376     bool CannotRemove = false;
10377     for (++BI; &*BI != TI; ++BI) {
10378       if (isa<AllocaInst>(BI) || isMalloc(BI)) {
10379         CannotRemove = true;
10380         break;
10381       }
10382       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10383         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10384           // If there is a stackrestore below this one, remove this one.
10385           if (II->getIntrinsicID() == Intrinsic::stackrestore)
10386             return EraseInstFromFunction(CI);
10387           // Otherwise, ignore the intrinsic.
10388         } else {
10389           // If we found a non-intrinsic call, we can't remove the stack
10390           // restore.
10391           CannotRemove = true;
10392           break;
10393         }
10394       }
10395     }
10396     
10397     // If the stack restore is in a return/unwind block and if there are no
10398     // allocas or calls between the restore and the return, nuke the restore.
10399     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10400       return EraseInstFromFunction(CI);
10401     break;
10402   }
10403   }
10404
10405   return visitCallSite(II);
10406 }
10407
10408 // InvokeInst simplification
10409 //
10410 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10411   return visitCallSite(&II);
10412 }
10413
10414 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
10415 /// passed through the varargs area, we can eliminate the use of the cast.
10416 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10417                                          const CastInst * const CI,
10418                                          const TargetData * const TD,
10419                                          const int ix) {
10420   if (!CI->isLosslessCast())
10421     return false;
10422
10423   // The size of ByVal arguments is derived from the type, so we
10424   // can't change to a type with a different size.  If the size were
10425   // passed explicitly we could avoid this check.
10426   if (!CS.paramHasAttr(ix, Attribute::ByVal))
10427     return true;
10428
10429   const Type* SrcTy = 
10430             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10431   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10432   if (!SrcTy->isSized() || !DstTy->isSized())
10433     return false;
10434   if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10435     return false;
10436   return true;
10437 }
10438
10439 // visitCallSite - Improvements for call and invoke instructions.
10440 //
10441 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10442   bool Changed = false;
10443
10444   // If the callee is a constexpr cast of a function, attempt to move the cast
10445   // to the arguments of the call/invoke.
10446   if (transformConstExprCastCall(CS)) return 0;
10447
10448   Value *Callee = CS.getCalledValue();
10449
10450   if (Function *CalleeF = dyn_cast<Function>(Callee))
10451     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10452       Instruction *OldCall = CS.getInstruction();
10453       // If the call and callee calling conventions don't match, this call must
10454       // be unreachable, as the call is undefined.
10455       new StoreInst(ConstantInt::getTrue(*Context),
10456                 UndefValue::get(Type::getInt1PtrTy(*Context)), 
10457                                   OldCall);
10458       // If OldCall dues not return void then replaceAllUsesWith undef.
10459       // This allows ValueHandlers and custom metadata to adjust itself.
10460       if (!OldCall->getType()->isVoidTy())
10461         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
10462       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10463         return EraseInstFromFunction(*OldCall);
10464       return 0;
10465     }
10466
10467   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10468     // This instruction is not reachable, just remove it.  We insert a store to
10469     // undef so that we know that this code is not reachable, despite the fact
10470     // that we can't modify the CFG here.
10471     new StoreInst(ConstantInt::getTrue(*Context),
10472                UndefValue::get(Type::getInt1PtrTy(*Context)),
10473                   CS.getInstruction());
10474
10475     // If CS dues not return void then replaceAllUsesWith undef.
10476     // This allows ValueHandlers and custom metadata to adjust itself.
10477     if (!CS.getInstruction()->getType()->isVoidTy())
10478       CS.getInstruction()->
10479         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
10480
10481     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10482       // Don't break the CFG, insert a dummy cond branch.
10483       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10484                          ConstantInt::getTrue(*Context), II);
10485     }
10486     return EraseInstFromFunction(*CS.getInstruction());
10487   }
10488
10489   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10490     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10491       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10492         return transformCallThroughTrampoline(CS);
10493
10494   const PointerType *PTy = cast<PointerType>(Callee->getType());
10495   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10496   if (FTy->isVarArg()) {
10497     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10498     // See if we can optimize any arguments passed through the varargs area of
10499     // the call.
10500     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10501            E = CS.arg_end(); I != E; ++I, ++ix) {
10502       CastInst *CI = dyn_cast<CastInst>(*I);
10503       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10504         *I = CI->getOperand(0);
10505         Changed = true;
10506       }
10507     }
10508   }
10509
10510   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10511     // Inline asm calls cannot throw - mark them 'nounwind'.
10512     CS.setDoesNotThrow();
10513     Changed = true;
10514   }
10515
10516   return Changed ? CS.getInstruction() : 0;
10517 }
10518
10519 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10520 // attempt to move the cast to the arguments of the call/invoke.
10521 //
10522 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10523   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10524   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10525   if (CE->getOpcode() != Instruction::BitCast || 
10526       !isa<Function>(CE->getOperand(0)))
10527     return false;
10528   Function *Callee = cast<Function>(CE->getOperand(0));
10529   Instruction *Caller = CS.getInstruction();
10530   const AttrListPtr &CallerPAL = CS.getAttributes();
10531
10532   // Okay, this is a cast from a function to a different type.  Unless doing so
10533   // would cause a type conversion of one of our arguments, change this call to
10534   // be a direct call with arguments casted to the appropriate types.
10535   //
10536   const FunctionType *FT = Callee->getFunctionType();
10537   const Type *OldRetTy = Caller->getType();
10538   const Type *NewRetTy = FT->getReturnType();
10539
10540   if (isa<StructType>(NewRetTy))
10541     return false; // TODO: Handle multiple return values.
10542
10543   // Check to see if we are changing the return type...
10544   if (OldRetTy != NewRetTy) {
10545     if (Callee->isDeclaration() &&
10546         // Conversion is ok if changing from one pointer type to another or from
10547         // a pointer to an integer of the same size.
10548         !((isa<PointerType>(OldRetTy) || !TD ||
10549            OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
10550           (isa<PointerType>(NewRetTy) || !TD ||
10551            NewRetTy == TD->getIntPtrType(Caller->getContext()))))
10552       return false;   // Cannot transform this return value.
10553
10554     if (!Caller->use_empty() &&
10555         // void -> non-void is handled specially
10556         !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
10557       return false;   // Cannot transform this return value.
10558
10559     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10560       Attributes RAttrs = CallerPAL.getRetAttributes();
10561       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10562         return false;   // Attribute not compatible with transformed value.
10563     }
10564
10565     // If the callsite is an invoke instruction, and the return value is used by
10566     // a PHI node in a successor, we cannot change the return type of the call
10567     // because there is no place to put the cast instruction (without breaking
10568     // the critical edge).  Bail out in this case.
10569     if (!Caller->use_empty())
10570       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10571         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10572              UI != E; ++UI)
10573           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10574             if (PN->getParent() == II->getNormalDest() ||
10575                 PN->getParent() == II->getUnwindDest())
10576               return false;
10577   }
10578
10579   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10580   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10581
10582   CallSite::arg_iterator AI = CS.arg_begin();
10583   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10584     const Type *ParamTy = FT->getParamType(i);
10585     const Type *ActTy = (*AI)->getType();
10586
10587     if (!CastInst::isCastable(ActTy, ParamTy))
10588       return false;   // Cannot transform this parameter value.
10589
10590     if (CallerPAL.getParamAttributes(i + 1) 
10591         & Attribute::typeIncompatible(ParamTy))
10592       return false;   // Attribute not compatible with transformed value.
10593
10594     // Converting from one pointer type to another or between a pointer and an
10595     // integer of the same size is safe even if we do not have a body.
10596     bool isConvertible = ActTy == ParamTy ||
10597       (TD && ((isa<PointerType>(ParamTy) ||
10598       ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10599               (isa<PointerType>(ActTy) ||
10600               ActTy == TD->getIntPtrType(Caller->getContext()))));
10601     if (Callee->isDeclaration() && !isConvertible) return false;
10602   }
10603
10604   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10605       Callee->isDeclaration())
10606     return false;   // Do not delete arguments unless we have a function body.
10607
10608   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10609       !CallerPAL.isEmpty())
10610     // In this case we have more arguments than the new function type, but we
10611     // won't be dropping them.  Check that these extra arguments have attributes
10612     // that are compatible with being a vararg call argument.
10613     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10614       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10615         break;
10616       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10617       if (PAttrs & Attribute::VarArgsIncompatible)
10618         return false;
10619     }
10620
10621   // Okay, we decided that this is a safe thing to do: go ahead and start
10622   // inserting cast instructions as necessary...
10623   std::vector<Value*> Args;
10624   Args.reserve(NumActualArgs);
10625   SmallVector<AttributeWithIndex, 8> attrVec;
10626   attrVec.reserve(NumCommonArgs);
10627
10628   // Get any return attributes.
10629   Attributes RAttrs = CallerPAL.getRetAttributes();
10630
10631   // If the return value is not being used, the type may not be compatible
10632   // with the existing attributes.  Wipe out any problematic attributes.
10633   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10634
10635   // Add the new return attributes.
10636   if (RAttrs)
10637     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10638
10639   AI = CS.arg_begin();
10640   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10641     const Type *ParamTy = FT->getParamType(i);
10642     if ((*AI)->getType() == ParamTy) {
10643       Args.push_back(*AI);
10644     } else {
10645       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10646           false, ParamTy, false);
10647       Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
10648     }
10649
10650     // Add any parameter attributes.
10651     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10652       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10653   }
10654
10655   // If the function takes more arguments than the call was taking, add them
10656   // now.
10657   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10658     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10659
10660   // If we are removing arguments to the function, emit an obnoxious warning.
10661   if (FT->getNumParams() < NumActualArgs) {
10662     if (!FT->isVarArg()) {
10663       errs() << "WARNING: While resolving call to function '"
10664              << Callee->getName() << "' arguments were dropped!\n";
10665     } else {
10666       // Add all of the arguments in their promoted form to the arg list.
10667       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10668         const Type *PTy = getPromotedType((*AI)->getType());
10669         if (PTy != (*AI)->getType()) {
10670           // Must promote to pass through va_arg area!
10671           Instruction::CastOps opcode =
10672             CastInst::getCastOpcode(*AI, false, PTy, false);
10673           Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
10674         } else {
10675           Args.push_back(*AI);
10676         }
10677
10678         // Add any parameter attributes.
10679         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10680           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10681       }
10682     }
10683   }
10684
10685   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10686     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10687
10688   if (NewRetTy->isVoidTy())
10689     Caller->setName("");   // Void type should not have a name.
10690
10691   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10692                                                      attrVec.end());
10693
10694   Instruction *NC;
10695   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10696     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10697                             Args.begin(), Args.end(),
10698                             Caller->getName(), Caller);
10699     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10700     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10701   } else {
10702     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10703                           Caller->getName(), Caller);
10704     CallInst *CI = cast<CallInst>(Caller);
10705     if (CI->isTailCall())
10706       cast<CallInst>(NC)->setTailCall();
10707     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10708     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10709   }
10710
10711   // Insert a cast of the return type as necessary.
10712   Value *NV = NC;
10713   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10714     if (!NV->getType()->isVoidTy()) {
10715       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10716                                                             OldRetTy, false);
10717       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10718
10719       // If this is an invoke instruction, we should insert it after the first
10720       // non-phi, instruction in the normal successor block.
10721       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10722         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10723         InsertNewInstBefore(NC, *I);
10724       } else {
10725         // Otherwise, it's a call, just insert cast right after the call instr
10726         InsertNewInstBefore(NC, *Caller);
10727       }
10728       Worklist.AddUsersToWorkList(*Caller);
10729     } else {
10730       NV = UndefValue::get(Caller->getType());
10731     }
10732   }
10733
10734
10735   if (!Caller->use_empty())
10736     Caller->replaceAllUsesWith(NV);
10737   
10738   EraseInstFromFunction(*Caller);
10739   return true;
10740 }
10741
10742 // transformCallThroughTrampoline - Turn a call to a function created by the
10743 // init_trampoline intrinsic into a direct call to the underlying function.
10744 //
10745 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10746   Value *Callee = CS.getCalledValue();
10747   const PointerType *PTy = cast<PointerType>(Callee->getType());
10748   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10749   const AttrListPtr &Attrs = CS.getAttributes();
10750
10751   // If the call already has the 'nest' attribute somewhere then give up -
10752   // otherwise 'nest' would occur twice after splicing in the chain.
10753   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10754     return 0;
10755
10756   IntrinsicInst *Tramp =
10757     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10758
10759   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10760   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10761   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10762
10763   const AttrListPtr &NestAttrs = NestF->getAttributes();
10764   if (!NestAttrs.isEmpty()) {
10765     unsigned NestIdx = 1;
10766     const Type *NestTy = 0;
10767     Attributes NestAttr = Attribute::None;
10768
10769     // Look for a parameter marked with the 'nest' attribute.
10770     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10771          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10772       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10773         // Record the parameter type and any other attributes.
10774         NestTy = *I;
10775         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10776         break;
10777       }
10778
10779     if (NestTy) {
10780       Instruction *Caller = CS.getInstruction();
10781       std::vector<Value*> NewArgs;
10782       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10783
10784       SmallVector<AttributeWithIndex, 8> NewAttrs;
10785       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10786
10787       // Insert the nest argument into the call argument list, which may
10788       // mean appending it.  Likewise for attributes.
10789
10790       // Add any result attributes.
10791       if (Attributes Attr = Attrs.getRetAttributes())
10792         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10793
10794       {
10795         unsigned Idx = 1;
10796         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10797         do {
10798           if (Idx == NestIdx) {
10799             // Add the chain argument and attributes.
10800             Value *NestVal = Tramp->getOperand(3);
10801             if (NestVal->getType() != NestTy)
10802               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10803             NewArgs.push_back(NestVal);
10804             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10805           }
10806
10807           if (I == E)
10808             break;
10809
10810           // Add the original argument and attributes.
10811           NewArgs.push_back(*I);
10812           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10813             NewAttrs.push_back
10814               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10815
10816           ++Idx, ++I;
10817         } while (1);
10818       }
10819
10820       // Add any function attributes.
10821       if (Attributes Attr = Attrs.getFnAttributes())
10822         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10823
10824       // The trampoline may have been bitcast to a bogus type (FTy).
10825       // Handle this by synthesizing a new function type, equal to FTy
10826       // with the chain parameter inserted.
10827
10828       std::vector<const Type*> NewTypes;
10829       NewTypes.reserve(FTy->getNumParams()+1);
10830
10831       // Insert the chain's type into the list of parameter types, which may
10832       // mean appending it.
10833       {
10834         unsigned Idx = 1;
10835         FunctionType::param_iterator I = FTy->param_begin(),
10836           E = FTy->param_end();
10837
10838         do {
10839           if (Idx == NestIdx)
10840             // Add the chain's type.
10841             NewTypes.push_back(NestTy);
10842
10843           if (I == E)
10844             break;
10845
10846           // Add the original type.
10847           NewTypes.push_back(*I);
10848
10849           ++Idx, ++I;
10850         } while (1);
10851       }
10852
10853       // Replace the trampoline call with a direct call.  Let the generic
10854       // code sort out any function type mismatches.
10855       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 
10856                                                 FTy->isVarArg());
10857       Constant *NewCallee =
10858         NestF->getType() == PointerType::getUnqual(NewFTy) ?
10859         NestF : ConstantExpr::getBitCast(NestF, 
10860                                          PointerType::getUnqual(NewFTy));
10861       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10862                                                    NewAttrs.end());
10863
10864       Instruction *NewCaller;
10865       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10866         NewCaller = InvokeInst::Create(NewCallee,
10867                                        II->getNormalDest(), II->getUnwindDest(),
10868                                        NewArgs.begin(), NewArgs.end(),
10869                                        Caller->getName(), Caller);
10870         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10871         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10872       } else {
10873         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10874                                      Caller->getName(), Caller);
10875         if (cast<CallInst>(Caller)->isTailCall())
10876           cast<CallInst>(NewCaller)->setTailCall();
10877         cast<CallInst>(NewCaller)->
10878           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10879         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10880       }
10881       if (!Caller->getType()->isVoidTy())
10882         Caller->replaceAllUsesWith(NewCaller);
10883       Caller->eraseFromParent();
10884       Worklist.Remove(Caller);
10885       return 0;
10886     }
10887   }
10888
10889   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10890   // parameter, there is no need to adjust the argument list.  Let the generic
10891   // code sort out any function type mismatches.
10892   Constant *NewCallee =
10893     NestF->getType() == PTy ? NestF : 
10894                               ConstantExpr::getBitCast(NestF, PTy);
10895   CS.setCalledFunction(NewCallee);
10896   return CS.getInstruction();
10897 }
10898
10899 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10900 /// and if a/b/c and the add's all have a single use, turn this into a phi
10901 /// and a single binop.
10902 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10903   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10904   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10905   unsigned Opc = FirstInst->getOpcode();
10906   Value *LHSVal = FirstInst->getOperand(0);
10907   Value *RHSVal = FirstInst->getOperand(1);
10908     
10909   const Type *LHSType = LHSVal->getType();
10910   const Type *RHSType = RHSVal->getType();
10911   
10912   // Scan to see if all operands are the same opcode, and all have one use.
10913   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10914     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10915     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10916         // Verify type of the LHS matches so we don't fold cmp's of different
10917         // types or GEP's with different index types.
10918         I->getOperand(0)->getType() != LHSType ||
10919         I->getOperand(1)->getType() != RHSType)
10920       return 0;
10921
10922     // If they are CmpInst instructions, check their predicates
10923     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10924       if (cast<CmpInst>(I)->getPredicate() !=
10925           cast<CmpInst>(FirstInst)->getPredicate())
10926         return 0;
10927     
10928     // Keep track of which operand needs a phi node.
10929     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10930     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10931   }
10932
10933   // If both LHS and RHS would need a PHI, don't do this transformation,
10934   // because it would increase the number of PHIs entering the block,
10935   // which leads to higher register pressure. This is especially
10936   // bad when the PHIs are in the header of a loop.
10937   if (!LHSVal && !RHSVal)
10938     return 0;
10939   
10940   // Otherwise, this is safe to transform!
10941   
10942   Value *InLHS = FirstInst->getOperand(0);
10943   Value *InRHS = FirstInst->getOperand(1);
10944   PHINode *NewLHS = 0, *NewRHS = 0;
10945   if (LHSVal == 0) {
10946     NewLHS = PHINode::Create(LHSType,
10947                              FirstInst->getOperand(0)->getName() + ".pn");
10948     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10949     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10950     InsertNewInstBefore(NewLHS, PN);
10951     LHSVal = NewLHS;
10952   }
10953   
10954   if (RHSVal == 0) {
10955     NewRHS = PHINode::Create(RHSType,
10956                              FirstInst->getOperand(1)->getName() + ".pn");
10957     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10958     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10959     InsertNewInstBefore(NewRHS, PN);
10960     RHSVal = NewRHS;
10961   }
10962   
10963   // Add all operands to the new PHIs.
10964   if (NewLHS || NewRHS) {
10965     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10966       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10967       if (NewLHS) {
10968         Value *NewInLHS = InInst->getOperand(0);
10969         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10970       }
10971       if (NewRHS) {
10972         Value *NewInRHS = InInst->getOperand(1);
10973         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10974       }
10975     }
10976   }
10977     
10978   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10979     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10980   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10981   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10982                          LHSVal, RHSVal);
10983 }
10984
10985 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10986   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10987   
10988   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10989                                         FirstInst->op_end());
10990   // This is true if all GEP bases are allocas and if all indices into them are
10991   // constants.
10992   bool AllBasePointersAreAllocas = true;
10993
10994   // We don't want to replace this phi if the replacement would require
10995   // more than one phi, which leads to higher register pressure. This is
10996   // especially bad when the PHIs are in the header of a loop.
10997   bool NeededPhi = false;
10998   
10999   // Scan to see if all operands are the same opcode, and all have one use.
11000   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
11001     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
11002     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
11003       GEP->getNumOperands() != FirstInst->getNumOperands())
11004       return 0;
11005
11006     // Keep track of whether or not all GEPs are of alloca pointers.
11007     if (AllBasePointersAreAllocas &&
11008         (!isa<AllocaInst>(GEP->getOperand(0)) ||
11009          !GEP->hasAllConstantIndices()))
11010       AllBasePointersAreAllocas = false;
11011     
11012     // Compare the operand lists.
11013     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
11014       if (FirstInst->getOperand(op) == GEP->getOperand(op))
11015         continue;
11016       
11017       // Don't merge two GEPs when two operands differ (introducing phi nodes)
11018       // if one of the PHIs has a constant for the index.  The index may be
11019       // substantially cheaper to compute for the constants, so making it a
11020       // variable index could pessimize the path.  This also handles the case
11021       // for struct indices, which must always be constant.
11022       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
11023           isa<ConstantInt>(GEP->getOperand(op)))
11024         return 0;
11025       
11026       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
11027         return 0;
11028
11029       // If we already needed a PHI for an earlier operand, and another operand
11030       // also requires a PHI, we'd be introducing more PHIs than we're
11031       // eliminating, which increases register pressure on entry to the PHI's
11032       // block.
11033       if (NeededPhi)
11034         return 0;
11035
11036       FixedOperands[op] = 0;  // Needs a PHI.
11037       NeededPhi = true;
11038     }
11039   }
11040   
11041   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
11042   // bother doing this transformation.  At best, this will just save a bit of
11043   // offset calculation, but all the predecessors will have to materialize the
11044   // stack address into a register anyway.  We'd actually rather *clone* the
11045   // load up into the predecessors so that we have a load of a gep of an alloca,
11046   // which can usually all be folded into the load.
11047   if (AllBasePointersAreAllocas)
11048     return 0;
11049   
11050   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
11051   // that is variable.
11052   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
11053   
11054   bool HasAnyPHIs = false;
11055   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
11056     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
11057     Value *FirstOp = FirstInst->getOperand(i);
11058     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
11059                                      FirstOp->getName()+".pn");
11060     InsertNewInstBefore(NewPN, PN);
11061     
11062     NewPN->reserveOperandSpace(e);
11063     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
11064     OperandPhis[i] = NewPN;
11065     FixedOperands[i] = NewPN;
11066     HasAnyPHIs = true;
11067   }
11068
11069   
11070   // Add all operands to the new PHIs.
11071   if (HasAnyPHIs) {
11072     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11073       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
11074       BasicBlock *InBB = PN.getIncomingBlock(i);
11075       
11076       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
11077         if (PHINode *OpPhi = OperandPhis[op])
11078           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
11079     }
11080   }
11081   
11082   Value *Base = FixedOperands[0];
11083   return cast<GEPOperator>(FirstInst)->isInBounds() ?
11084     GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
11085                                       FixedOperands.end()) :
11086     GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
11087                               FixedOperands.end());
11088 }
11089
11090
11091 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
11092 /// sink the load out of the block that defines it.  This means that it must be
11093 /// obvious the value of the load is not changed from the point of the load to
11094 /// the end of the block it is in.
11095 ///
11096 /// Finally, it is safe, but not profitable, to sink a load targetting a
11097 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
11098 /// to a register.
11099 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
11100   BasicBlock::iterator BBI = L, E = L->getParent()->end();
11101   
11102   for (++BBI; BBI != E; ++BBI)
11103     if (BBI->mayWriteToMemory())
11104       return false;
11105   
11106   // Check for non-address taken alloca.  If not address-taken already, it isn't
11107   // profitable to do this xform.
11108   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
11109     bool isAddressTaken = false;
11110     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
11111          UI != E; ++UI) {
11112       if (isa<LoadInst>(UI)) continue;
11113       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
11114         // If storing TO the alloca, then the address isn't taken.
11115         if (SI->getOperand(1) == AI) continue;
11116       }
11117       isAddressTaken = true;
11118       break;
11119     }
11120     
11121     if (!isAddressTaken && AI->isStaticAlloca())
11122       return false;
11123   }
11124   
11125   // If this load is a load from a GEP with a constant offset from an alloca,
11126   // then we don't want to sink it.  In its present form, it will be
11127   // load [constant stack offset].  Sinking it will cause us to have to
11128   // materialize the stack addresses in each predecessor in a register only to
11129   // do a shared load from register in the successor.
11130   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
11131     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
11132       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
11133         return false;
11134   
11135   return true;
11136 }
11137
11138 Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
11139   LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
11140   
11141   // When processing loads, we need to propagate two bits of information to the
11142   // sunk load: whether it is volatile, and what its alignment is.  We currently
11143   // don't sink loads when some have their alignment specified and some don't.
11144   // visitLoadInst will propagate an alignment onto the load when TD is around,
11145   // and if TD isn't around, we can't handle the mixed case.
11146   bool isVolatile = FirstLI->isVolatile();
11147   unsigned LoadAlignment = FirstLI->getAlignment();
11148   
11149   // We can't sink the load if the loaded value could be modified between the
11150   // load and the PHI.
11151   if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
11152       !isSafeAndProfitableToSinkLoad(FirstLI))
11153     return 0;
11154   
11155   // If the PHI is of volatile loads and the load block has multiple
11156   // successors, sinking it would remove a load of the volatile value from
11157   // the path through the other successor.
11158   if (isVolatile && 
11159       FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
11160     return 0;
11161   
11162   // Check to see if all arguments are the same operation.
11163   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11164     LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
11165     if (!LI || !LI->hasOneUse())
11166       return 0;
11167     
11168     // We can't sink the load if the loaded value could be modified between 
11169     // the load and the PHI.
11170     if (LI->isVolatile() != isVolatile ||
11171         LI->getParent() != PN.getIncomingBlock(i) ||
11172         !isSafeAndProfitableToSinkLoad(LI))
11173       return 0;
11174       
11175     // If some of the loads have an alignment specified but not all of them,
11176     // we can't do the transformation.
11177     if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
11178       return 0;
11179     
11180     LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
11181     
11182     // If the PHI is of volatile loads and the load block has multiple
11183     // successors, sinking it would remove a load of the volatile value from
11184     // the path through the other successor.
11185     if (isVolatile &&
11186         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
11187       return 0;
11188   }
11189   
11190   // Okay, they are all the same operation.  Create a new PHI node of the
11191   // correct type, and PHI together all of the LHS's of the instructions.
11192   PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
11193                                    PN.getName()+".in");
11194   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
11195   
11196   Value *InVal = FirstLI->getOperand(0);
11197   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
11198   
11199   // Add all operands to the new PHI.
11200   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11201     Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
11202     if (NewInVal != InVal)
11203       InVal = 0;
11204     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11205   }
11206   
11207   Value *PhiVal;
11208   if (InVal) {
11209     // The new PHI unions all of the same values together.  This is really
11210     // common, so we handle it intelligently here for compile-time speed.
11211     PhiVal = InVal;
11212     delete NewPN;
11213   } else {
11214     InsertNewInstBefore(NewPN, PN);
11215     PhiVal = NewPN;
11216   }
11217   
11218   // If this was a volatile load that we are merging, make sure to loop through
11219   // and mark all the input loads as non-volatile.  If we don't do this, we will
11220   // insert a new volatile load and the old ones will not be deletable.
11221   if (isVolatile)
11222     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
11223       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
11224   
11225   return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
11226 }
11227
11228
11229
11230 /// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
11231 /// operator and they all are only used by the PHI, PHI together their
11232 /// inputs, and do the operation once, to the result of the PHI.
11233 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
11234   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
11235
11236   if (isa<GetElementPtrInst>(FirstInst))
11237     return FoldPHIArgGEPIntoPHI(PN);
11238   if (isa<LoadInst>(FirstInst))
11239     return FoldPHIArgLoadIntoPHI(PN);
11240   
11241   // Scan the instruction, looking for input operations that can be folded away.
11242   // If all input operands to the phi are the same instruction (e.g. a cast from
11243   // the same type or "+42") we can pull the operation through the PHI, reducing
11244   // code size and simplifying code.
11245   Constant *ConstantOp = 0;
11246   const Type *CastSrcTy = 0;
11247   
11248   if (isa<CastInst>(FirstInst)) {
11249     CastSrcTy = FirstInst->getOperand(0)->getType();
11250
11251     // Be careful about transforming integer PHIs.  We don't want to pessimize
11252     // the code by turning an i32 into an i1293.
11253     if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
11254       if (!ShouldChangeType(PN.getType(), CastSrcTy, TD))
11255         return 0;
11256     }
11257   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
11258     // Can fold binop, compare or shift here if the RHS is a constant, 
11259     // otherwise call FoldPHIArgBinOpIntoPHI.
11260     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
11261     if (ConstantOp == 0)
11262       return FoldPHIArgBinOpIntoPHI(PN);
11263   } else {
11264     return 0;  // Cannot fold this operation.
11265   }
11266
11267   // Check to see if all arguments are the same operation.
11268   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11269     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
11270     if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
11271       return 0;
11272     if (CastSrcTy) {
11273       if (I->getOperand(0)->getType() != CastSrcTy)
11274         return 0;  // Cast operation must match.
11275     } else if (I->getOperand(1) != ConstantOp) {
11276       return 0;
11277     }
11278   }
11279
11280   // Okay, they are all the same operation.  Create a new PHI node of the
11281   // correct type, and PHI together all of the LHS's of the instructions.
11282   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
11283                                    PN.getName()+".in");
11284   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
11285
11286   Value *InVal = FirstInst->getOperand(0);
11287   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
11288
11289   // Add all operands to the new PHI.
11290   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11291     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
11292     if (NewInVal != InVal)
11293       InVal = 0;
11294     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11295   }
11296
11297   Value *PhiVal;
11298   if (InVal) {
11299     // The new PHI unions all of the same values together.  This is really
11300     // common, so we handle it intelligently here for compile-time speed.
11301     PhiVal = InVal;
11302     delete NewPN;
11303   } else {
11304     InsertNewInstBefore(NewPN, PN);
11305     PhiVal = NewPN;
11306   }
11307
11308   // Insert and return the new operation.
11309   if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
11310     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
11311   
11312   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
11313     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
11314   
11315   CmpInst *CIOp = cast<CmpInst>(FirstInst);
11316   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
11317                          PhiVal, ConstantOp);
11318 }
11319
11320 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
11321 /// that is dead.
11322 static bool DeadPHICycle(PHINode *PN,
11323                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
11324   if (PN->use_empty()) return true;
11325   if (!PN->hasOneUse()) return false;
11326
11327   // Remember this node, and if we find the cycle, return.
11328   if (!PotentiallyDeadPHIs.insert(PN))
11329     return true;
11330   
11331   // Don't scan crazily complex things.
11332   if (PotentiallyDeadPHIs.size() == 16)
11333     return false;
11334
11335   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
11336     return DeadPHICycle(PU, PotentiallyDeadPHIs);
11337
11338   return false;
11339 }
11340
11341 /// PHIsEqualValue - Return true if this phi node is always equal to
11342 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
11343 ///   z = some value; x = phi (y, z); y = phi (x, z)
11344 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
11345                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
11346   // See if we already saw this PHI node.
11347   if (!ValueEqualPHIs.insert(PN))
11348     return true;
11349   
11350   // Don't scan crazily complex things.
11351   if (ValueEqualPHIs.size() == 16)
11352     return false;
11353  
11354   // Scan the operands to see if they are either phi nodes or are equal to
11355   // the value.
11356   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11357     Value *Op = PN->getIncomingValue(i);
11358     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
11359       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
11360         return false;
11361     } else if (Op != NonPhiInVal)
11362       return false;
11363   }
11364   
11365   return true;
11366 }
11367
11368
11369 namespace {
11370 struct PHIUsageRecord {
11371   unsigned PHIId;     // The ID # of the PHI (something determinstic to sort on)
11372   unsigned Shift;     // The amount shifted.
11373   Instruction *Inst;  // The trunc instruction.
11374   
11375   PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
11376     : PHIId(pn), Shift(Sh), Inst(User) {}
11377   
11378   bool operator<(const PHIUsageRecord &RHS) const {
11379     if (PHIId < RHS.PHIId) return true;
11380     if (PHIId > RHS.PHIId) return false;
11381     if (Shift < RHS.Shift) return true;
11382     if (Shift > RHS.Shift) return false;
11383     return Inst->getType()->getPrimitiveSizeInBits() <
11384            RHS.Inst->getType()->getPrimitiveSizeInBits();
11385   }
11386 };
11387   
11388 struct LoweredPHIRecord {
11389   PHINode *PN;        // The PHI that was lowered.
11390   unsigned Shift;     // The amount shifted.
11391   unsigned Width;     // The width extracted.
11392   
11393   LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
11394     : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
11395   
11396   // Ctor form used by DenseMap.
11397   LoweredPHIRecord(PHINode *pn, unsigned Sh)
11398     : PN(pn), Shift(Sh), Width(0) {}
11399 };
11400 }
11401
11402 namespace llvm {
11403   template<>
11404   struct DenseMapInfo<LoweredPHIRecord> {
11405     static inline LoweredPHIRecord getEmptyKey() {
11406       return LoweredPHIRecord(0, 0);
11407     }
11408     static inline LoweredPHIRecord getTombstoneKey() {
11409       return LoweredPHIRecord(0, 1);
11410     }
11411     static unsigned getHashValue(const LoweredPHIRecord &Val) {
11412       return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
11413              (Val.Width>>3);
11414     }
11415     static bool isEqual(const LoweredPHIRecord &LHS,
11416                         const LoweredPHIRecord &RHS) {
11417       return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
11418              LHS.Width == RHS.Width;
11419     }
11420   };
11421   template <>
11422   struct isPodLike<LoweredPHIRecord> { static const bool value = true; };
11423 }
11424
11425
11426 /// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
11427 /// illegal type: see if it is only used by trunc or trunc(lshr) operations.  If
11428 /// so, we split the PHI into the various pieces being extracted.  This sort of
11429 /// thing is introduced when SROA promotes an aggregate to large integer values.
11430 ///
11431 /// TODO: The user of the trunc may be an bitcast to float/double/vector or an
11432 /// inttoptr.  We should produce new PHIs in the right type.
11433 ///
11434 Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
11435   // PHIUsers - Keep track of all of the truncated values extracted from a set
11436   // of PHIs, along with their offset.  These are the things we want to rewrite.
11437   SmallVector<PHIUsageRecord, 16> PHIUsers;
11438   
11439   // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
11440   // nodes which are extracted from. PHIsToSlice is a set we use to avoid
11441   // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
11442   // check the uses of (to ensure they are all extracts).
11443   SmallVector<PHINode*, 8> PHIsToSlice;
11444   SmallPtrSet<PHINode*, 8> PHIsInspected;
11445   
11446   PHIsToSlice.push_back(&FirstPhi);
11447   PHIsInspected.insert(&FirstPhi);
11448   
11449   for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
11450     PHINode *PN = PHIsToSlice[PHIId];
11451     
11452     // Scan the input list of the PHI.  If any input is an invoke, and if the
11453     // input is defined in the predecessor, then we won't be split the critical
11454     // edge which is required to insert a truncate.  Because of this, we have to
11455     // bail out.
11456     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11457       InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
11458       if (II == 0) continue;
11459       if (II->getParent() != PN->getIncomingBlock(i))
11460         continue;
11461      
11462       // If we have a phi, and if it's directly in the predecessor, then we have
11463       // a critical edge where we need to put the truncate.  Since we can't
11464       // split the edge in instcombine, we have to bail out.
11465       return 0;
11466     }
11467       
11468     
11469     for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
11470          UI != E; ++UI) {
11471       Instruction *User = cast<Instruction>(*UI);
11472       
11473       // If the user is a PHI, inspect its uses recursively.
11474       if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
11475         if (PHIsInspected.insert(UserPN))
11476           PHIsToSlice.push_back(UserPN);
11477         continue;
11478       }
11479       
11480       // Truncates are always ok.
11481       if (isa<TruncInst>(User)) {
11482         PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
11483         continue;
11484       }
11485       
11486       // Otherwise it must be a lshr which can only be used by one trunc.
11487       if (User->getOpcode() != Instruction::LShr ||
11488           !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
11489           !isa<ConstantInt>(User->getOperand(1)))
11490         return 0;
11491       
11492       unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
11493       PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
11494     }
11495   }
11496   
11497   // If we have no users, they must be all self uses, just nuke the PHI.
11498   if (PHIUsers.empty())
11499     return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
11500   
11501   // If this phi node is transformable, create new PHIs for all the pieces
11502   // extracted out of it.  First, sort the users by their offset and size.
11503   array_pod_sort(PHIUsers.begin(), PHIUsers.end());
11504   
11505   DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
11506             for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11507               errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
11508         );
11509   
11510   // PredValues - This is a temporary used when rewriting PHI nodes.  It is
11511   // hoisted out here to avoid construction/destruction thrashing.
11512   DenseMap<BasicBlock*, Value*> PredValues;
11513   
11514   // ExtractedVals - Each new PHI we introduce is saved here so we don't
11515   // introduce redundant PHIs.
11516   DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
11517   
11518   for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
11519     unsigned PHIId = PHIUsers[UserI].PHIId;
11520     PHINode *PN = PHIsToSlice[PHIId];
11521     unsigned Offset = PHIUsers[UserI].Shift;
11522     const Type *Ty = PHIUsers[UserI].Inst->getType();
11523     
11524     PHINode *EltPHI;
11525     
11526     // If we've already lowered a user like this, reuse the previously lowered
11527     // value.
11528     if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
11529       
11530       // Otherwise, Create the new PHI node for this user.
11531       EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
11532       assert(EltPHI->getType() != PN->getType() &&
11533              "Truncate didn't shrink phi?");
11534     
11535       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11536         BasicBlock *Pred = PN->getIncomingBlock(i);
11537         Value *&PredVal = PredValues[Pred];
11538         
11539         // If we already have a value for this predecessor, reuse it.
11540         if (PredVal) {
11541           EltPHI->addIncoming(PredVal, Pred);
11542           continue;
11543         }
11544
11545         // Handle the PHI self-reuse case.
11546         Value *InVal = PN->getIncomingValue(i);
11547         if (InVal == PN) {
11548           PredVal = EltPHI;
11549           EltPHI->addIncoming(PredVal, Pred);
11550           continue;
11551         }
11552         
11553         if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
11554           // If the incoming value was a PHI, and if it was one of the PHIs we
11555           // already rewrote it, just use the lowered value.
11556           if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
11557             PredVal = Res;
11558             EltPHI->addIncoming(PredVal, Pred);
11559             continue;
11560           }
11561         }
11562         
11563         // Otherwise, do an extract in the predecessor.
11564         Builder->SetInsertPoint(Pred, Pred->getTerminator());
11565         Value *Res = InVal;
11566         if (Offset)
11567           Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
11568                                                           Offset), "extract");
11569         Res = Builder->CreateTrunc(Res, Ty, "extract.t");
11570         PredVal = Res;
11571         EltPHI->addIncoming(Res, Pred);
11572         
11573         // If the incoming value was a PHI, and if it was one of the PHIs we are
11574         // rewriting, we will ultimately delete the code we inserted.  This
11575         // means we need to revisit that PHI to make sure we extract out the
11576         // needed piece.
11577         if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
11578           if (PHIsInspected.count(OldInVal)) {
11579             unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
11580                                           OldInVal)-PHIsToSlice.begin();
11581             PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset, 
11582                                               cast<Instruction>(Res)));
11583             ++UserE;
11584           }
11585       }
11586       PredValues.clear();
11587       
11588       DEBUG(errs() << "  Made element PHI for offset " << Offset << ": "
11589                    << *EltPHI << '\n');
11590       ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
11591     }
11592     
11593     // Replace the use of this piece with the PHI node.
11594     ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
11595   }
11596   
11597   // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
11598   // with undefs.
11599   Value *Undef = UndefValue::get(FirstPhi.getType());
11600   for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11601     ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
11602   return ReplaceInstUsesWith(FirstPhi, Undef);
11603 }
11604
11605 // PHINode simplification
11606 //
11607 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
11608   // If LCSSA is around, don't mess with Phi nodes
11609   if (MustPreserveLCSSA) return 0;
11610   
11611   if (Value *V = PN.hasConstantValue())
11612     return ReplaceInstUsesWith(PN, V);
11613
11614   // If all PHI operands are the same operation, pull them through the PHI,
11615   // reducing code size.
11616   if (isa<Instruction>(PN.getIncomingValue(0)) &&
11617       isa<Instruction>(PN.getIncomingValue(1)) &&
11618       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
11619       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
11620       // FIXME: The hasOneUse check will fail for PHIs that use the value more
11621       // than themselves more than once.
11622       PN.getIncomingValue(0)->hasOneUse())
11623     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
11624       return Result;
11625
11626   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
11627   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
11628   // PHI)... break the cycle.
11629   if (PN.hasOneUse()) {
11630     Instruction *PHIUser = cast<Instruction>(PN.use_back());
11631     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
11632       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
11633       PotentiallyDeadPHIs.insert(&PN);
11634       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
11635         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
11636     }
11637    
11638     // If this phi has a single use, and if that use just computes a value for
11639     // the next iteration of a loop, delete the phi.  This occurs with unused
11640     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
11641     // common case here is good because the only other things that catch this
11642     // are induction variable analysis (sometimes) and ADCE, which is only run
11643     // late.
11644     if (PHIUser->hasOneUse() &&
11645         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
11646         PHIUser->use_back() == &PN) {
11647       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
11648     }
11649   }
11650
11651   // We sometimes end up with phi cycles that non-obviously end up being the
11652   // same value, for example:
11653   //   z = some value; x = phi (y, z); y = phi (x, z)
11654   // where the phi nodes don't necessarily need to be in the same block.  Do a
11655   // quick check to see if the PHI node only contains a single non-phi value, if
11656   // so, scan to see if the phi cycle is actually equal to that value.
11657   {
11658     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
11659     // Scan for the first non-phi operand.
11660     while (InValNo != NumOperandVals && 
11661            isa<PHINode>(PN.getIncomingValue(InValNo)))
11662       ++InValNo;
11663
11664     if (InValNo != NumOperandVals) {
11665       Value *NonPhiInVal = PN.getOperand(InValNo);
11666       
11667       // Scan the rest of the operands to see if there are any conflicts, if so
11668       // there is no need to recursively scan other phis.
11669       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11670         Value *OpVal = PN.getIncomingValue(InValNo);
11671         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11672           break;
11673       }
11674       
11675       // If we scanned over all operands, then we have one unique value plus
11676       // phi values.  Scan PHI nodes to see if they all merge in each other or
11677       // the value.
11678       if (InValNo == NumOperandVals) {
11679         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11680         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11681           return ReplaceInstUsesWith(PN, NonPhiInVal);
11682       }
11683     }
11684   }
11685
11686   // If there are multiple PHIs, sort their operands so that they all list
11687   // the blocks in the same order. This will help identical PHIs be eliminated
11688   // by other passes. Other passes shouldn't depend on this for correctness
11689   // however.
11690   PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
11691   if (&PN != FirstPN)
11692     for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
11693       BasicBlock *BBA = PN.getIncomingBlock(i);
11694       BasicBlock *BBB = FirstPN->getIncomingBlock(i);
11695       if (BBA != BBB) {
11696         Value *VA = PN.getIncomingValue(i);
11697         unsigned j = PN.getBasicBlockIndex(BBB);
11698         Value *VB = PN.getIncomingValue(j);
11699         PN.setIncomingBlock(i, BBB);
11700         PN.setIncomingValue(i, VB);
11701         PN.setIncomingBlock(j, BBA);
11702         PN.setIncomingValue(j, VA);
11703         // NOTE: Instcombine normally would want us to "return &PN" if we
11704         // modified any of the operands of an instruction.  However, since we
11705         // aren't adding or removing uses (just rearranging them) we don't do
11706         // this in this case.
11707       }
11708     }
11709
11710   // If this is an integer PHI and we know that it has an illegal type, see if
11711   // it is only used by trunc or trunc(lshr) operations.  If so, we split the
11712   // PHI into the various pieces being extracted.  This sort of thing is
11713   // introduced when SROA promotes an aggregate to a single large integer type.
11714   if (isa<IntegerType>(PN.getType()) && TD &&
11715       !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
11716     if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
11717       return Res;
11718   
11719   return 0;
11720 }
11721
11722 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
11723   SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
11724
11725   if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
11726     return ReplaceInstUsesWith(GEP, V);
11727
11728   Value *PtrOp = GEP.getOperand(0);
11729
11730   if (isa<UndefValue>(GEP.getOperand(0)))
11731     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
11732
11733   // Eliminate unneeded casts for indices.
11734   if (TD) {
11735     bool MadeChange = false;
11736     unsigned PtrSize = TD->getPointerSizeInBits();
11737     
11738     gep_type_iterator GTI = gep_type_begin(GEP);
11739     for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11740          I != E; ++I, ++GTI) {
11741       if (!isa<SequentialType>(*GTI)) continue;
11742       
11743       // If we are using a wider index than needed for this platform, shrink it
11744       // to what we need.  If narrower, sign-extend it to what we need.  This
11745       // explicit cast can make subsequent optimizations more obvious.
11746       unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
11747       if (OpBits == PtrSize)
11748         continue;
11749       
11750       *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
11751       MadeChange = true;
11752     }
11753     if (MadeChange) return &GEP;
11754   }
11755
11756   // Combine Indices - If the source pointer to this getelementptr instruction
11757   // is a getelementptr instruction, combine the indices of the two
11758   // getelementptr instructions into a single instruction.
11759   //
11760   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
11761     // Note that if our source is a gep chain itself that we wait for that
11762     // chain to be resolved before we perform this transformation.  This
11763     // avoids us creating a TON of code in some cases.
11764     //
11765     if (GetElementPtrInst *SrcGEP =
11766           dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11767       if (SrcGEP->getNumOperands() == 2)
11768         return 0;   // Wait until our source is folded to completion.
11769
11770     SmallVector<Value*, 8> Indices;
11771
11772     // Find out whether the last index in the source GEP is a sequential idx.
11773     bool EndsWithSequential = false;
11774     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11775          I != E; ++I)
11776       EndsWithSequential = !isa<StructType>(*I);
11777
11778     // Can we combine the two pointer arithmetics offsets?
11779     if (EndsWithSequential) {
11780       // Replace: gep (gep %P, long B), long A, ...
11781       // With:    T = long A+B; gep %P, T, ...
11782       //
11783       Value *Sum;
11784       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11785       Value *GO1 = GEP.getOperand(1);
11786       if (SO1 == Constant::getNullValue(SO1->getType())) {
11787         Sum = GO1;
11788       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
11789         Sum = SO1;
11790       } else {
11791         // If they aren't the same type, then the input hasn't been processed
11792         // by the loop above yet (which canonicalizes sequential index types to
11793         // intptr_t).  Just avoid transforming this until the input has been
11794         // normalized.
11795         if (SO1->getType() != GO1->getType())
11796           return 0;
11797         Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11798       }
11799
11800       // Update the GEP in place if possible.
11801       if (Src->getNumOperands() == 2) {
11802         GEP.setOperand(0, Src->getOperand(0));
11803         GEP.setOperand(1, Sum);
11804         return &GEP;
11805       }
11806       Indices.append(Src->op_begin()+1, Src->op_end()-1);
11807       Indices.push_back(Sum);
11808       Indices.append(GEP.op_begin()+2, GEP.op_end());
11809     } else if (isa<Constant>(*GEP.idx_begin()) &&
11810                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11811                Src->getNumOperands() != 1) {
11812       // Otherwise we can do the fold if the first index of the GEP is a zero
11813       Indices.append(Src->op_begin()+1, Src->op_end());
11814       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
11815     }
11816
11817     if (!Indices.empty())
11818       return (cast<GEPOperator>(&GEP)->isInBounds() &&
11819               Src->isInBounds()) ?
11820         GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11821                                           Indices.end(), GEP.getName()) :
11822         GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
11823                                   Indices.end(), GEP.getName());
11824   }
11825   
11826   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11827   if (Value *X = getBitCastOperand(PtrOp)) {
11828     assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
11829
11830     // If the input bitcast is actually "bitcast(bitcast(x))", then we don't 
11831     // want to change the gep until the bitcasts are eliminated.
11832     if (getBitCastOperand(X)) {
11833       Worklist.AddValue(PtrOp);
11834       return 0;
11835     }
11836     
11837     bool HasZeroPointerIndex = false;
11838     if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
11839       HasZeroPointerIndex = C->isZero();
11840     
11841     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11842     // into     : GEP [10 x i8]* X, i32 0, ...
11843     //
11844     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11845     //           into     : GEP i8* X, ...
11846     // 
11847     // This occurs when the program declares an array extern like "int X[];"
11848     if (HasZeroPointerIndex) {
11849       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11850       const PointerType *XTy = cast<PointerType>(X->getType());
11851       if (const ArrayType *CATy =
11852           dyn_cast<ArrayType>(CPTy->getElementType())) {
11853         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11854         if (CATy->getElementType() == XTy->getElementType()) {
11855           // -> GEP i8* X, ...
11856           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11857           return cast<GEPOperator>(&GEP)->isInBounds() ?
11858             GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11859                                               GEP.getName()) :
11860             GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11861                                       GEP.getName());
11862         }
11863         
11864         if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
11865           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11866           if (CATy->getElementType() == XATy->getElementType()) {
11867             // -> GEP [10 x i8]* X, i32 0, ...
11868             // At this point, we know that the cast source type is a pointer
11869             // to an array of the same type as the destination pointer
11870             // array.  Because the array type is never stepped over (there
11871             // is a leading zero) we can fold the cast into this GEP.
11872             GEP.setOperand(0, X);
11873             return &GEP;
11874           }
11875         }
11876       }
11877     } else if (GEP.getNumOperands() == 2) {
11878       // Transform things like:
11879       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11880       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11881       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11882       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11883       if (TD && isa<ArrayType>(SrcElTy) &&
11884           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11885           TD->getTypeAllocSize(ResElTy)) {
11886         Value *Idx[2];
11887         Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11888         Idx[1] = GEP.getOperand(1);
11889         Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11890           Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11891           Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11892         // V and GEP are both pointer types --> BitCast
11893         return new BitCastInst(NewGEP, GEP.getType());
11894       }
11895       
11896       // Transform things like:
11897       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11898       //   (where tmp = 8*tmp2) into:
11899       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11900       
11901       if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
11902         uint64_t ArrayEltSize =
11903             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11904         
11905         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11906         // allow either a mul, shift, or constant here.
11907         Value *NewIdx = 0;
11908         ConstantInt *Scale = 0;
11909         if (ArrayEltSize == 1) {
11910           NewIdx = GEP.getOperand(1);
11911           Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11912         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11913           NewIdx = ConstantInt::get(CI->getType(), 1);
11914           Scale = CI;
11915         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11916           if (Inst->getOpcode() == Instruction::Shl &&
11917               isa<ConstantInt>(Inst->getOperand(1))) {
11918             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11919             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11920             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11921                                      1ULL << ShAmtVal);
11922             NewIdx = Inst->getOperand(0);
11923           } else if (Inst->getOpcode() == Instruction::Mul &&
11924                      isa<ConstantInt>(Inst->getOperand(1))) {
11925             Scale = cast<ConstantInt>(Inst->getOperand(1));
11926             NewIdx = Inst->getOperand(0);
11927           }
11928         }
11929         
11930         // If the index will be to exactly the right offset with the scale taken
11931         // out, perform the transformation. Note, we don't know whether Scale is
11932         // signed or not. We'll use unsigned version of division/modulo
11933         // operation after making sure Scale doesn't have the sign bit set.
11934         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11935             Scale->getZExtValue() % ArrayEltSize == 0) {
11936           Scale = ConstantInt::get(Scale->getType(),
11937                                    Scale->getZExtValue() / ArrayEltSize);
11938           if (Scale->getZExtValue() != 1) {
11939             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11940                                                        false /*ZExt*/);
11941             NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
11942           }
11943
11944           // Insert the new GEP instruction.
11945           Value *Idx[2];
11946           Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11947           Idx[1] = NewIdx;
11948           Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11949             Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11950             Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11951           // The NewGEP must be pointer typed, so must the old one -> BitCast
11952           return new BitCastInst(NewGEP, GEP.getType());
11953         }
11954       }
11955     }
11956   }
11957   
11958   /// See if we can simplify:
11959   ///   X = bitcast A* to B*
11960   ///   Y = gep X, <...constant indices...>
11961   /// into a gep of the original struct.  This is important for SROA and alias
11962   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11963   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11964     if (TD &&
11965         !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11966       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11967       // a constant back from EmitGEPOffset.
11968       ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, *this));
11969       int64_t Offset = OffsetV->getSExtValue();
11970       
11971       // If this GEP instruction doesn't move the pointer, just replace the GEP
11972       // with a bitcast of the real input to the dest type.
11973       if (Offset == 0) {
11974         // If the bitcast is of an allocation, and the allocation will be
11975         // converted to match the type of the cast, don't touch this.
11976         if (isa<AllocaInst>(BCI->getOperand(0)) ||
11977             isMalloc(BCI->getOperand(0))) {
11978           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11979           if (Instruction *I = visitBitCast(*BCI)) {
11980             if (I != BCI) {
11981               I->takeName(BCI);
11982               BCI->getParent()->getInstList().insert(BCI, I);
11983               ReplaceInstUsesWith(*BCI, I);
11984             }
11985             return &GEP;
11986           }
11987         }
11988         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11989       }
11990       
11991       // Otherwise, if the offset is non-zero, we need to find out if there is a
11992       // field at Offset in 'A's type.  If so, we can pull the cast through the
11993       // GEP.
11994       SmallVector<Value*, 8> NewIndices;
11995       const Type *InTy =
11996         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11997       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11998         Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11999           Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
12000                                      NewIndices.end()) :
12001           Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
12002                              NewIndices.end());
12003         
12004         if (NGEP->getType() == GEP.getType())
12005           return ReplaceInstUsesWith(GEP, NGEP);
12006         NGEP->takeName(&GEP);
12007         return new BitCastInst(NGEP, GEP.getType());
12008       }
12009     }
12010   }    
12011     
12012   return 0;
12013 }
12014
12015 Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
12016   // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
12017   if (AI.isArrayAllocation()) {  // Check C != 1
12018     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
12019       const Type *NewTy = 
12020         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
12021       assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
12022       AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
12023       New->setAlignment(AI.getAlignment());
12024
12025       // Scan to the end of the allocation instructions, to skip over a block of
12026       // allocas if possible...also skip interleaved debug info
12027       //
12028       BasicBlock::iterator It = New;
12029       while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
12030
12031       // Now that I is pointing to the first non-allocation-inst in the block,
12032       // insert our getelementptr instruction...
12033       //
12034       Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
12035       Value *Idx[2];
12036       Idx[0] = NullIdx;
12037       Idx[1] = NullIdx;
12038       Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
12039                                                    New->getName()+".sub", It);
12040
12041       // Now make everything use the getelementptr instead of the original
12042       // allocation.
12043       return ReplaceInstUsesWith(AI, V);
12044     } else if (isa<UndefValue>(AI.getArraySize())) {
12045       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
12046     }
12047   }
12048
12049   if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
12050     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
12051     // Note that we only do this for alloca's, because malloc should allocate
12052     // and return a unique pointer, even for a zero byte allocation.
12053     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
12054       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
12055
12056     // If the alignment is 0 (unspecified), assign it the preferred alignment.
12057     if (AI.getAlignment() == 0)
12058       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
12059   }
12060
12061   return 0;
12062 }
12063
12064 Instruction *InstCombiner::visitFree(Instruction &FI) {
12065   Value *Op = FI.getOperand(1);
12066
12067   // free undef -> unreachable.
12068   if (isa<UndefValue>(Op)) {
12069     // Insert a new store to null because we cannot modify the CFG here.
12070     new StoreInst(ConstantInt::getTrue(*Context),
12071            UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
12072     return EraseInstFromFunction(FI);
12073   }
12074   
12075   // If we have 'free null' delete the instruction.  This can happen in stl code
12076   // when lots of inlining happens.
12077   if (isa<ConstantPointerNull>(Op))
12078     return EraseInstFromFunction(FI);
12079
12080   // If we have a malloc call whose only use is a free call, delete both.
12081   if (isMalloc(Op)) {
12082     if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
12083       if (Op->hasOneUse() && CI->hasOneUse()) {
12084         EraseInstFromFunction(FI);
12085         EraseInstFromFunction(*CI);
12086         return EraseInstFromFunction(*cast<Instruction>(Op));
12087       }
12088     } else {
12089       // Op is a call to malloc
12090       if (Op->hasOneUse()) {
12091         EraseInstFromFunction(FI);
12092         return EraseInstFromFunction(*cast<Instruction>(Op));
12093       }
12094     }
12095   }
12096
12097   return 0;
12098 }
12099
12100 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
12101 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
12102                                         const TargetData *TD) {
12103   User *CI = cast<User>(LI.getOperand(0));
12104   Value *CastOp = CI->getOperand(0);
12105   LLVMContext *Context = IC.getContext();
12106
12107   const PointerType *DestTy = cast<PointerType>(CI->getType());
12108   const Type *DestPTy = DestTy->getElementType();
12109   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
12110
12111     // If the address spaces don't match, don't eliminate the cast.
12112     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
12113       return 0;
12114
12115     const Type *SrcPTy = SrcTy->getElementType();
12116
12117     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
12118          isa<VectorType>(DestPTy)) {
12119       // If the source is an array, the code below will not succeed.  Check to
12120       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
12121       // constants.
12122       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
12123         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
12124           if (ASrcTy->getNumElements() != 0) {
12125             Value *Idxs[2];
12126             Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
12127             Idxs[1] = Idxs[0];
12128             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
12129             SrcTy = cast<PointerType>(CastOp->getType());
12130             SrcPTy = SrcTy->getElementType();
12131           }
12132
12133       if (IC.getTargetData() &&
12134           (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
12135             isa<VectorType>(SrcPTy)) &&
12136           // Do not allow turning this into a load of an integer, which is then
12137           // casted to a pointer, this pessimizes pointer analysis a lot.
12138           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
12139           IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
12140                IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
12141
12142         // Okay, we are casting from one integer or pointer type to another of
12143         // the same size.  Instead of casting the pointer before the load, cast
12144         // the result of the loaded value.
12145         Value *NewLoad = 
12146           IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
12147         // Now cast the result of the load.
12148         return new BitCastInst(NewLoad, LI.getType());
12149       }
12150     }
12151   }
12152   return 0;
12153 }
12154
12155 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
12156   Value *Op = LI.getOperand(0);
12157
12158   // Attempt to improve the alignment.
12159   if (TD) {
12160     unsigned KnownAlign =
12161       GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
12162     if (KnownAlign >
12163         (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
12164                                   LI.getAlignment()))
12165       LI.setAlignment(KnownAlign);
12166   }
12167
12168   // load (cast X) --> cast (load X) iff safe.
12169   if (isa<CastInst>(Op))
12170     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
12171       return Res;
12172
12173   // None of the following transforms are legal for volatile loads.
12174   if (LI.isVolatile()) return 0;
12175   
12176   // Do really simple store-to-load forwarding and load CSE, to catch cases
12177   // where there are several consequtive memory accesses to the same location,
12178   // separated by a few arithmetic operations.
12179   BasicBlock::iterator BBI = &LI;
12180   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
12181     return ReplaceInstUsesWith(LI, AvailableVal);
12182
12183   // load(gep null, ...) -> unreachable
12184   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
12185     const Value *GEPI0 = GEPI->getOperand(0);
12186     // TODO: Consider a target hook for valid address spaces for this xform.
12187     if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
12188       // Insert a new store to null instruction before the load to indicate
12189       // that this code is not reachable.  We do this instead of inserting
12190       // an unreachable instruction directly because we cannot modify the
12191       // CFG.
12192       new StoreInst(UndefValue::get(LI.getType()),
12193                     Constant::getNullValue(Op->getType()), &LI);
12194       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
12195     }
12196   } 
12197
12198   // load null/undef -> unreachable
12199   // TODO: Consider a target hook for valid address spaces for this xform.
12200   if (isa<UndefValue>(Op) ||
12201       (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
12202     // Insert a new store to null instruction before the load to indicate that
12203     // this code is not reachable.  We do this instead of inserting an
12204     // unreachable instruction directly because we cannot modify the CFG.
12205     new StoreInst(UndefValue::get(LI.getType()),
12206                   Constant::getNullValue(Op->getType()), &LI);
12207     return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
12208   }
12209
12210   // Instcombine load (constantexpr_cast global) -> cast (load global)
12211   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
12212     if (CE->isCast())
12213       if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
12214         return Res;
12215   
12216   if (Op->hasOneUse()) {
12217     // Change select and PHI nodes to select values instead of addresses: this
12218     // helps alias analysis out a lot, allows many others simplifications, and
12219     // exposes redundancy in the code.
12220     //
12221     // Note that we cannot do the transformation unless we know that the
12222     // introduced loads cannot trap!  Something like this is valid as long as
12223     // the condition is always false: load (select bool %C, int* null, int* %G),
12224     // but it would not be valid if we transformed it to load from null
12225     // unconditionally.
12226     //
12227     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
12228       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
12229       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
12230           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
12231         Value *V1 = Builder->CreateLoad(SI->getOperand(1),
12232                                         SI->getOperand(1)->getName()+".val");
12233         Value *V2 = Builder->CreateLoad(SI->getOperand(2),
12234                                         SI->getOperand(2)->getName()+".val");
12235         return SelectInst::Create(SI->getCondition(), V1, V2);
12236       }
12237
12238       // load (select (cond, null, P)) -> load P
12239       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
12240         if (C->isNullValue()) {
12241           LI.setOperand(0, SI->getOperand(2));
12242           return &LI;
12243         }
12244
12245       // load (select (cond, P, null)) -> load P
12246       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
12247         if (C->isNullValue()) {
12248           LI.setOperand(0, SI->getOperand(1));
12249           return &LI;
12250         }
12251     }
12252   }
12253   return 0;
12254 }
12255
12256 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
12257 /// when possible.  This makes it generally easy to do alias analysis and/or
12258 /// SROA/mem2reg of the memory object.
12259 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
12260   User *CI = cast<User>(SI.getOperand(1));
12261   Value *CastOp = CI->getOperand(0);
12262
12263   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
12264   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
12265   if (SrcTy == 0) return 0;
12266   
12267   const Type *SrcPTy = SrcTy->getElementType();
12268
12269   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
12270     return 0;
12271   
12272   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
12273   /// to its first element.  This allows us to handle things like:
12274   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
12275   /// on 32-bit hosts.
12276   SmallVector<Value*, 4> NewGEPIndices;
12277   
12278   // If the source is an array, the code below will not succeed.  Check to
12279   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
12280   // constants.
12281   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
12282     // Index through pointer.
12283     Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
12284     NewGEPIndices.push_back(Zero);
12285     
12286     while (1) {
12287       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
12288         if (!STy->getNumElements()) /* Struct can be empty {} */
12289           break;
12290         NewGEPIndices.push_back(Zero);
12291         SrcPTy = STy->getElementType(0);
12292       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
12293         NewGEPIndices.push_back(Zero);
12294         SrcPTy = ATy->getElementType();
12295       } else {
12296         break;
12297       }
12298     }
12299     
12300     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
12301   }
12302
12303   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
12304     return 0;
12305   
12306   // If the pointers point into different address spaces or if they point to
12307   // values with different sizes, we can't do the transformation.
12308   if (!IC.getTargetData() ||
12309       SrcTy->getAddressSpace() != 
12310         cast<PointerType>(CI->getType())->getAddressSpace() ||
12311       IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
12312       IC.getTargetData()->getTypeSizeInBits(DestPTy))
12313     return 0;
12314
12315   // Okay, we are casting from one integer or pointer type to another of
12316   // the same size.  Instead of casting the pointer before 
12317   // the store, cast the value to be stored.
12318   Value *NewCast;
12319   Value *SIOp0 = SI.getOperand(0);
12320   Instruction::CastOps opcode = Instruction::BitCast;
12321   const Type* CastSrcTy = SIOp0->getType();
12322   const Type* CastDstTy = SrcPTy;
12323   if (isa<PointerType>(CastDstTy)) {
12324     if (CastSrcTy->isInteger())
12325       opcode = Instruction::IntToPtr;
12326   } else if (isa<IntegerType>(CastDstTy)) {
12327     if (isa<PointerType>(SIOp0->getType()))
12328       opcode = Instruction::PtrToInt;
12329   }
12330   
12331   // SIOp0 is a pointer to aggregate and this is a store to the first field,
12332   // emit a GEP to index into its first field.
12333   if (!NewGEPIndices.empty())
12334     CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
12335                                            NewGEPIndices.end());
12336   
12337   NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
12338                                    SIOp0->getName()+".c");
12339   return new StoreInst(NewCast, CastOp);
12340 }
12341
12342 /// equivalentAddressValues - Test if A and B will obviously have the same
12343 /// value. This includes recognizing that %t0 and %t1 will have the same
12344 /// value in code like this:
12345 ///   %t0 = getelementptr \@a, 0, 3
12346 ///   store i32 0, i32* %t0
12347 ///   %t1 = getelementptr \@a, 0, 3
12348 ///   %t2 = load i32* %t1
12349 ///
12350 static bool equivalentAddressValues(Value *A, Value *B) {
12351   // Test if the values are trivially equivalent.
12352   if (A == B) return true;
12353   
12354   // Test if the values come form identical arithmetic instructions.
12355   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
12356   // its only used to compare two uses within the same basic block, which
12357   // means that they'll always either have the same value or one of them
12358   // will have an undefined value.
12359   if (isa<BinaryOperator>(A) ||
12360       isa<CastInst>(A) ||
12361       isa<PHINode>(A) ||
12362       isa<GetElementPtrInst>(A))
12363     if (Instruction *BI = dyn_cast<Instruction>(B))
12364       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
12365         return true;
12366   
12367   // Otherwise they may not be equivalent.
12368   return false;
12369 }
12370
12371 // If this instruction has two uses, one of which is a llvm.dbg.declare,
12372 // return the llvm.dbg.declare.
12373 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
12374   if (!V->hasNUses(2))
12375     return 0;
12376   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
12377        UI != E; ++UI) {
12378     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
12379       return DI;
12380     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
12381       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
12382         return DI;
12383       }
12384   }
12385   return 0;
12386 }
12387
12388 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
12389   Value *Val = SI.getOperand(0);
12390   Value *Ptr = SI.getOperand(1);
12391
12392   // If the RHS is an alloca with a single use, zapify the store, making the
12393   // alloca dead.
12394   // If the RHS is an alloca with a two uses, the other one being a 
12395   // llvm.dbg.declare, zapify the store and the declare, making the
12396   // alloca dead.  We must do this to prevent declare's from affecting
12397   // codegen.
12398   if (!SI.isVolatile()) {
12399     if (Ptr->hasOneUse()) {
12400       if (isa<AllocaInst>(Ptr)) {
12401         EraseInstFromFunction(SI);
12402         ++NumCombined;
12403         return 0;
12404       }
12405       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
12406         if (isa<AllocaInst>(GEP->getOperand(0))) {
12407           if (GEP->getOperand(0)->hasOneUse()) {
12408             EraseInstFromFunction(SI);
12409             ++NumCombined;
12410             return 0;
12411           }
12412           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
12413             EraseInstFromFunction(*DI);
12414             EraseInstFromFunction(SI);
12415             ++NumCombined;
12416             return 0;
12417           }
12418         }
12419       }
12420     }
12421     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
12422       EraseInstFromFunction(*DI);
12423       EraseInstFromFunction(SI);
12424       ++NumCombined;
12425       return 0;
12426     }
12427   }
12428
12429   // Attempt to improve the alignment.
12430   if (TD) {
12431     unsigned KnownAlign =
12432       GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
12433     if (KnownAlign >
12434         (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
12435                                   SI.getAlignment()))
12436       SI.setAlignment(KnownAlign);
12437   }
12438
12439   // Do really simple DSE, to catch cases where there are several consecutive
12440   // stores to the same location, separated by a few arithmetic operations. This
12441   // situation often occurs with bitfield accesses.
12442   BasicBlock::iterator BBI = &SI;
12443   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
12444        --ScanInsts) {
12445     --BBI;
12446     // Don't count debug info directives, lest they affect codegen,
12447     // and we skip pointer-to-pointer bitcasts, which are NOPs.
12448     // It is necessary for correctness to skip those that feed into a
12449     // llvm.dbg.declare, as these are not present when debugging is off.
12450     if (isa<DbgInfoIntrinsic>(BBI) ||
12451         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12452       ScanInsts++;
12453       continue;
12454     }    
12455     
12456     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
12457       // Prev store isn't volatile, and stores to the same location?
12458       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
12459                                                           SI.getOperand(1))) {
12460         ++NumDeadStore;
12461         ++BBI;
12462         EraseInstFromFunction(*PrevSI);
12463         continue;
12464       }
12465       break;
12466     }
12467     
12468     // If this is a load, we have to stop.  However, if the loaded value is from
12469     // the pointer we're loading and is producing the pointer we're storing,
12470     // then *this* store is dead (X = load P; store X -> P).
12471     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
12472       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
12473           !SI.isVolatile()) {
12474         EraseInstFromFunction(SI);
12475         ++NumCombined;
12476         return 0;
12477       }
12478       // Otherwise, this is a load from some other location.  Stores before it
12479       // may not be dead.
12480       break;
12481     }
12482     
12483     // Don't skip over loads or things that can modify memory.
12484     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
12485       break;
12486   }
12487   
12488   
12489   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
12490
12491   // store X, null    -> turns into 'unreachable' in SimplifyCFG
12492   if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
12493     if (!isa<UndefValue>(Val)) {
12494       SI.setOperand(0, UndefValue::get(Val->getType()));
12495       if (Instruction *U = dyn_cast<Instruction>(Val))
12496         Worklist.Add(U);  // Dropped a use.
12497       ++NumCombined;
12498     }
12499     return 0;  // Do not modify these!
12500   }
12501
12502   // store undef, Ptr -> noop
12503   if (isa<UndefValue>(Val)) {
12504     EraseInstFromFunction(SI);
12505     ++NumCombined;
12506     return 0;
12507   }
12508
12509   // If the pointer destination is a cast, see if we can fold the cast into the
12510   // source instead.
12511   if (isa<CastInst>(Ptr))
12512     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12513       return Res;
12514   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
12515     if (CE->isCast())
12516       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12517         return Res;
12518
12519   
12520   // If this store is the last instruction in the basic block (possibly
12521   // excepting debug info instructions and the pointer bitcasts that feed
12522   // into them), and if the block ends with an unconditional branch, try
12523   // to move it to the successor block.
12524   BBI = &SI; 
12525   do {
12526     ++BBI;
12527   } while (isa<DbgInfoIntrinsic>(BBI) ||
12528            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
12529   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
12530     if (BI->isUnconditional())
12531       if (SimplifyStoreAtEndOfBlock(SI))
12532         return 0;  // xform done!
12533   
12534   return 0;
12535 }
12536
12537 /// SimplifyStoreAtEndOfBlock - Turn things like:
12538 ///   if () { *P = v1; } else { *P = v2 }
12539 /// into a phi node with a store in the successor.
12540 ///
12541 /// Simplify things like:
12542 ///   *P = v1; if () { *P = v2; }
12543 /// into a phi node with a store in the successor.
12544 ///
12545 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12546   BasicBlock *StoreBB = SI.getParent();
12547   
12548   // Check to see if the successor block has exactly two incoming edges.  If
12549   // so, see if the other predecessor contains a store to the same location.
12550   // if so, insert a PHI node (if needed) and move the stores down.
12551   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
12552   
12553   // Determine whether Dest has exactly two predecessors and, if so, compute
12554   // the other predecessor.
12555   pred_iterator PI = pred_begin(DestBB);
12556   BasicBlock *OtherBB = 0;
12557   if (*PI != StoreBB)
12558     OtherBB = *PI;
12559   ++PI;
12560   if (PI == pred_end(DestBB))
12561     return false;
12562   
12563   if (*PI != StoreBB) {
12564     if (OtherBB)
12565       return false;
12566     OtherBB = *PI;
12567   }
12568   if (++PI != pred_end(DestBB))
12569     return false;
12570
12571   // Bail out if all the relevant blocks aren't distinct (this can happen,
12572   // for example, if SI is in an infinite loop)
12573   if (StoreBB == DestBB || OtherBB == DestBB)
12574     return false;
12575
12576   // Verify that the other block ends in a branch and is not otherwise empty.
12577   BasicBlock::iterator BBI = OtherBB->getTerminator();
12578   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12579   if (!OtherBr || BBI == OtherBB->begin())
12580     return false;
12581   
12582   // If the other block ends in an unconditional branch, check for the 'if then
12583   // else' case.  there is an instruction before the branch.
12584   StoreInst *OtherStore = 0;
12585   if (OtherBr->isUnconditional()) {
12586     --BBI;
12587     // Skip over debugging info.
12588     while (isa<DbgInfoIntrinsic>(BBI) ||
12589            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12590       if (BBI==OtherBB->begin())
12591         return false;
12592       --BBI;
12593     }
12594     // If this isn't a store, isn't a store to the same location, or if the
12595     // alignments differ, bail out.
12596     OtherStore = dyn_cast<StoreInst>(BBI);
12597     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
12598         OtherStore->getAlignment() != SI.getAlignment())
12599       return false;
12600   } else {
12601     // Otherwise, the other block ended with a conditional branch. If one of the
12602     // destinations is StoreBB, then we have the if/then case.
12603     if (OtherBr->getSuccessor(0) != StoreBB && 
12604         OtherBr->getSuccessor(1) != StoreBB)
12605       return false;
12606     
12607     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12608     // if/then triangle.  See if there is a store to the same ptr as SI that
12609     // lives in OtherBB.
12610     for (;; --BBI) {
12611       // Check to see if we find the matching store.
12612       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12613         if (OtherStore->getOperand(1) != SI.getOperand(1) ||
12614             OtherStore->getAlignment() != SI.getAlignment())
12615           return false;
12616         break;
12617       }
12618       // If we find something that may be using or overwriting the stored
12619       // value, or if we run out of instructions, we can't do the xform.
12620       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12621           BBI == OtherBB->begin())
12622         return false;
12623     }
12624     
12625     // In order to eliminate the store in OtherBr, we have to
12626     // make sure nothing reads or overwrites the stored value in
12627     // StoreBB.
12628     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12629       // FIXME: This should really be AA driven.
12630       if (I->mayReadFromMemory() || I->mayWriteToMemory())
12631         return false;
12632     }
12633   }
12634   
12635   // Insert a PHI node now if we need it.
12636   Value *MergedVal = OtherStore->getOperand(0);
12637   if (MergedVal != SI.getOperand(0)) {
12638     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12639     PN->reserveOperandSpace(2);
12640     PN->addIncoming(SI.getOperand(0), SI.getParent());
12641     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12642     MergedVal = InsertNewInstBefore(PN, DestBB->front());
12643   }
12644   
12645   // Advance to a place where it is safe to insert the new store and
12646   // insert it.
12647   BBI = DestBB->getFirstNonPHI();
12648   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12649                                     OtherStore->isVolatile(),
12650                                     SI.getAlignment()), *BBI);
12651   
12652   // Nuke the old stores.
12653   EraseInstFromFunction(SI);
12654   EraseInstFromFunction(*OtherStore);
12655   ++NumCombined;
12656   return true;
12657 }
12658
12659
12660 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12661   // Change br (not X), label True, label False to: br X, label False, True
12662   Value *X = 0;
12663   BasicBlock *TrueDest;
12664   BasicBlock *FalseDest;
12665   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
12666       !isa<Constant>(X)) {
12667     // Swap Destinations and condition...
12668     BI.setCondition(X);
12669     BI.setSuccessor(0, FalseDest);
12670     BI.setSuccessor(1, TrueDest);
12671     return &BI;
12672   }
12673
12674   // Cannonicalize fcmp_one -> fcmp_oeq
12675   FCmpInst::Predicate FPred; Value *Y;
12676   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12677                              TrueDest, FalseDest)) &&
12678       BI.getCondition()->hasOneUse())
12679     if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12680         FPred == FCmpInst::FCMP_OGE) {
12681       FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12682       Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12683       
12684       // Swap Destinations and condition.
12685       BI.setSuccessor(0, FalseDest);
12686       BI.setSuccessor(1, TrueDest);
12687       Worklist.Add(Cond);
12688       return &BI;
12689     }
12690
12691   // Cannonicalize icmp_ne -> icmp_eq
12692   ICmpInst::Predicate IPred;
12693   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12694                       TrueDest, FalseDest)) &&
12695       BI.getCondition()->hasOneUse())
12696     if (IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12697         IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12698         IPred == ICmpInst::ICMP_SGE) {
12699       ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12700       Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12701       // Swap Destinations and condition.
12702       BI.setSuccessor(0, FalseDest);
12703       BI.setSuccessor(1, TrueDest);
12704       Worklist.Add(Cond);
12705       return &BI;
12706     }
12707
12708   return 0;
12709 }
12710
12711 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12712   Value *Cond = SI.getCondition();
12713   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12714     if (I->getOpcode() == Instruction::Add)
12715       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12716         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12717         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12718           SI.setOperand(i,
12719                    ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
12720                                                 AddRHS));
12721         SI.setOperand(0, I->getOperand(0));
12722         Worklist.Add(I);
12723         return &SI;
12724       }
12725   }
12726   return 0;
12727 }
12728
12729 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12730   Value *Agg = EV.getAggregateOperand();
12731
12732   if (!EV.hasIndices())
12733     return ReplaceInstUsesWith(EV, Agg);
12734
12735   if (Constant *C = dyn_cast<Constant>(Agg)) {
12736     if (isa<UndefValue>(C))
12737       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12738       
12739     if (isa<ConstantAggregateZero>(C))
12740       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12741
12742     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12743       // Extract the element indexed by the first index out of the constant
12744       Value *V = C->getOperand(*EV.idx_begin());
12745       if (EV.getNumIndices() > 1)
12746         // Extract the remaining indices out of the constant indexed by the
12747         // first index
12748         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12749       else
12750         return ReplaceInstUsesWith(EV, V);
12751     }
12752     return 0; // Can't handle other constants
12753   } 
12754   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12755     // We're extracting from an insertvalue instruction, compare the indices
12756     const unsigned *exti, *exte, *insi, *inse;
12757     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12758          exte = EV.idx_end(), inse = IV->idx_end();
12759          exti != exte && insi != inse;
12760          ++exti, ++insi) {
12761       if (*insi != *exti)
12762         // The insert and extract both reference distinctly different elements.
12763         // This means the extract is not influenced by the insert, and we can
12764         // replace the aggregate operand of the extract with the aggregate
12765         // operand of the insert. i.e., replace
12766         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12767         // %E = extractvalue { i32, { i32 } } %I, 0
12768         // with
12769         // %E = extractvalue { i32, { i32 } } %A, 0
12770         return ExtractValueInst::Create(IV->getAggregateOperand(),
12771                                         EV.idx_begin(), EV.idx_end());
12772     }
12773     if (exti == exte && insi == inse)
12774       // Both iterators are at the end: Index lists are identical. Replace
12775       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12776       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12777       // with "i32 42"
12778       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12779     if (exti == exte) {
12780       // The extract list is a prefix of the insert list. i.e. replace
12781       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12782       // %E = extractvalue { i32, { i32 } } %I, 1
12783       // with
12784       // %X = extractvalue { i32, { i32 } } %A, 1
12785       // %E = insertvalue { i32 } %X, i32 42, 0
12786       // by switching the order of the insert and extract (though the
12787       // insertvalue should be left in, since it may have other uses).
12788       Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12789                                                  EV.idx_begin(), EV.idx_end());
12790       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12791                                      insi, inse);
12792     }
12793     if (insi == inse)
12794       // The insert list is a prefix of the extract list
12795       // We can simply remove the common indices from the extract and make it
12796       // operate on the inserted value instead of the insertvalue result.
12797       // i.e., replace
12798       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12799       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12800       // with
12801       // %E extractvalue { i32 } { i32 42 }, 0
12802       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12803                                       exti, exte);
12804   }
12805   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
12806     // We're extracting from an intrinsic, see if we're the only user, which
12807     // allows us to simplify multiple result intrinsics to simpler things that
12808     // just get one value..
12809     if (II->hasOneUse()) {
12810       // Check if we're grabbing the overflow bit or the result of a 'with
12811       // overflow' intrinsic.  If it's the latter we can remove the intrinsic
12812       // and replace it with a traditional binary instruction.
12813       switch (II->getIntrinsicID()) {
12814       case Intrinsic::uadd_with_overflow:
12815       case Intrinsic::sadd_with_overflow:
12816         if (*EV.idx_begin() == 0) {  // Normal result.
12817           Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12818           II->replaceAllUsesWith(UndefValue::get(II->getType()));
12819           EraseInstFromFunction(*II);
12820           return BinaryOperator::CreateAdd(LHS, RHS);
12821         }
12822         break;
12823       case Intrinsic::usub_with_overflow:
12824       case Intrinsic::ssub_with_overflow:
12825         if (*EV.idx_begin() == 0) {  // Normal result.
12826           Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12827           II->replaceAllUsesWith(UndefValue::get(II->getType()));
12828           EraseInstFromFunction(*II);
12829           return BinaryOperator::CreateSub(LHS, RHS);
12830         }
12831         break;
12832       case Intrinsic::umul_with_overflow:
12833       case Intrinsic::smul_with_overflow:
12834         if (*EV.idx_begin() == 0) {  // Normal result.
12835           Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12836           II->replaceAllUsesWith(UndefValue::get(II->getType()));
12837           EraseInstFromFunction(*II);
12838           return BinaryOperator::CreateMul(LHS, RHS);
12839         }
12840         break;
12841       default:
12842         break;
12843       }
12844     }
12845   }
12846   // Can't simplify extracts from other values. Note that nested extracts are
12847   // already simplified implicitely by the above (extract ( extract (insert) )
12848   // will be translated into extract ( insert ( extract ) ) first and then just
12849   // the value inserted, if appropriate).
12850   return 0;
12851 }
12852
12853 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12854 /// is to leave as a vector operation.
12855 static bool CheapToScalarize(Value *V, bool isConstant) {
12856   if (isa<ConstantAggregateZero>(V)) 
12857     return true;
12858   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12859     if (isConstant) return true;
12860     // If all elts are the same, we can extract.
12861     Constant *Op0 = C->getOperand(0);
12862     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12863       if (C->getOperand(i) != Op0)
12864         return false;
12865     return true;
12866   }
12867   Instruction *I = dyn_cast<Instruction>(V);
12868   if (!I) return false;
12869   
12870   // Insert element gets simplified to the inserted element or is deleted if
12871   // this is constant idx extract element and its a constant idx insertelt.
12872   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12873       isa<ConstantInt>(I->getOperand(2)))
12874     return true;
12875   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12876     return true;
12877   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12878     if (BO->hasOneUse() &&
12879         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12880          CheapToScalarize(BO->getOperand(1), isConstant)))
12881       return true;
12882   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12883     if (CI->hasOneUse() &&
12884         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12885          CheapToScalarize(CI->getOperand(1), isConstant)))
12886       return true;
12887   
12888   return false;
12889 }
12890
12891 /// Read and decode a shufflevector mask.
12892 ///
12893 /// It turns undef elements into values that are larger than the number of
12894 /// elements in the input.
12895 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12896   unsigned NElts = SVI->getType()->getNumElements();
12897   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12898     return std::vector<unsigned>(NElts, 0);
12899   if (isa<UndefValue>(SVI->getOperand(2)))
12900     return std::vector<unsigned>(NElts, 2*NElts);
12901
12902   std::vector<unsigned> Result;
12903   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12904   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12905     if (isa<UndefValue>(*i))
12906       Result.push_back(NElts*2);  // undef -> 8
12907     else
12908       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12909   return Result;
12910 }
12911
12912 /// FindScalarElement - Given a vector and an element number, see if the scalar
12913 /// value is already around as a register, for example if it were inserted then
12914 /// extracted from the vector.
12915 static Value *FindScalarElement(Value *V, unsigned EltNo,
12916                                 LLVMContext *Context) {
12917   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12918   const VectorType *PTy = cast<VectorType>(V->getType());
12919   unsigned Width = PTy->getNumElements();
12920   if (EltNo >= Width)  // Out of range access.
12921     return UndefValue::get(PTy->getElementType());
12922   
12923   if (isa<UndefValue>(V))
12924     return UndefValue::get(PTy->getElementType());
12925   else if (isa<ConstantAggregateZero>(V))
12926     return Constant::getNullValue(PTy->getElementType());
12927   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12928     return CP->getOperand(EltNo);
12929   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12930     // If this is an insert to a variable element, we don't know what it is.
12931     if (!isa<ConstantInt>(III->getOperand(2))) 
12932       return 0;
12933     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12934     
12935     // If this is an insert to the element we are looking for, return the
12936     // inserted value.
12937     if (EltNo == IIElt) 
12938       return III->getOperand(1);
12939     
12940     // Otherwise, the insertelement doesn't modify the value, recurse on its
12941     // vector input.
12942     return FindScalarElement(III->getOperand(0), EltNo, Context);
12943   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12944     unsigned LHSWidth =
12945       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12946     unsigned InEl = getShuffleMask(SVI)[EltNo];
12947     if (InEl < LHSWidth)
12948       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12949     else if (InEl < LHSWidth*2)
12950       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12951     else
12952       return UndefValue::get(PTy->getElementType());
12953   }
12954   
12955   // Otherwise, we don't know.
12956   return 0;
12957 }
12958
12959 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12960   // If vector val is undef, replace extract with scalar undef.
12961   if (isa<UndefValue>(EI.getOperand(0)))
12962     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12963
12964   // If vector val is constant 0, replace extract with scalar 0.
12965   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12966     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12967   
12968   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12969     // If vector val is constant with all elements the same, replace EI with
12970     // that element. When the elements are not identical, we cannot replace yet
12971     // (we do that below, but only when the index is constant).
12972     Constant *op0 = C->getOperand(0);
12973     for (unsigned i = 1; i != C->getNumOperands(); ++i)
12974       if (C->getOperand(i) != op0) {
12975         op0 = 0; 
12976         break;
12977       }
12978     if (op0)
12979       return ReplaceInstUsesWith(EI, op0);
12980   }
12981   
12982   // If extracting a specified index from the vector, see if we can recursively
12983   // find a previously computed scalar that was inserted into the vector.
12984   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12985     unsigned IndexVal = IdxC->getZExtValue();
12986     unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
12987       
12988     // If this is extracting an invalid index, turn this into undef, to avoid
12989     // crashing the code below.
12990     if (IndexVal >= VectorWidth)
12991       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12992     
12993     // This instruction only demands the single element from the input vector.
12994     // If the input vector has a single use, simplify it based on this use
12995     // property.
12996     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12997       APInt UndefElts(VectorWidth, 0);
12998       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12999       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
13000                                                 DemandedMask, UndefElts)) {
13001         EI.setOperand(0, V);
13002         return &EI;
13003       }
13004     }
13005     
13006     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
13007       return ReplaceInstUsesWith(EI, Elt);
13008     
13009     // If the this extractelement is directly using a bitcast from a vector of
13010     // the same number of elements, see if we can find the source element from
13011     // it.  In this case, we will end up needing to bitcast the scalars.
13012     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
13013       if (const VectorType *VT = 
13014               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
13015         if (VT->getNumElements() == VectorWidth)
13016           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
13017                                              IndexVal, Context))
13018             return new BitCastInst(Elt, EI.getType());
13019     }
13020   }
13021   
13022   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
13023     // Push extractelement into predecessor operation if legal and
13024     // profitable to do so
13025     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
13026       if (I->hasOneUse() &&
13027           CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
13028         Value *newEI0 =
13029           Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
13030                                         EI.getName()+".lhs");
13031         Value *newEI1 =
13032           Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
13033                                         EI.getName()+".rhs");
13034         return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
13035       }
13036     } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
13037       // Extracting the inserted element?
13038       if (IE->getOperand(2) == EI.getOperand(1))
13039         return ReplaceInstUsesWith(EI, IE->getOperand(1));
13040       // If the inserted and extracted elements are constants, they must not
13041       // be the same value, extract from the pre-inserted value instead.
13042       if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
13043         Worklist.AddValue(EI.getOperand(0));
13044         EI.setOperand(0, IE->getOperand(0));
13045         return &EI;
13046       }
13047     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
13048       // If this is extracting an element from a shufflevector, figure out where
13049       // it came from and extract from the appropriate input element instead.
13050       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
13051         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
13052         Value *Src;
13053         unsigned LHSWidth =
13054           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
13055
13056         if (SrcIdx < LHSWidth)
13057           Src = SVI->getOperand(0);
13058         else if (SrcIdx < LHSWidth*2) {
13059           SrcIdx -= LHSWidth;
13060           Src = SVI->getOperand(1);
13061         } else {
13062           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
13063         }
13064         return ExtractElementInst::Create(Src,
13065                          ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
13066                                           false));
13067       }
13068     }
13069     // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
13070   }
13071   return 0;
13072 }
13073
13074 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
13075 /// elements from either LHS or RHS, return the shuffle mask and true. 
13076 /// Otherwise, return false.
13077 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
13078                                          std::vector<Constant*> &Mask,
13079                                          LLVMContext *Context) {
13080   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
13081          "Invalid CollectSingleShuffleElements");
13082   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
13083
13084   if (isa<UndefValue>(V)) {
13085     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
13086     return true;
13087   } else if (V == LHS) {
13088     for (unsigned i = 0; i != NumElts; ++i)
13089       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
13090     return true;
13091   } else if (V == RHS) {
13092     for (unsigned i = 0; i != NumElts; ++i)
13093       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
13094     return true;
13095   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
13096     // If this is an insert of an extract from some other vector, include it.
13097     Value *VecOp    = IEI->getOperand(0);
13098     Value *ScalarOp = IEI->getOperand(1);
13099     Value *IdxOp    = IEI->getOperand(2);
13100     
13101     if (!isa<ConstantInt>(IdxOp))
13102       return false;
13103     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
13104     
13105     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
13106       // Okay, we can handle this if the vector we are insertinting into is
13107       // transitively ok.
13108       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
13109         // If so, update the mask to reflect the inserted undef.
13110         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
13111         return true;
13112       }      
13113     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
13114       if (isa<ConstantInt>(EI->getOperand(1)) &&
13115           EI->getOperand(0)->getType() == V->getType()) {
13116         unsigned ExtractedIdx =
13117           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13118         
13119         // This must be extracting from either LHS or RHS.
13120         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
13121           // Okay, we can handle this if the vector we are insertinting into is
13122           // transitively ok.
13123           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
13124             // If so, update the mask to reflect the inserted value.
13125             if (EI->getOperand(0) == LHS) {
13126               Mask[InsertedIdx % NumElts] = 
13127                  ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
13128             } else {
13129               assert(EI->getOperand(0) == RHS);
13130               Mask[InsertedIdx % NumElts] = 
13131                 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
13132               
13133             }
13134             return true;
13135           }
13136         }
13137       }
13138     }
13139   }
13140   // TODO: Handle shufflevector here!
13141   
13142   return false;
13143 }
13144
13145 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
13146 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
13147 /// that computes V and the LHS value of the shuffle.
13148 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
13149                                      Value *&RHS, LLVMContext *Context) {
13150   assert(isa<VectorType>(V->getType()) && 
13151          (RHS == 0 || V->getType() == RHS->getType()) &&
13152          "Invalid shuffle!");
13153   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
13154
13155   if (isa<UndefValue>(V)) {
13156     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
13157     return V;
13158   } else if (isa<ConstantAggregateZero>(V)) {
13159     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
13160     return V;
13161   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
13162     // If this is an insert of an extract from some other vector, include it.
13163     Value *VecOp    = IEI->getOperand(0);
13164     Value *ScalarOp = IEI->getOperand(1);
13165     Value *IdxOp    = IEI->getOperand(2);
13166     
13167     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13168       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13169           EI->getOperand(0)->getType() == V->getType()) {
13170         unsigned ExtractedIdx =
13171           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13172         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
13173         
13174         // Either the extracted from or inserted into vector must be RHSVec,
13175         // otherwise we'd end up with a shuffle of three inputs.
13176         if (EI->getOperand(0) == RHS || RHS == 0) {
13177           RHS = EI->getOperand(0);
13178           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
13179           Mask[InsertedIdx % NumElts] = 
13180             ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
13181           return V;
13182         }
13183         
13184         if (VecOp == RHS) {
13185           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
13186                                             RHS, Context);
13187           // Everything but the extracted element is replaced with the RHS.
13188           for (unsigned i = 0; i != NumElts; ++i) {
13189             if (i != InsertedIdx)
13190               Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
13191           }
13192           return V;
13193         }
13194         
13195         // If this insertelement is a chain that comes from exactly these two
13196         // vectors, return the vector and the effective shuffle.
13197         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
13198                                          Context))
13199           return EI->getOperand(0);
13200         
13201       }
13202     }
13203   }
13204   // TODO: Handle shufflevector here!
13205   
13206   // Otherwise, can't do anything fancy.  Return an identity vector.
13207   for (unsigned i = 0; i != NumElts; ++i)
13208     Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
13209   return V;
13210 }
13211
13212 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
13213   Value *VecOp    = IE.getOperand(0);
13214   Value *ScalarOp = IE.getOperand(1);
13215   Value *IdxOp    = IE.getOperand(2);
13216   
13217   // Inserting an undef or into an undefined place, remove this.
13218   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
13219     ReplaceInstUsesWith(IE, VecOp);
13220   
13221   // If the inserted element was extracted from some other vector, and if the 
13222   // indexes are constant, try to turn this into a shufflevector operation.
13223   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13224     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13225         EI->getOperand(0)->getType() == IE.getType()) {
13226       unsigned NumVectorElts = IE.getType()->getNumElements();
13227       unsigned ExtractedIdx =
13228         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13229       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
13230       
13231       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
13232         return ReplaceInstUsesWith(IE, VecOp);
13233       
13234       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
13235         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
13236       
13237       // If we are extracting a value from a vector, then inserting it right
13238       // back into the same place, just use the input vector.
13239       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
13240         return ReplaceInstUsesWith(IE, VecOp);      
13241       
13242       // If this insertelement isn't used by some other insertelement, turn it
13243       // (and any insertelements it points to), into one big shuffle.
13244       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
13245         std::vector<Constant*> Mask;
13246         Value *RHS = 0;
13247         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
13248         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
13249         // We now have a shuffle of LHS, RHS, Mask.
13250         return new ShuffleVectorInst(LHS, RHS,
13251                                      ConstantVector::get(Mask));
13252       }
13253     }
13254   }
13255
13256   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
13257   APInt UndefElts(VWidth, 0);
13258   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13259   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
13260     return &IE;
13261
13262   return 0;
13263 }
13264
13265
13266 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
13267   Value *LHS = SVI.getOperand(0);
13268   Value *RHS = SVI.getOperand(1);
13269   std::vector<unsigned> Mask = getShuffleMask(&SVI);
13270
13271   bool MadeChange = false;
13272
13273   // Undefined shuffle mask -> undefined value.
13274   if (isa<UndefValue>(SVI.getOperand(2)))
13275     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
13276
13277   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
13278
13279   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
13280     return 0;
13281
13282   APInt UndefElts(VWidth, 0);
13283   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13284   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
13285     LHS = SVI.getOperand(0);
13286     RHS = SVI.getOperand(1);
13287     MadeChange = true;
13288   }
13289   
13290   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
13291   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
13292   if (LHS == RHS || isa<UndefValue>(LHS)) {
13293     if (isa<UndefValue>(LHS) && LHS == RHS) {
13294       // shuffle(undef,undef,mask) -> undef.
13295       return ReplaceInstUsesWith(SVI, LHS);
13296     }
13297     
13298     // Remap any references to RHS to use LHS.
13299     std::vector<Constant*> Elts;
13300     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13301       if (Mask[i] >= 2*e)
13302         Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13303       else {
13304         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
13305             (Mask[i] <  e && isa<UndefValue>(LHS))) {
13306           Mask[i] = 2*e;     // Turn into undef.
13307           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13308         } else {
13309           Mask[i] = Mask[i] % e;  // Force to LHS.
13310           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
13311         }
13312       }
13313     }
13314     SVI.setOperand(0, SVI.getOperand(1));
13315     SVI.setOperand(1, UndefValue::get(RHS->getType()));
13316     SVI.setOperand(2, ConstantVector::get(Elts));
13317     LHS = SVI.getOperand(0);
13318     RHS = SVI.getOperand(1);
13319     MadeChange = true;
13320   }
13321   
13322   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
13323   bool isLHSID = true, isRHSID = true;
13324     
13325   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13326     if (Mask[i] >= e*2) continue;  // Ignore undef values.
13327     // Is this an identity shuffle of the LHS value?
13328     isLHSID &= (Mask[i] == i);
13329       
13330     // Is this an identity shuffle of the RHS value?
13331     isRHSID &= (Mask[i]-e == i);
13332   }
13333
13334   // Eliminate identity shuffles.
13335   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
13336   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
13337   
13338   // If the LHS is a shufflevector itself, see if we can combine it with this
13339   // one without producing an unusual shuffle.  Here we are really conservative:
13340   // we are absolutely afraid of producing a shuffle mask not in the input
13341   // program, because the code gen may not be smart enough to turn a merged
13342   // shuffle into two specific shuffles: it may produce worse code.  As such,
13343   // we only merge two shuffles if the result is one of the two input shuffle
13344   // masks.  In this case, merging the shuffles just removes one instruction,
13345   // which we know is safe.  This is good for things like turning:
13346   // (splat(splat)) -> splat.
13347   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
13348     if (isa<UndefValue>(RHS)) {
13349       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
13350
13351       if (LHSMask.size() == Mask.size()) {
13352         std::vector<unsigned> NewMask;
13353         for (unsigned i = 0, e = Mask.size(); i != e; ++i)
13354           if (Mask[i] >= e)
13355             NewMask.push_back(2*e);
13356           else
13357             NewMask.push_back(LHSMask[Mask[i]]);
13358       
13359         // If the result mask is equal to the src shuffle or this
13360         // shuffle mask, do the replacement.
13361         if (NewMask == LHSMask || NewMask == Mask) {
13362           unsigned LHSInNElts =
13363             cast<VectorType>(LHSSVI->getOperand(0)->getType())->
13364             getNumElements();
13365           std::vector<Constant*> Elts;
13366           for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
13367             if (NewMask[i] >= LHSInNElts*2) {
13368               Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13369             } else {
13370               Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
13371                                               NewMask[i]));
13372             }
13373           }
13374           return new ShuffleVectorInst(LHSSVI->getOperand(0),
13375                                        LHSSVI->getOperand(1),
13376                                        ConstantVector::get(Elts));
13377         }
13378       }
13379     }
13380   }
13381
13382   return MadeChange ? &SVI : 0;
13383 }
13384
13385
13386
13387
13388 /// TryToSinkInstruction - Try to move the specified instruction from its
13389 /// current block into the beginning of DestBlock, which can only happen if it's
13390 /// safe to move the instruction past all of the instructions between it and the
13391 /// end of its block.
13392 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
13393   assert(I->hasOneUse() && "Invariants didn't hold!");
13394
13395   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
13396   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
13397     return false;
13398
13399   // Do not sink alloca instructions out of the entry block.
13400   if (isa<AllocaInst>(I) && I->getParent() ==
13401         &DestBlock->getParent()->getEntryBlock())
13402     return false;
13403
13404   // We can only sink load instructions if there is nothing between the load and
13405   // the end of block that could change the value.
13406   if (I->mayReadFromMemory()) {
13407     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
13408          Scan != E; ++Scan)
13409       if (Scan->mayWriteToMemory())
13410         return false;
13411   }
13412
13413   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
13414
13415   CopyPrecedingStopPoint(I, InsertPos);
13416   I->moveBefore(InsertPos);
13417   ++NumSunkInst;
13418   return true;
13419 }
13420
13421
13422 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
13423 /// all reachable code to the worklist.
13424 ///
13425 /// This has a couple of tricks to make the code faster and more powerful.  In
13426 /// particular, we constant fold and DCE instructions as we go, to avoid adding
13427 /// them to the worklist (this significantly speeds up instcombine on code where
13428 /// many instructions are dead or constant).  Additionally, if we find a branch
13429 /// whose condition is a known constant, we only visit the reachable successors.
13430 ///
13431 static bool AddReachableCodeToWorklist(BasicBlock *BB, 
13432                                        SmallPtrSet<BasicBlock*, 64> &Visited,
13433                                        InstCombiner &IC,
13434                                        const TargetData *TD) {
13435   bool MadeIRChange = false;
13436   SmallVector<BasicBlock*, 256> Worklist;
13437   Worklist.push_back(BB);
13438   
13439   std::vector<Instruction*> InstrsForInstCombineWorklist;
13440   InstrsForInstCombineWorklist.reserve(128);
13441
13442   SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
13443   
13444   while (!Worklist.empty()) {
13445     BB = Worklist.back();
13446     Worklist.pop_back();
13447     
13448     // We have now visited this block!  If we've already been here, ignore it.
13449     if (!Visited.insert(BB)) continue;
13450
13451     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
13452       Instruction *Inst = BBI++;
13453       
13454       // DCE instruction if trivially dead.
13455       if (isInstructionTriviallyDead(Inst)) {
13456         ++NumDeadInst;
13457         DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
13458         Inst->eraseFromParent();
13459         continue;
13460       }
13461       
13462       // ConstantProp instruction if trivially constant.
13463       if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
13464         if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
13465           DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
13466                        << *Inst << '\n');
13467           Inst->replaceAllUsesWith(C);
13468           ++NumConstProp;
13469           Inst->eraseFromParent();
13470           continue;
13471         }
13472       
13473       
13474       
13475       if (TD) {
13476         // See if we can constant fold its operands.
13477         for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
13478              i != e; ++i) {
13479           ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
13480           if (CE == 0) continue;
13481           
13482           // If we already folded this constant, don't try again.
13483           if (!FoldedConstants.insert(CE))
13484             continue;
13485           
13486           Constant *NewC = ConstantFoldConstantExpression(CE, TD);
13487           if (NewC && NewC != CE) {
13488             *i = NewC;
13489             MadeIRChange = true;
13490           }
13491         }
13492       }
13493       
13494
13495       InstrsForInstCombineWorklist.push_back(Inst);
13496     }
13497
13498     // Recursively visit successors.  If this is a branch or switch on a
13499     // constant, only visit the reachable successor.
13500     TerminatorInst *TI = BB->getTerminator();
13501     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
13502       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
13503         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
13504         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
13505         Worklist.push_back(ReachableBB);
13506         continue;
13507       }
13508     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
13509       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
13510         // See if this is an explicit destination.
13511         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
13512           if (SI->getCaseValue(i) == Cond) {
13513             BasicBlock *ReachableBB = SI->getSuccessor(i);
13514             Worklist.push_back(ReachableBB);
13515             continue;
13516           }
13517         
13518         // Otherwise it is the default destination.
13519         Worklist.push_back(SI->getSuccessor(0));
13520         continue;
13521       }
13522     }
13523     
13524     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
13525       Worklist.push_back(TI->getSuccessor(i));
13526   }
13527   
13528   // Once we've found all of the instructions to add to instcombine's worklist,
13529   // add them in reverse order.  This way instcombine will visit from the top
13530   // of the function down.  This jives well with the way that it adds all uses
13531   // of instructions to the worklist after doing a transformation, thus avoiding
13532   // some N^2 behavior in pathological cases.
13533   IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
13534                               InstrsForInstCombineWorklist.size());
13535   
13536   return MadeIRChange;
13537 }
13538
13539 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
13540   MadeIRChange = false;
13541   
13542   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
13543         << F.getNameStr() << "\n");
13544
13545   {
13546     // Do a depth-first traversal of the function, populate the worklist with
13547     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
13548     // track of which blocks we visit.
13549     SmallPtrSet<BasicBlock*, 64> Visited;
13550     MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
13551
13552     // Do a quick scan over the function.  If we find any blocks that are
13553     // unreachable, remove any instructions inside of them.  This prevents
13554     // the instcombine code from having to deal with some bad special cases.
13555     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
13556       if (!Visited.count(BB)) {
13557         Instruction *Term = BB->getTerminator();
13558         while (Term != BB->begin()) {   // Remove instrs bottom-up
13559           BasicBlock::iterator I = Term; --I;
13560
13561           DEBUG(errs() << "IC: DCE: " << *I << '\n');
13562           // A debug intrinsic shouldn't force another iteration if we weren't
13563           // going to do one without it.
13564           if (!isa<DbgInfoIntrinsic>(I)) {
13565             ++NumDeadInst;
13566             MadeIRChange = true;
13567           }
13568
13569           // If I is not void type then replaceAllUsesWith undef.
13570           // This allows ValueHandlers and custom metadata to adjust itself.
13571           if (!I->getType()->isVoidTy())
13572             I->replaceAllUsesWith(UndefValue::get(I->getType()));
13573           I->eraseFromParent();
13574         }
13575       }
13576   }
13577
13578   while (!Worklist.isEmpty()) {
13579     Instruction *I = Worklist.RemoveOne();
13580     if (I == 0) continue;  // skip null values.
13581
13582     // Check to see if we can DCE the instruction.
13583     if (isInstructionTriviallyDead(I)) {
13584       DEBUG(errs() << "IC: DCE: " << *I << '\n');
13585       EraseInstFromFunction(*I);
13586       ++NumDeadInst;
13587       MadeIRChange = true;
13588       continue;
13589     }
13590
13591     // Instruction isn't dead, see if we can constant propagate it.
13592     if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
13593       if (Constant *C = ConstantFoldInstruction(I, TD)) {
13594         DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
13595
13596         // Add operands to the worklist.
13597         ReplaceInstUsesWith(*I, C);
13598         ++NumConstProp;
13599         EraseInstFromFunction(*I);
13600         MadeIRChange = true;
13601         continue;
13602       }
13603
13604     // See if we can trivially sink this instruction to a successor basic block.
13605     if (I->hasOneUse()) {
13606       BasicBlock *BB = I->getParent();
13607       Instruction *UserInst = cast<Instruction>(I->use_back());
13608       BasicBlock *UserParent;
13609       
13610       // Get the block the use occurs in.
13611       if (PHINode *PN = dyn_cast<PHINode>(UserInst))
13612         UserParent = PN->getIncomingBlock(I->use_begin().getUse());
13613       else
13614         UserParent = UserInst->getParent();
13615       
13616       if (UserParent != BB) {
13617         bool UserIsSuccessor = false;
13618         // See if the user is one of our successors.
13619         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13620           if (*SI == UserParent) {
13621             UserIsSuccessor = true;
13622             break;
13623           }
13624
13625         // If the user is one of our immediate successors, and if that successor
13626         // only has us as a predecessors (we'd have to split the critical edge
13627         // otherwise), we can keep going.
13628         if (UserIsSuccessor && UserParent->getSinglePredecessor())
13629           // Okay, the CFG is simple enough, try to sink this instruction.
13630           MadeIRChange |= TryToSinkInstruction(I, UserParent);
13631       }
13632     }
13633
13634     // Now that we have an instruction, try combining it to simplify it.
13635     Builder->SetInsertPoint(I->getParent(), I);
13636     
13637 #ifndef NDEBUG
13638     std::string OrigI;
13639 #endif
13640     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
13641     DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
13642
13643     if (Instruction *Result = visit(*I)) {
13644       ++NumCombined;
13645       // Should we replace the old instruction with a new one?
13646       if (Result != I) {
13647         DEBUG(errs() << "IC: Old = " << *I << '\n'
13648                      << "    New = " << *Result << '\n');
13649
13650         // Everything uses the new instruction now.
13651         I->replaceAllUsesWith(Result);
13652
13653         // Push the new instruction and any users onto the worklist.
13654         Worklist.Add(Result);
13655         Worklist.AddUsersToWorkList(*Result);
13656
13657         // Move the name to the new instruction first.
13658         Result->takeName(I);
13659
13660         // Insert the new instruction into the basic block...
13661         BasicBlock *InstParent = I->getParent();
13662         BasicBlock::iterator InsertPos = I;
13663
13664         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
13665           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13666             ++InsertPos;
13667
13668         InstParent->getInstList().insert(InsertPos, Result);
13669
13670         EraseInstFromFunction(*I);
13671       } else {
13672 #ifndef NDEBUG
13673         DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13674                      << "    New = " << *I << '\n');
13675 #endif
13676
13677         // If the instruction was modified, it's possible that it is now dead.
13678         // if so, remove it.
13679         if (isInstructionTriviallyDead(I)) {
13680           EraseInstFromFunction(*I);
13681         } else {
13682           Worklist.Add(I);
13683           Worklist.AddUsersToWorkList(*I);
13684         }
13685       }
13686       MadeIRChange = true;
13687     }
13688   }
13689
13690   Worklist.Zap();
13691   return MadeIRChange;
13692 }
13693
13694
13695 bool InstCombiner::runOnFunction(Function &F) {
13696   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13697   Context = &F.getContext();
13698   TD = getAnalysisIfAvailable<TargetData>();
13699
13700   
13701   /// Builder - This is an IRBuilder that automatically inserts new
13702   /// instructions into the worklist when they are created.
13703   IRBuilder<true, TargetFolder, InstCombineIRInserter> 
13704     TheBuilder(F.getContext(), TargetFolder(TD),
13705                InstCombineIRInserter(Worklist));
13706   Builder = &TheBuilder;
13707   
13708   bool EverMadeChange = false;
13709
13710   // Iterate while there is work to do.
13711   unsigned Iteration = 0;
13712   while (DoOneIteration(F, Iteration++))
13713     EverMadeChange = true;
13714   
13715   Builder = 0;
13716   return EverMadeChange;
13717 }
13718
13719 FunctionPass *llvm::createInstructionCombiningPass() {
13720   return new InstCombiner();
13721 }