Generalize the previous xform to handle cases where exactly
[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 *FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
262                                               GlobalVariable *GV, CmpInst &ICI);
263     Instruction *visitFCmpInst(FCmpInst &I);
264     Instruction *visitICmpInst(ICmpInst &I);
265     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
266     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
267                                                 Instruction *LHS,
268                                                 ConstantInt *RHS);
269     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
270                                 ConstantInt *DivRHS);
271     Instruction *FoldICmpAddOpCst(ICmpInst &ICI, Value *X, ConstantInt *CI,
272                                   ICmpInst::Predicate Pred, Value *TheAdd);
273     Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
274                              ICmpInst::Predicate Cond, Instruction &I);
275     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
276                                      BinaryOperator &I);
277     Instruction *commonCastTransforms(CastInst &CI);
278     Instruction *commonIntCastTransforms(CastInst &CI);
279     Instruction *commonPointerCastTransforms(CastInst &CI);
280     Instruction *visitTrunc(TruncInst &CI);
281     Instruction *visitZExt(ZExtInst &CI);
282     Instruction *visitSExt(SExtInst &CI);
283     Instruction *visitFPTrunc(FPTruncInst &CI);
284     Instruction *visitFPExt(CastInst &CI);
285     Instruction *visitFPToUI(FPToUIInst &FI);
286     Instruction *visitFPToSI(FPToSIInst &FI);
287     Instruction *visitUIToFP(CastInst &CI);
288     Instruction *visitSIToFP(CastInst &CI);
289     Instruction *visitPtrToInt(PtrToIntInst &CI);
290     Instruction *visitIntToPtr(IntToPtrInst &CI);
291     Instruction *visitBitCast(BitCastInst &CI);
292     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
293                                 Instruction *FI);
294     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
295     Instruction *FoldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
296                               Value *A, Value *B, Instruction &Outer,
297                               SelectPatternFlavor SPF2, Value *C);
298     Instruction *visitSelectInst(SelectInst &SI);
299     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
300     Instruction *visitCallInst(CallInst &CI);
301     Instruction *visitInvokeInst(InvokeInst &II);
302
303     Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
304     Instruction *visitPHINode(PHINode &PN);
305     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
306     Instruction *visitAllocaInst(AllocaInst &AI);
307     Instruction *visitFree(Instruction &FI);
308     Instruction *visitLoadInst(LoadInst &LI);
309     Instruction *visitStoreInst(StoreInst &SI);
310     Instruction *visitBranchInst(BranchInst &BI);
311     Instruction *visitSwitchInst(SwitchInst &SI);
312     Instruction *visitInsertElementInst(InsertElementInst &IE);
313     Instruction *visitExtractElementInst(ExtractElementInst &EI);
314     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
315     Instruction *visitExtractValueInst(ExtractValueInst &EV);
316
317     // visitInstruction - Specify what to return for unhandled instructions...
318     Instruction *visitInstruction(Instruction &I) { return 0; }
319
320   private:
321     Instruction *visitCallSite(CallSite CS);
322     bool transformConstExprCastCall(CallSite CS);
323     Instruction *transformCallThroughTrampoline(CallSite CS);
324     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
325                                    bool DoXform = true);
326     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
327     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
328
329
330   public:
331     // InsertNewInstBefore - insert an instruction New before instruction Old
332     // in the program.  Add the new instruction to the worklist.
333     //
334     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
335       assert(New && New->getParent() == 0 &&
336              "New instruction already inserted into a basic block!");
337       BasicBlock *BB = Old.getParent();
338       BB->getInstList().insert(&Old, New);  // Insert inst
339       Worklist.Add(New);
340       return New;
341     }
342         
343     // ReplaceInstUsesWith - This method is to be used when an instruction is
344     // found to be dead, replacable with another preexisting expression.  Here
345     // we add all uses of I to the worklist, replace all uses of I with the new
346     // value, then return I, so that the inst combiner will know that I was
347     // modified.
348     //
349     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
350       Worklist.AddUsersToWorkList(I);   // Add all modified instrs to worklist.
351       
352       // If we are replacing the instruction with itself, this must be in a
353       // segment of unreachable code, so just clobber the instruction.
354       if (&I == V) 
355         V = UndefValue::get(I.getType());
356         
357       I.replaceAllUsesWith(V);
358       return &I;
359     }
360
361     // EraseInstFromFunction - When dealing with an instruction that has side
362     // effects or produces a void value, we can't rely on DCE to delete the
363     // instruction.  Instead, visit methods should return the value returned by
364     // this function.
365     Instruction *EraseInstFromFunction(Instruction &I) {
366       DEBUG(errs() << "IC: ERASE " << I << '\n');
367
368       assert(I.use_empty() && "Cannot erase instruction that is used!");
369       // Make sure that we reprocess all operands now that we reduced their
370       // use counts.
371       if (I.getNumOperands() < 8) {
372         for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
373           if (Instruction *Op = dyn_cast<Instruction>(*i))
374             Worklist.Add(Op);
375       }
376       Worklist.Remove(&I);
377       I.eraseFromParent();
378       MadeIRChange = true;
379       return 0;  // Don't do anything with FI
380     }
381         
382     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
383                            APInt &KnownOne, unsigned Depth = 0) const {
384       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
385     }
386     
387     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
388                            unsigned Depth = 0) const {
389       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
390     }
391     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
392       return llvm::ComputeNumSignBits(Op, TD, Depth);
393     }
394
395   private:
396
397     /// SimplifyCommutative - This performs a few simplifications for 
398     /// commutative operators.
399     bool SimplifyCommutative(BinaryOperator &I);
400
401     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
402     /// based on the demanded bits.
403     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
404                                    APInt& KnownZero, APInt& KnownOne,
405                                    unsigned Depth);
406     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
407                               APInt& KnownZero, APInt& KnownOne,
408                               unsigned Depth=0);
409         
410     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
411     /// SimplifyDemandedBits knows about.  See if the instruction has any
412     /// properties that allow us to simplify its operands.
413     bool SimplifyDemandedInstructionBits(Instruction &Inst);
414         
415     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
416                                       APInt& UndefElts, unsigned Depth = 0);
417       
418     // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
419     // which has a PHI node as operand #0, see if we can fold the instruction
420     // into the PHI (which is only possible if all operands to the PHI are
421     // constants).
422     //
423     // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
424     // that would normally be unprofitable because they strongly encourage jump
425     // threading.
426     Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
427
428     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
429     // operator and they all are only used by the PHI, PHI together their
430     // inputs, and do the operation once, to the result of the PHI.
431     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
432     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
433     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
434     Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
435
436     
437     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
438                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
439     
440     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
441                               bool isSub, Instruction &I);
442     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
443                                  bool isSigned, bool Inside, Instruction &IB);
444     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
445     Instruction *MatchBSwap(BinaryOperator &I);
446     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
447     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
448     Instruction *SimplifyMemSet(MemSetInst *MI);
449
450
451     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
452
453     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
454                                     unsigned CastOpc, int &NumCastsRemoved);
455     unsigned GetOrEnforceKnownAlignment(Value *V,
456                                         unsigned PrefAlign = 0);
457
458   };
459 } // end anonymous namespace
460
461 char InstCombiner::ID = 0;
462 static RegisterPass<InstCombiner>
463 X("instcombine", "Combine redundant instructions");
464
465 // getComplexity:  Assign a complexity or rank value to LLVM Values...
466 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
467 static unsigned getComplexity(Value *V) {
468   if (isa<Instruction>(V)) {
469     if (BinaryOperator::isNeg(V) ||
470         BinaryOperator::isFNeg(V) ||
471         BinaryOperator::isNot(V))
472       return 3;
473     return 4;
474   }
475   if (isa<Argument>(V)) return 3;
476   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
477 }
478
479 // isOnlyUse - Return true if this instruction will be deleted if we stop using
480 // it.
481 static bool isOnlyUse(Value *V) {
482   return V->hasOneUse() || isa<Constant>(V);
483 }
484
485 // getPromotedType - Return the specified type promoted as it would be to pass
486 // though a va_arg area...
487 static const Type *getPromotedType(const Type *Ty) {
488   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
489     if (ITy->getBitWidth() < 32)
490       return Type::getInt32Ty(Ty->getContext());
491   }
492   return Ty;
493 }
494
495 /// ShouldChangeType - Return true if it is desirable to convert a computation
496 /// from 'From' to 'To'.  We don't want to convert from a legal to an illegal
497 /// type for example, or from a smaller to a larger illegal type.
498 static bool ShouldChangeType(const Type *From, const Type *To,
499                              const TargetData *TD) {
500   assert(isa<IntegerType>(From) && isa<IntegerType>(To));
501   
502   // If we don't have TD, we don't know if the source/dest are legal.
503   if (!TD) return false;
504   
505   unsigned FromWidth = From->getPrimitiveSizeInBits();
506   unsigned ToWidth = To->getPrimitiveSizeInBits();
507   bool FromLegal = TD->isLegalInteger(FromWidth);
508   bool ToLegal = TD->isLegalInteger(ToWidth);
509   
510   // If this is a legal integer from type, and the result would be an illegal
511   // type, don't do the transformation.
512   if (FromLegal && !ToLegal)
513     return false;
514   
515   // Otherwise, if both are illegal, do not increase the size of the result. We
516   // do allow things like i160 -> i64, but not i64 -> i160.
517   if (!FromLegal && !ToLegal && ToWidth > FromWidth)
518     return false;
519   
520   return true;
521 }
522
523 /// getBitCastOperand - If the specified operand is a CastInst, a constant
524 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
525 /// operand value, otherwise return null.
526 static Value *getBitCastOperand(Value *V) {
527   if (Operator *O = dyn_cast<Operator>(V)) {
528     if (O->getOpcode() == Instruction::BitCast)
529       return O->getOperand(0);
530     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
531       if (GEP->hasAllZeroIndices())
532         return GEP->getPointerOperand();
533   }
534   return 0;
535 }
536
537 /// This function is a wrapper around CastInst::isEliminableCastPair. It
538 /// simply extracts arguments and returns what that function returns.
539 static Instruction::CastOps 
540 isEliminableCastPair(
541   const CastInst *CI, ///< The first cast instruction
542   unsigned opcode,       ///< The opcode of the second cast instruction
543   const Type *DstTy,     ///< The target type for the second cast instruction
544   TargetData *TD         ///< The target data for pointer size
545 ) {
546
547   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
548   const Type *MidTy = CI->getType();                  // B from above
549
550   // Get the opcodes of the two Cast instructions
551   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
552   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
553
554   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
555                                                 DstTy,
556                                   TD ? TD->getIntPtrType(CI->getContext()) : 0);
557   
558   // We don't want to form an inttoptr or ptrtoint that converts to an integer
559   // type that differs from the pointer size.
560   if ((Res == Instruction::IntToPtr &&
561           (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
562       (Res == Instruction::PtrToInt &&
563           (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
564     Res = 0;
565   
566   return Instruction::CastOps(Res);
567 }
568
569 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
570 /// in any code being generated.  It does not require codegen if V is simple
571 /// enough or if the cast can be folded into other casts.
572 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
573                               const Type *Ty, TargetData *TD) {
574   if (V->getType() == Ty || isa<Constant>(V)) return false;
575   
576   // If this is another cast that can be eliminated, it isn't codegen either.
577   if (const CastInst *CI = dyn_cast<CastInst>(V))
578     if (isEliminableCastPair(CI, opcode, Ty, TD))
579       return false;
580   return true;
581 }
582
583 // SimplifyCommutative - This performs a few simplifications for commutative
584 // operators:
585 //
586 //  1. Order operands such that they are listed from right (least complex) to
587 //     left (most complex).  This puts constants before unary operators before
588 //     binary operators.
589 //
590 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
591 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
592 //
593 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
594   bool Changed = false;
595   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
596     Changed = !I.swapOperands();
597
598   if (!I.isAssociative()) return Changed;
599   Instruction::BinaryOps Opcode = I.getOpcode();
600   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
601     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
602       if (isa<Constant>(I.getOperand(1))) {
603         Constant *Folded = ConstantExpr::get(I.getOpcode(),
604                                              cast<Constant>(I.getOperand(1)),
605                                              cast<Constant>(Op->getOperand(1)));
606         I.setOperand(0, Op->getOperand(0));
607         I.setOperand(1, Folded);
608         return true;
609       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
610         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
611             isOnlyUse(Op) && isOnlyUse(Op1)) {
612           Constant *C1 = cast<Constant>(Op->getOperand(1));
613           Constant *C2 = cast<Constant>(Op1->getOperand(1));
614
615           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
616           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
617           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
618                                                     Op1->getOperand(0),
619                                                     Op1->getName(), &I);
620           Worklist.Add(New);
621           I.setOperand(0, New);
622           I.setOperand(1, Folded);
623           return true;
624         }
625     }
626   return Changed;
627 }
628
629 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
630 // if the LHS is a constant zero (which is the 'negate' form).
631 //
632 static inline Value *dyn_castNegVal(Value *V) {
633   if (BinaryOperator::isNeg(V))
634     return BinaryOperator::getNegArgument(V);
635
636   // Constants can be considered to be negated values if they can be folded.
637   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
638     return ConstantExpr::getNeg(C);
639
640   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
641     if (C->getType()->getElementType()->isInteger())
642       return ConstantExpr::getNeg(C);
643
644   return 0;
645 }
646
647 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
648 // instruction if the LHS is a constant negative zero (which is the 'negate'
649 // form).
650 //
651 static inline Value *dyn_castFNegVal(Value *V) {
652   if (BinaryOperator::isFNeg(V))
653     return BinaryOperator::getFNegArgument(V);
654
655   // Constants can be considered to be negated values if they can be folded.
656   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
657     return ConstantExpr::getFNeg(C);
658
659   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
660     if (C->getType()->getElementType()->isFloatingPoint())
661       return ConstantExpr::getFNeg(C);
662
663   return 0;
664 }
665
666 /// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
667 /// returning the kind and providing the out parameter results if we
668 /// successfully match.
669 static SelectPatternFlavor
670 MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
671   SelectInst *SI = dyn_cast<SelectInst>(V);
672   if (SI == 0) return SPF_UNKNOWN;
673   
674   ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
675   if (ICI == 0) return SPF_UNKNOWN;
676   
677   LHS = ICI->getOperand(0);
678   RHS = ICI->getOperand(1);
679   
680   // (icmp X, Y) ? X : Y 
681   if (SI->getTrueValue() == ICI->getOperand(0) &&
682       SI->getFalseValue() == ICI->getOperand(1)) {
683     switch (ICI->getPredicate()) {
684     default: return SPF_UNKNOWN; // Equality.
685     case ICmpInst::ICMP_UGT:
686     case ICmpInst::ICMP_UGE: return SPF_UMAX;
687     case ICmpInst::ICMP_SGT:
688     case ICmpInst::ICMP_SGE: return SPF_SMAX;
689     case ICmpInst::ICMP_ULT:
690     case ICmpInst::ICMP_ULE: return SPF_UMIN;
691     case ICmpInst::ICMP_SLT:
692     case ICmpInst::ICMP_SLE: return SPF_SMIN;
693     }
694   }
695   
696   // (icmp X, Y) ? Y : X 
697   if (SI->getTrueValue() == ICI->getOperand(1) &&
698       SI->getFalseValue() == ICI->getOperand(0)) {
699     switch (ICI->getPredicate()) {
700       default: return SPF_UNKNOWN; // Equality.
701       case ICmpInst::ICMP_UGT:
702       case ICmpInst::ICMP_UGE: return SPF_UMIN;
703       case ICmpInst::ICMP_SGT:
704       case ICmpInst::ICMP_SGE: return SPF_SMIN;
705       case ICmpInst::ICMP_ULT:
706       case ICmpInst::ICMP_ULE: return SPF_UMAX;
707       case ICmpInst::ICMP_SLT:
708       case ICmpInst::ICMP_SLE: return SPF_SMAX;
709     }
710   }
711   
712   // TODO: (X > 4) ? X : 5   -->  (X >= 5) ? X : 5  -->  MAX(X, 5)
713   
714   return SPF_UNKNOWN;
715 }
716
717 /// isFreeToInvert - Return true if the specified value is free to invert (apply
718 /// ~ to).  This happens in cases where the ~ can be eliminated.
719 static inline bool isFreeToInvert(Value *V) {
720   // ~(~(X)) -> X.
721   if (BinaryOperator::isNot(V))
722     return true;
723   
724   // Constants can be considered to be not'ed values.
725   if (isa<ConstantInt>(V))
726     return true;
727   
728   // Compares can be inverted if they have a single use.
729   if (CmpInst *CI = dyn_cast<CmpInst>(V))
730     return CI->hasOneUse();
731   
732   return false;
733 }
734
735 static inline Value *dyn_castNotVal(Value *V) {
736   // If this is not(not(x)) don't return that this is a not: we want the two
737   // not's to be folded first.
738   if (BinaryOperator::isNot(V)) {
739     Value *Operand = BinaryOperator::getNotArgument(V);
740     if (!isFreeToInvert(Operand))
741       return Operand;
742   }
743
744   // Constants can be considered to be not'ed values...
745   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
746     return ConstantInt::get(C->getType(), ~C->getValue());
747   return 0;
748 }
749
750
751
752 // dyn_castFoldableMul - If this value is a multiply that can be folded into
753 // other computations (because it has a constant operand), return the
754 // non-constant operand of the multiply, and set CST to point to the multiplier.
755 // Otherwise, return null.
756 //
757 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
758   if (V->hasOneUse() && V->getType()->isInteger())
759     if (Instruction *I = dyn_cast<Instruction>(V)) {
760       if (I->getOpcode() == Instruction::Mul)
761         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
762           return I->getOperand(0);
763       if (I->getOpcode() == Instruction::Shl)
764         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
765           // The multiplier is really 1 << CST.
766           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
767           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
768           CST = ConstantInt::get(V->getType()->getContext(),
769                                  APInt(BitWidth, 1).shl(CSTVal));
770           return I->getOperand(0);
771         }
772     }
773   return 0;
774 }
775
776 /// AddOne - Add one to a ConstantInt
777 static Constant *AddOne(Constant *C) {
778   return ConstantExpr::getAdd(C, 
779     ConstantInt::get(C->getType(), 1));
780 }
781 /// SubOne - Subtract one from a ConstantInt
782 static Constant *SubOne(ConstantInt *C) {
783   return ConstantExpr::getSub(C, 
784     ConstantInt::get(C->getType(), 1));
785 }
786 /// MultiplyOverflows - True if the multiply can not be expressed in an int
787 /// this size.
788 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
789   uint32_t W = C1->getBitWidth();
790   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
791   if (sign) {
792     LHSExt.sext(W * 2);
793     RHSExt.sext(W * 2);
794   } else {
795     LHSExt.zext(W * 2);
796     RHSExt.zext(W * 2);
797   }
798
799   APInt MulExt = LHSExt * RHSExt;
800
801   if (!sign)
802     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
803   
804   APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
805   APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
806   return MulExt.slt(Min) || MulExt.sgt(Max);
807 }
808
809
810 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
811 /// specified instruction is a constant integer.  If so, check to see if there
812 /// are any bits set in the constant that are not demanded.  If so, shrink the
813 /// constant and return true.
814 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
815                                    APInt Demanded) {
816   assert(I && "No instruction?");
817   assert(OpNo < I->getNumOperands() && "Operand index too large");
818
819   // If the operand is not a constant integer, nothing to do.
820   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
821   if (!OpC) return false;
822
823   // If there are no bits set that aren't demanded, nothing to do.
824   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
825   if ((~Demanded & OpC->getValue()) == 0)
826     return false;
827
828   // This instruction is producing bits that are not demanded. Shrink the RHS.
829   Demanded &= OpC->getValue();
830   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
831   return true;
832 }
833
834 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
835 // set of known zero and one bits, compute the maximum and minimum values that
836 // could have the specified known zero and known one bits, returning them in
837 // min/max.
838 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
839                                                    const APInt& KnownOne,
840                                                    APInt& Min, APInt& Max) {
841   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
842          KnownZero.getBitWidth() == Min.getBitWidth() &&
843          KnownZero.getBitWidth() == Max.getBitWidth() &&
844          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
845   APInt UnknownBits = ~(KnownZero|KnownOne);
846
847   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
848   // bit if it is unknown.
849   Min = KnownOne;
850   Max = KnownOne|UnknownBits;
851   
852   if (UnknownBits.isNegative()) { // Sign bit is unknown
853     Min.set(Min.getBitWidth()-1);
854     Max.clear(Max.getBitWidth()-1);
855   }
856 }
857
858 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
859 // a set of known zero and one bits, compute the maximum and minimum values that
860 // could have the specified known zero and known one bits, returning them in
861 // min/max.
862 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
863                                                      const APInt &KnownOne,
864                                                      APInt &Min, APInt &Max) {
865   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
866          KnownZero.getBitWidth() == Min.getBitWidth() &&
867          KnownZero.getBitWidth() == Max.getBitWidth() &&
868          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
869   APInt UnknownBits = ~(KnownZero|KnownOne);
870   
871   // The minimum value is when the unknown bits are all zeros.
872   Min = KnownOne;
873   // The maximum value is when the unknown bits are all ones.
874   Max = KnownOne|UnknownBits;
875 }
876
877 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
878 /// SimplifyDemandedBits knows about.  See if the instruction has any
879 /// properties that allow us to simplify its operands.
880 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
881   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
882   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
883   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
884   
885   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
886                                      KnownZero, KnownOne, 0);
887   if (V == 0) return false;
888   if (V == &Inst) return true;
889   ReplaceInstUsesWith(Inst, V);
890   return true;
891 }
892
893 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
894 /// specified instruction operand if possible, updating it in place.  It returns
895 /// true if it made any change and false otherwise.
896 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
897                                         APInt &KnownZero, APInt &KnownOne,
898                                         unsigned Depth) {
899   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
900                                           KnownZero, KnownOne, Depth);
901   if (NewVal == 0) return false;
902   U = NewVal;
903   return true;
904 }
905
906
907 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
908 /// value based on the demanded bits.  When this function is called, it is known
909 /// that only the bits set in DemandedMask of the result of V are ever used
910 /// downstream. Consequently, depending on the mask and V, it may be possible
911 /// to replace V with a constant or one of its operands. In such cases, this
912 /// function does the replacement and returns true. In all other cases, it
913 /// returns false after analyzing the expression and setting KnownOne and known
914 /// to be one in the expression.  KnownZero contains all the bits that are known
915 /// to be zero in the expression. These are provided to potentially allow the
916 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
917 /// the expression. KnownOne and KnownZero always follow the invariant that 
918 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
919 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
920 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
921 /// and KnownOne must all be the same.
922 ///
923 /// This returns null if it did not change anything and it permits no
924 /// simplification.  This returns V itself if it did some simplification of V's
925 /// operands based on the information about what bits are demanded. This returns
926 /// some other non-null value if it found out that V is equal to another value
927 /// in the context where the specified bits are demanded, but not for all users.
928 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
929                                              APInt &KnownZero, APInt &KnownOne,
930                                              unsigned Depth) {
931   assert(V != 0 && "Null pointer of Value???");
932   assert(Depth <= 6 && "Limit Search Depth");
933   uint32_t BitWidth = DemandedMask.getBitWidth();
934   const Type *VTy = V->getType();
935   assert((TD || !isa<PointerType>(VTy)) &&
936          "SimplifyDemandedBits needs to know bit widths!");
937   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
938          (!VTy->isIntOrIntVector() ||
939           VTy->getScalarSizeInBits() == BitWidth) &&
940          KnownZero.getBitWidth() == BitWidth &&
941          KnownOne.getBitWidth() == BitWidth &&
942          "Value *V, DemandedMask, KnownZero and KnownOne "
943          "must have same BitWidth");
944   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
945     // We know all of the bits for a constant!
946     KnownOne = CI->getValue() & DemandedMask;
947     KnownZero = ~KnownOne & DemandedMask;
948     return 0;
949   }
950   if (isa<ConstantPointerNull>(V)) {
951     // We know all of the bits for a constant!
952     KnownOne.clear();
953     KnownZero = DemandedMask;
954     return 0;
955   }
956
957   KnownZero.clear();
958   KnownOne.clear();
959   if (DemandedMask == 0) {   // Not demanding any bits from V.
960     if (isa<UndefValue>(V))
961       return 0;
962     return UndefValue::get(VTy);
963   }
964   
965   if (Depth == 6)        // Limit search depth.
966     return 0;
967   
968   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
969   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
970
971   Instruction *I = dyn_cast<Instruction>(V);
972   if (!I) {
973     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
974     return 0;        // Only analyze instructions.
975   }
976
977   // If there are multiple uses of this value and we aren't at the root, then
978   // we can't do any simplifications of the operands, because DemandedMask
979   // only reflects the bits demanded by *one* of the users.
980   if (Depth != 0 && !I->hasOneUse()) {
981     // Despite the fact that we can't simplify this instruction in all User's
982     // context, we can at least compute the knownzero/knownone bits, and we can
983     // do simplifications that apply to *just* the one user if we know that
984     // this instruction has a simpler value in that context.
985     if (I->getOpcode() == Instruction::And) {
986       // If either the LHS or the RHS are Zero, the result is zero.
987       ComputeMaskedBits(I->getOperand(1), DemandedMask,
988                         RHSKnownZero, RHSKnownOne, Depth+1);
989       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
990                         LHSKnownZero, LHSKnownOne, Depth+1);
991       
992       // If all of the demanded bits are known 1 on one side, return the other.
993       // These bits cannot contribute to the result of the 'and' in this
994       // context.
995       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
996           (DemandedMask & ~LHSKnownZero))
997         return I->getOperand(0);
998       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
999           (DemandedMask & ~RHSKnownZero))
1000         return I->getOperand(1);
1001       
1002       // If all of the demanded bits in the inputs are known zeros, return zero.
1003       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1004         return Constant::getNullValue(VTy);
1005       
1006     } else if (I->getOpcode() == Instruction::Or) {
1007       // We can simplify (X|Y) -> X or Y in the user's context if we know that
1008       // only bits from X or Y are demanded.
1009       
1010       // If either the LHS or the RHS are One, the result is One.
1011       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
1012                         RHSKnownZero, RHSKnownOne, Depth+1);
1013       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
1014                         LHSKnownZero, LHSKnownOne, Depth+1);
1015       
1016       // If all of the demanded bits are known zero on one side, return the
1017       // other.  These bits cannot contribute to the result of the 'or' in this
1018       // context.
1019       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
1020           (DemandedMask & ~LHSKnownOne))
1021         return I->getOperand(0);
1022       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
1023           (DemandedMask & ~RHSKnownOne))
1024         return I->getOperand(1);
1025       
1026       // If all of the potentially set bits on one side are known to be set on
1027       // the other side, just use the 'other' side.
1028       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
1029           (DemandedMask & (~RHSKnownZero)))
1030         return I->getOperand(0);
1031       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1032           (DemandedMask & (~LHSKnownZero)))
1033         return I->getOperand(1);
1034     }
1035     
1036     // Compute the KnownZero/KnownOne bits to simplify things downstream.
1037     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
1038     return 0;
1039   }
1040   
1041   // If this is the root being simplified, allow it to have multiple uses,
1042   // just set the DemandedMask to all bits so that we can try to simplify the
1043   // operands.  This allows visitTruncInst (for example) to simplify the
1044   // operand of a trunc without duplicating all the logic below.
1045   if (Depth == 0 && !V->hasOneUse())
1046     DemandedMask = APInt::getAllOnesValue(BitWidth);
1047   
1048   switch (I->getOpcode()) {
1049   default:
1050     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1051     break;
1052   case Instruction::And:
1053     // If either the LHS or the RHS are Zero, the result is zero.
1054     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1055                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1056         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
1057                              LHSKnownZero, LHSKnownOne, Depth+1))
1058       return I;
1059     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1060     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1061
1062     // If all of the demanded bits are known 1 on one side, return the other.
1063     // These bits cannot contribute to the result of the 'and'.
1064     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
1065         (DemandedMask & ~LHSKnownZero))
1066       return I->getOperand(0);
1067     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
1068         (DemandedMask & ~RHSKnownZero))
1069       return I->getOperand(1);
1070     
1071     // If all of the demanded bits in the inputs are known zeros, return zero.
1072     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1073       return Constant::getNullValue(VTy);
1074       
1075     // If the RHS is a constant, see if we can simplify it.
1076     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1077       return I;
1078       
1079     // Output known-1 bits are only known if set in both the LHS & RHS.
1080     RHSKnownOne &= LHSKnownOne;
1081     // Output known-0 are known to be clear if zero in either the LHS | RHS.
1082     RHSKnownZero |= LHSKnownZero;
1083     break;
1084   case Instruction::Or:
1085     // If either the LHS or the RHS are One, the result is One.
1086     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1087                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1088         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
1089                              LHSKnownZero, LHSKnownOne, Depth+1))
1090       return I;
1091     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1092     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1093     
1094     // If all of the demanded bits are known zero on one side, return the other.
1095     // These bits cannot contribute to the result of the 'or'.
1096     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
1097         (DemandedMask & ~LHSKnownOne))
1098       return I->getOperand(0);
1099     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
1100         (DemandedMask & ~RHSKnownOne))
1101       return I->getOperand(1);
1102
1103     // If all of the potentially set bits on one side are known to be set on
1104     // the other side, just use the 'other' side.
1105     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
1106         (DemandedMask & (~RHSKnownZero)))
1107       return I->getOperand(0);
1108     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1109         (DemandedMask & (~LHSKnownZero)))
1110       return I->getOperand(1);
1111         
1112     // If the RHS is a constant, see if we can simplify it.
1113     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1114       return I;
1115           
1116     // Output known-0 bits are only known if clear in both the LHS & RHS.
1117     RHSKnownZero &= LHSKnownZero;
1118     // Output known-1 are known to be set if set in either the LHS | RHS.
1119     RHSKnownOne |= LHSKnownOne;
1120     break;
1121   case Instruction::Xor: {
1122     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1123                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1124         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1125                              LHSKnownZero, LHSKnownOne, Depth+1))
1126       return I;
1127     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1128     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1129     
1130     // If all of the demanded bits are known zero on one side, return the other.
1131     // These bits cannot contribute to the result of the 'xor'.
1132     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1133       return I->getOperand(0);
1134     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1135       return I->getOperand(1);
1136     
1137     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1138     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1139                          (RHSKnownOne & LHSKnownOne);
1140     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1141     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1142                         (RHSKnownOne & LHSKnownZero);
1143     
1144     // If all of the demanded bits are known to be zero on one side or the
1145     // other, turn this into an *inclusive* or.
1146     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1147     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1148       Instruction *Or = 
1149         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1150                                  I->getName());
1151       return InsertNewInstBefore(Or, *I);
1152     }
1153     
1154     // If all of the demanded bits on one side are known, and all of the set
1155     // bits on that side are also known to be set on the other side, turn this
1156     // into an AND, as we know the bits will be cleared.
1157     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1158     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1159       // all known
1160       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1161         Constant *AndC = Constant::getIntegerValue(VTy,
1162                                                    ~RHSKnownOne & DemandedMask);
1163         Instruction *And = 
1164           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1165         return InsertNewInstBefore(And, *I);
1166       }
1167     }
1168     
1169     // If the RHS is a constant, see if we can simplify it.
1170     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1171     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1172       return I;
1173     
1174     // If our LHS is an 'and' and if it has one use, and if any of the bits we
1175     // are flipping are known to be set, then the xor is just resetting those
1176     // bits to zero.  We can just knock out bits from the 'and' and the 'xor',
1177     // simplifying both of them.
1178     if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1179       if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1180           isa<ConstantInt>(I->getOperand(1)) &&
1181           isa<ConstantInt>(LHSInst->getOperand(1)) &&
1182           (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1183         ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1184         ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1185         APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1186         
1187         Constant *AndC =
1188           ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1189         Instruction *NewAnd = 
1190           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1191         InsertNewInstBefore(NewAnd, *I);
1192         
1193         Constant *XorC =
1194           ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1195         Instruction *NewXor =
1196           BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1197         return InsertNewInstBefore(NewXor, *I);
1198       }
1199           
1200           
1201     RHSKnownZero = KnownZeroOut;
1202     RHSKnownOne  = KnownOneOut;
1203     break;
1204   }
1205   case Instruction::Select:
1206     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1207                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1208         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1209                              LHSKnownZero, LHSKnownOne, Depth+1))
1210       return I;
1211     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1212     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1213     
1214     // If the operands are constants, see if we can simplify them.
1215     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1216         ShrinkDemandedConstant(I, 2, DemandedMask))
1217       return I;
1218     
1219     // Only known if known in both the LHS and RHS.
1220     RHSKnownOne &= LHSKnownOne;
1221     RHSKnownZero &= LHSKnownZero;
1222     break;
1223   case Instruction::Trunc: {
1224     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1225     DemandedMask.zext(truncBf);
1226     RHSKnownZero.zext(truncBf);
1227     RHSKnownOne.zext(truncBf);
1228     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1229                              RHSKnownZero, RHSKnownOne, Depth+1))
1230       return I;
1231     DemandedMask.trunc(BitWidth);
1232     RHSKnownZero.trunc(BitWidth);
1233     RHSKnownOne.trunc(BitWidth);
1234     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1235     break;
1236   }
1237   case Instruction::BitCast:
1238     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1239       return false;  // vector->int or fp->int?
1240
1241     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1242       if (const VectorType *SrcVTy =
1243             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1244         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1245           // Don't touch a bitcast between vectors of different element counts.
1246           return false;
1247       } else
1248         // Don't touch a scalar-to-vector bitcast.
1249         return false;
1250     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1251       // Don't touch a vector-to-scalar bitcast.
1252       return false;
1253
1254     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1255                              RHSKnownZero, RHSKnownOne, Depth+1))
1256       return I;
1257     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1258     break;
1259   case Instruction::ZExt: {
1260     // Compute the bits in the result that are not present in the input.
1261     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1262     
1263     DemandedMask.trunc(SrcBitWidth);
1264     RHSKnownZero.trunc(SrcBitWidth);
1265     RHSKnownOne.trunc(SrcBitWidth);
1266     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1267                              RHSKnownZero, RHSKnownOne, Depth+1))
1268       return I;
1269     DemandedMask.zext(BitWidth);
1270     RHSKnownZero.zext(BitWidth);
1271     RHSKnownOne.zext(BitWidth);
1272     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1273     // The top bits are known to be zero.
1274     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1275     break;
1276   }
1277   case Instruction::SExt: {
1278     // Compute the bits in the result that are not present in the input.
1279     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1280     
1281     APInt InputDemandedBits = DemandedMask & 
1282                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1283
1284     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1285     // If any of the sign extended bits are demanded, we know that the sign
1286     // bit is demanded.
1287     if ((NewBits & DemandedMask) != 0)
1288       InputDemandedBits.set(SrcBitWidth-1);
1289       
1290     InputDemandedBits.trunc(SrcBitWidth);
1291     RHSKnownZero.trunc(SrcBitWidth);
1292     RHSKnownOne.trunc(SrcBitWidth);
1293     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1294                              RHSKnownZero, RHSKnownOne, Depth+1))
1295       return I;
1296     InputDemandedBits.zext(BitWidth);
1297     RHSKnownZero.zext(BitWidth);
1298     RHSKnownOne.zext(BitWidth);
1299     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1300       
1301     // If the sign bit of the input is known set or clear, then we know the
1302     // top bits of the result.
1303
1304     // If the input sign bit is known zero, or if the NewBits are not demanded
1305     // convert this into a zero extension.
1306     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1307       // Convert to ZExt cast
1308       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1309       return InsertNewInstBefore(NewCast, *I);
1310     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1311       RHSKnownOne |= NewBits;
1312     }
1313     break;
1314   }
1315   case Instruction::Add: {
1316     // Figure out what the input bits are.  If the top bits of the and result
1317     // are not demanded, then the add doesn't demand them from its input
1318     // either.
1319     unsigned NLZ = DemandedMask.countLeadingZeros();
1320       
1321     // If there is a constant on the RHS, there are a variety of xformations
1322     // we can do.
1323     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1324       // If null, this should be simplified elsewhere.  Some of the xforms here
1325       // won't work if the RHS is zero.
1326       if (RHS->isZero())
1327         break;
1328       
1329       // If the top bit of the output is demanded, demand everything from the
1330       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1331       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1332
1333       // Find information about known zero/one bits in the input.
1334       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1335                                LHSKnownZero, LHSKnownOne, Depth+1))
1336         return I;
1337
1338       // If the RHS of the add has bits set that can't affect the input, reduce
1339       // the constant.
1340       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1341         return I;
1342       
1343       // Avoid excess work.
1344       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1345         break;
1346       
1347       // Turn it into OR if input bits are zero.
1348       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1349         Instruction *Or =
1350           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1351                                    I->getName());
1352         return InsertNewInstBefore(Or, *I);
1353       }
1354       
1355       // We can say something about the output known-zero and known-one bits,
1356       // depending on potential carries from the input constant and the
1357       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1358       // bits set and the RHS constant is 0x01001, then we know we have a known
1359       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1360       
1361       // To compute this, we first compute the potential carry bits.  These are
1362       // the bits which may be modified.  I'm not aware of a better way to do
1363       // this scan.
1364       const APInt &RHSVal = RHS->getValue();
1365       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1366       
1367       // Now that we know which bits have carries, compute the known-1/0 sets.
1368       
1369       // Bits are known one if they are known zero in one operand and one in the
1370       // other, and there is no input carry.
1371       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1372                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1373       
1374       // Bits are known zero if they are known zero in both operands and there
1375       // is no input carry.
1376       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1377     } else {
1378       // If the high-bits of this ADD are not demanded, then it does not demand
1379       // the high bits of its LHS or RHS.
1380       if (DemandedMask[BitWidth-1] == 0) {
1381         // Right fill the mask of bits for this ADD to demand the most
1382         // significant bit and all those below it.
1383         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1384         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1385                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1386             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1387                                  LHSKnownZero, LHSKnownOne, Depth+1))
1388           return I;
1389       }
1390     }
1391     break;
1392   }
1393   case Instruction::Sub:
1394     // If the high-bits of this SUB are not demanded, then it does not demand
1395     // the high bits of its LHS or RHS.
1396     if (DemandedMask[BitWidth-1] == 0) {
1397       // Right fill the mask of bits for this SUB to demand the most
1398       // significant bit and all those below it.
1399       uint32_t NLZ = DemandedMask.countLeadingZeros();
1400       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1401       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1402                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1403           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1404                                LHSKnownZero, LHSKnownOne, Depth+1))
1405         return I;
1406     }
1407     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1408     // the known zeros and ones.
1409     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1410     break;
1411   case Instruction::Shl:
1412     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1413       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1414       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1415       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1416                                RHSKnownZero, RHSKnownOne, Depth+1))
1417         return I;
1418       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1419       RHSKnownZero <<= ShiftAmt;
1420       RHSKnownOne  <<= ShiftAmt;
1421       // low bits known zero.
1422       if (ShiftAmt)
1423         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1424     }
1425     break;
1426   case Instruction::LShr:
1427     // For a logical shift right
1428     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1429       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1430       
1431       // Unsigned shift right.
1432       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1433       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1434                                RHSKnownZero, RHSKnownOne, Depth+1))
1435         return I;
1436       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1437       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1438       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1439       if (ShiftAmt) {
1440         // Compute the new bits that are at the top now.
1441         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1442         RHSKnownZero |= HighBits;  // high bits known zero.
1443       }
1444     }
1445     break;
1446   case Instruction::AShr:
1447     // If this is an arithmetic shift right and only the low-bit is set, we can
1448     // always convert this into a logical shr, even if the shift amount is
1449     // variable.  The low bit of the shift cannot be an input sign bit unless
1450     // the shift amount is >= the size of the datatype, which is undefined.
1451     if (DemandedMask == 1) {
1452       // Perform the logical shift right.
1453       Instruction *NewVal = BinaryOperator::CreateLShr(
1454                         I->getOperand(0), I->getOperand(1), I->getName());
1455       return InsertNewInstBefore(NewVal, *I);
1456     }    
1457
1458     // If the sign bit is the only bit demanded by this ashr, then there is no
1459     // need to do it, the shift doesn't change the high bit.
1460     if (DemandedMask.isSignBit())
1461       return I->getOperand(0);
1462     
1463     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1464       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1465       
1466       // Signed shift right.
1467       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1468       // If any of the "high bits" are demanded, we should set the sign bit as
1469       // demanded.
1470       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1471         DemandedMaskIn.set(BitWidth-1);
1472       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1473                                RHSKnownZero, RHSKnownOne, Depth+1))
1474         return I;
1475       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1476       // Compute the new bits that are at the top now.
1477       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1478       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1479       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1480         
1481       // Handle the sign bits.
1482       APInt SignBit(APInt::getSignBit(BitWidth));
1483       // Adjust to where it is now in the mask.
1484       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1485         
1486       // If the input sign bit is known to be zero, or if none of the top bits
1487       // are demanded, turn this into an unsigned shift right.
1488       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1489           (HighBits & ~DemandedMask) == HighBits) {
1490         // Perform the logical shift right.
1491         Instruction *NewVal = BinaryOperator::CreateLShr(
1492                           I->getOperand(0), SA, I->getName());
1493         return InsertNewInstBefore(NewVal, *I);
1494       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1495         RHSKnownOne |= HighBits;
1496       }
1497     }
1498     break;
1499   case Instruction::SRem:
1500     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1501       APInt RA = Rem->getValue().abs();
1502       if (RA.isPowerOf2()) {
1503         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1504           return I->getOperand(0);
1505
1506         APInt LowBits = RA - 1;
1507         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1508         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1509                                  LHSKnownZero, LHSKnownOne, Depth+1))
1510           return I;
1511
1512         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1513           LHSKnownZero |= ~LowBits;
1514
1515         KnownZero |= LHSKnownZero & DemandedMask;
1516
1517         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1518       }
1519     }
1520     break;
1521   case Instruction::URem: {
1522     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1523     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1524     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1525                              KnownZero2, KnownOne2, Depth+1) ||
1526         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1527                              KnownZero2, KnownOne2, Depth+1))
1528       return I;
1529
1530     unsigned Leaders = KnownZero2.countLeadingOnes();
1531     Leaders = std::max(Leaders,
1532                        KnownZero2.countLeadingOnes());
1533     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1534     break;
1535   }
1536   case Instruction::Call:
1537     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1538       switch (II->getIntrinsicID()) {
1539       default: break;
1540       case Intrinsic::bswap: {
1541         // If the only bits demanded come from one byte of the bswap result,
1542         // just shift the input byte into position to eliminate the bswap.
1543         unsigned NLZ = DemandedMask.countLeadingZeros();
1544         unsigned NTZ = DemandedMask.countTrailingZeros();
1545           
1546         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1547         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1548         // have 14 leading zeros, round to 8.
1549         NLZ &= ~7;
1550         NTZ &= ~7;
1551         // If we need exactly one byte, we can do this transformation.
1552         if (BitWidth-NLZ-NTZ == 8) {
1553           unsigned ResultBit = NTZ;
1554           unsigned InputBit = BitWidth-NTZ-8;
1555           
1556           // Replace this with either a left or right shift to get the byte into
1557           // the right place.
1558           Instruction *NewVal;
1559           if (InputBit > ResultBit)
1560             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1561                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1562           else
1563             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1564                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1565           NewVal->takeName(I);
1566           return InsertNewInstBefore(NewVal, *I);
1567         }
1568           
1569         // TODO: Could compute known zero/one bits based on the input.
1570         break;
1571       }
1572       }
1573     }
1574     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1575     break;
1576   }
1577   
1578   // If the client is only demanding bits that we know, return the known
1579   // constant.
1580   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1581     return Constant::getIntegerValue(VTy, RHSKnownOne);
1582   return false;
1583 }
1584
1585
1586 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1587 /// any number of elements. DemandedElts contains the set of elements that are
1588 /// actually used by the caller.  This method analyzes which elements of the
1589 /// operand are undef and returns that information in UndefElts.
1590 ///
1591 /// If the information about demanded elements can be used to simplify the
1592 /// operation, the operation is simplified, then the resultant value is
1593 /// returned.  This returns null if no change was made.
1594 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1595                                                 APInt& UndefElts,
1596                                                 unsigned Depth) {
1597   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1598   APInt EltMask(APInt::getAllOnesValue(VWidth));
1599   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1600
1601   if (isa<UndefValue>(V)) {
1602     // If the entire vector is undefined, just return this info.
1603     UndefElts = EltMask;
1604     return 0;
1605   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1606     UndefElts = EltMask;
1607     return UndefValue::get(V->getType());
1608   }
1609
1610   UndefElts = 0;
1611   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1612     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1613     Constant *Undef = UndefValue::get(EltTy);
1614
1615     std::vector<Constant*> Elts;
1616     for (unsigned i = 0; i != VWidth; ++i)
1617       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1618         Elts.push_back(Undef);
1619         UndefElts.set(i);
1620       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1621         Elts.push_back(Undef);
1622         UndefElts.set(i);
1623       } else {                               // Otherwise, defined.
1624         Elts.push_back(CP->getOperand(i));
1625       }
1626
1627     // If we changed the constant, return it.
1628     Constant *NewCP = ConstantVector::get(Elts);
1629     return NewCP != CP ? NewCP : 0;
1630   } else if (isa<ConstantAggregateZero>(V)) {
1631     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1632     // set to undef.
1633     
1634     // Check if this is identity. If so, return 0 since we are not simplifying
1635     // anything.
1636     if (DemandedElts == ((1ULL << VWidth) -1))
1637       return 0;
1638     
1639     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1640     Constant *Zero = Constant::getNullValue(EltTy);
1641     Constant *Undef = UndefValue::get(EltTy);
1642     std::vector<Constant*> Elts;
1643     for (unsigned i = 0; i != VWidth; ++i) {
1644       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1645       Elts.push_back(Elt);
1646     }
1647     UndefElts = DemandedElts ^ EltMask;
1648     return ConstantVector::get(Elts);
1649   }
1650   
1651   // Limit search depth.
1652   if (Depth == 10)
1653     return 0;
1654
1655   // If multiple users are using the root value, procede with
1656   // simplification conservatively assuming that all elements
1657   // are needed.
1658   if (!V->hasOneUse()) {
1659     // Quit if we find multiple users of a non-root value though.
1660     // They'll be handled when it's their turn to be visited by
1661     // the main instcombine process.
1662     if (Depth != 0)
1663       // TODO: Just compute the UndefElts information recursively.
1664       return 0;
1665
1666     // Conservatively assume that all elements are needed.
1667     DemandedElts = EltMask;
1668   }
1669   
1670   Instruction *I = dyn_cast<Instruction>(V);
1671   if (!I) return 0;        // Only analyze instructions.
1672   
1673   bool MadeChange = false;
1674   APInt UndefElts2(VWidth, 0);
1675   Value *TmpV;
1676   switch (I->getOpcode()) {
1677   default: break;
1678     
1679   case Instruction::InsertElement: {
1680     // If this is a variable index, we don't know which element it overwrites.
1681     // demand exactly the same input as we produce.
1682     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1683     if (Idx == 0) {
1684       // Note that we can't propagate undef elt info, because we don't know
1685       // which elt is getting updated.
1686       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1687                                         UndefElts2, Depth+1);
1688       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1689       break;
1690     }
1691     
1692     // If this is inserting an element that isn't demanded, remove this
1693     // insertelement.
1694     unsigned IdxNo = Idx->getZExtValue();
1695     if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1696       Worklist.Add(I);
1697       return I->getOperand(0);
1698     }
1699     
1700     // Otherwise, the element inserted overwrites whatever was there, so the
1701     // input demanded set is simpler than the output set.
1702     APInt DemandedElts2 = DemandedElts;
1703     DemandedElts2.clear(IdxNo);
1704     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1705                                       UndefElts, Depth+1);
1706     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1707
1708     // The inserted element is defined.
1709     UndefElts.clear(IdxNo);
1710     break;
1711   }
1712   case Instruction::ShuffleVector: {
1713     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1714     uint64_t LHSVWidth =
1715       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1716     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1717     for (unsigned i = 0; i < VWidth; i++) {
1718       if (DemandedElts[i]) {
1719         unsigned MaskVal = Shuffle->getMaskValue(i);
1720         if (MaskVal != -1u) {
1721           assert(MaskVal < LHSVWidth * 2 &&
1722                  "shufflevector mask index out of range!");
1723           if (MaskVal < LHSVWidth)
1724             LeftDemanded.set(MaskVal);
1725           else
1726             RightDemanded.set(MaskVal - LHSVWidth);
1727         }
1728       }
1729     }
1730
1731     APInt UndefElts4(LHSVWidth, 0);
1732     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1733                                       UndefElts4, Depth+1);
1734     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1735
1736     APInt UndefElts3(LHSVWidth, 0);
1737     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1738                                       UndefElts3, Depth+1);
1739     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1740
1741     bool NewUndefElts = false;
1742     for (unsigned i = 0; i < VWidth; i++) {
1743       unsigned MaskVal = Shuffle->getMaskValue(i);
1744       if (MaskVal == -1u) {
1745         UndefElts.set(i);
1746       } else if (MaskVal < LHSVWidth) {
1747         if (UndefElts4[MaskVal]) {
1748           NewUndefElts = true;
1749           UndefElts.set(i);
1750         }
1751       } else {
1752         if (UndefElts3[MaskVal - LHSVWidth]) {
1753           NewUndefElts = true;
1754           UndefElts.set(i);
1755         }
1756       }
1757     }
1758
1759     if (NewUndefElts) {
1760       // Add additional discovered undefs.
1761       std::vector<Constant*> Elts;
1762       for (unsigned i = 0; i < VWidth; ++i) {
1763         if (UndefElts[i])
1764           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
1765         else
1766           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
1767                                           Shuffle->getMaskValue(i)));
1768       }
1769       I->setOperand(2, ConstantVector::get(Elts));
1770       MadeChange = true;
1771     }
1772     break;
1773   }
1774   case Instruction::BitCast: {
1775     // Vector->vector casts only.
1776     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1777     if (!VTy) break;
1778     unsigned InVWidth = VTy->getNumElements();
1779     APInt InputDemandedElts(InVWidth, 0);
1780     unsigned Ratio;
1781
1782     if (VWidth == InVWidth) {
1783       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1784       // elements as are demanded of us.
1785       Ratio = 1;
1786       InputDemandedElts = DemandedElts;
1787     } else if (VWidth > InVWidth) {
1788       // Untested so far.
1789       break;
1790       
1791       // If there are more elements in the result than there are in the source,
1792       // then an input element is live if any of the corresponding output
1793       // elements are live.
1794       Ratio = VWidth/InVWidth;
1795       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1796         if (DemandedElts[OutIdx])
1797           InputDemandedElts.set(OutIdx/Ratio);
1798       }
1799     } else {
1800       // Untested so far.
1801       break;
1802       
1803       // If there are more elements in the source than there are in the result,
1804       // then an input element is live if the corresponding output element is
1805       // live.
1806       Ratio = InVWidth/VWidth;
1807       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1808         if (DemandedElts[InIdx/Ratio])
1809           InputDemandedElts.set(InIdx);
1810     }
1811     
1812     // div/rem demand all inputs, because they don't want divide by zero.
1813     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1814                                       UndefElts2, Depth+1);
1815     if (TmpV) {
1816       I->setOperand(0, TmpV);
1817       MadeChange = true;
1818     }
1819     
1820     UndefElts = UndefElts2;
1821     if (VWidth > InVWidth) {
1822       llvm_unreachable("Unimp");
1823       // If there are more elements in the result than there are in the source,
1824       // then an output element is undef if the corresponding input element is
1825       // undef.
1826       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1827         if (UndefElts2[OutIdx/Ratio])
1828           UndefElts.set(OutIdx);
1829     } else if (VWidth < InVWidth) {
1830       llvm_unreachable("Unimp");
1831       // If there are more elements in the source than there are in the result,
1832       // then a result element is undef if all of the corresponding input
1833       // elements are undef.
1834       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1835       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1836         if (!UndefElts2[InIdx])            // Not undef?
1837           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1838     }
1839     break;
1840   }
1841   case Instruction::And:
1842   case Instruction::Or:
1843   case Instruction::Xor:
1844   case Instruction::Add:
1845   case Instruction::Sub:
1846   case Instruction::Mul:
1847     // div/rem demand all inputs, because they don't want divide by zero.
1848     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1849                                       UndefElts, Depth+1);
1850     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1851     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1852                                       UndefElts2, Depth+1);
1853     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1854       
1855     // Output elements are undefined if both are undefined.  Consider things
1856     // like undef&0.  The result is known zero, not undef.
1857     UndefElts &= UndefElts2;
1858     break;
1859     
1860   case Instruction::Call: {
1861     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1862     if (!II) break;
1863     switch (II->getIntrinsicID()) {
1864     default: break;
1865       
1866     // Binary vector operations that work column-wise.  A dest element is a
1867     // function of the corresponding input elements from the two inputs.
1868     case Intrinsic::x86_sse_sub_ss:
1869     case Intrinsic::x86_sse_mul_ss:
1870     case Intrinsic::x86_sse_min_ss:
1871     case Intrinsic::x86_sse_max_ss:
1872     case Intrinsic::x86_sse2_sub_sd:
1873     case Intrinsic::x86_sse2_mul_sd:
1874     case Intrinsic::x86_sse2_min_sd:
1875     case Intrinsic::x86_sse2_max_sd:
1876       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1877                                         UndefElts, Depth+1);
1878       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1879       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1880                                         UndefElts2, Depth+1);
1881       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1882
1883       // If only the low elt is demanded and this is a scalarizable intrinsic,
1884       // scalarize it now.
1885       if (DemandedElts == 1) {
1886         switch (II->getIntrinsicID()) {
1887         default: break;
1888         case Intrinsic::x86_sse_sub_ss:
1889         case Intrinsic::x86_sse_mul_ss:
1890         case Intrinsic::x86_sse2_sub_sd:
1891         case Intrinsic::x86_sse2_mul_sd:
1892           // TODO: Lower MIN/MAX/ABS/etc
1893           Value *LHS = II->getOperand(1);
1894           Value *RHS = II->getOperand(2);
1895           // Extract the element as scalars.
1896           LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS, 
1897             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1898           RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1899             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1900           
1901           switch (II->getIntrinsicID()) {
1902           default: llvm_unreachable("Case stmts out of sync!");
1903           case Intrinsic::x86_sse_sub_ss:
1904           case Intrinsic::x86_sse2_sub_sd:
1905             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1906                                                         II->getName()), *II);
1907             break;
1908           case Intrinsic::x86_sse_mul_ss:
1909           case Intrinsic::x86_sse2_mul_sd:
1910             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1911                                                          II->getName()), *II);
1912             break;
1913           }
1914           
1915           Instruction *New =
1916             InsertElementInst::Create(
1917               UndefValue::get(II->getType()), TmpV,
1918               ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
1919           InsertNewInstBefore(New, *II);
1920           return New;
1921         }            
1922       }
1923         
1924       // Output elements are undefined if both are undefined.  Consider things
1925       // like undef&0.  The result is known zero, not undef.
1926       UndefElts &= UndefElts2;
1927       break;
1928     }
1929     break;
1930   }
1931   }
1932   return MadeChange ? I : 0;
1933 }
1934
1935
1936 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1937 /// function is designed to check a chain of associative operators for a
1938 /// potential to apply a certain optimization.  Since the optimization may be
1939 /// applicable if the expression was reassociated, this checks the chain, then
1940 /// reassociates the expression as necessary to expose the optimization
1941 /// opportunity.  This makes use of a special Functor, which must define
1942 /// 'shouldApply' and 'apply' methods.
1943 ///
1944 template<typename Functor>
1945 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1946   unsigned Opcode = Root.getOpcode();
1947   Value *LHS = Root.getOperand(0);
1948
1949   // Quick check, see if the immediate LHS matches...
1950   if (F.shouldApply(LHS))
1951     return F.apply(Root);
1952
1953   // Otherwise, if the LHS is not of the same opcode as the root, return.
1954   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1955   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1956     // Should we apply this transform to the RHS?
1957     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1958
1959     // If not to the RHS, check to see if we should apply to the LHS...
1960     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1961       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1962       ShouldApply = true;
1963     }
1964
1965     // If the functor wants to apply the optimization to the RHS of LHSI,
1966     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1967     if (ShouldApply) {
1968       // Now all of the instructions are in the current basic block, go ahead
1969       // and perform the reassociation.
1970       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1971
1972       // First move the selected RHS to the LHS of the root...
1973       Root.setOperand(0, LHSI->getOperand(1));
1974
1975       // Make what used to be the LHS of the root be the user of the root...
1976       Value *ExtraOperand = TmpLHSI->getOperand(1);
1977       if (&Root == TmpLHSI) {
1978         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1979         return 0;
1980       }
1981       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1982       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1983       BasicBlock::iterator ARI = &Root; ++ARI;
1984       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1985       ARI = Root;
1986
1987       // Now propagate the ExtraOperand down the chain of instructions until we
1988       // get to LHSI.
1989       while (TmpLHSI != LHSI) {
1990         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1991         // Move the instruction to immediately before the chain we are
1992         // constructing to avoid breaking dominance properties.
1993         NextLHSI->moveBefore(ARI);
1994         ARI = NextLHSI;
1995
1996         Value *NextOp = NextLHSI->getOperand(1);
1997         NextLHSI->setOperand(1, ExtraOperand);
1998         TmpLHSI = NextLHSI;
1999         ExtraOperand = NextOp;
2000       }
2001
2002       // Now that the instructions are reassociated, have the functor perform
2003       // the transformation...
2004       return F.apply(Root);
2005     }
2006
2007     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2008   }
2009   return 0;
2010 }
2011
2012 namespace {
2013
2014 // AddRHS - Implements: X + X --> X << 1
2015 struct AddRHS {
2016   Value *RHS;
2017   explicit AddRHS(Value *rhs) : RHS(rhs) {}
2018   bool shouldApply(Value *LHS) const { return LHS == RHS; }
2019   Instruction *apply(BinaryOperator &Add) const {
2020     return BinaryOperator::CreateShl(Add.getOperand(0),
2021                                      ConstantInt::get(Add.getType(), 1));
2022   }
2023 };
2024
2025 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2026 //                 iff C1&C2 == 0
2027 struct AddMaskingAnd {
2028   Constant *C2;
2029   explicit AddMaskingAnd(Constant *c) : C2(c) {}
2030   bool shouldApply(Value *LHS) const {
2031     ConstantInt *C1;
2032     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
2033            ConstantExpr::getAnd(C1, C2)->isNullValue();
2034   }
2035   Instruction *apply(BinaryOperator &Add) const {
2036     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
2037   }
2038 };
2039
2040 }
2041
2042 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
2043                                              InstCombiner *IC) {
2044   if (CastInst *CI = dyn_cast<CastInst>(&I))
2045     return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
2046
2047   // Figure out if the constant is the left or the right argument.
2048   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2049   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
2050
2051   if (Constant *SOC = dyn_cast<Constant>(SO)) {
2052     if (ConstIsRHS)
2053       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2054     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
2055   }
2056
2057   Value *Op0 = SO, *Op1 = ConstOperand;
2058   if (!ConstIsRHS)
2059     std::swap(Op0, Op1);
2060   
2061   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2062     return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
2063                                     SO->getName()+".op");
2064   if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
2065     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2066                                    SO->getName()+".cmp");
2067   if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
2068     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2069                                    SO->getName()+".cmp");
2070   llvm_unreachable("Unknown binary instruction type!");
2071 }
2072
2073 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
2074 // constant as the other operand, try to fold the binary operator into the
2075 // select arguments.  This also works for Cast instructions, which obviously do
2076 // not have a second operand.
2077 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2078                                      InstCombiner *IC) {
2079   // Don't modify shared select instructions
2080   if (!SI->hasOneUse()) return 0;
2081   Value *TV = SI->getOperand(1);
2082   Value *FV = SI->getOperand(2);
2083
2084   if (isa<Constant>(TV) || isa<Constant>(FV)) {
2085     // Bool selects with constant operands can be folded to logical ops.
2086     if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
2087
2088     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2089     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2090
2091     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2092                               SelectFalseVal);
2093   }
2094   return 0;
2095 }
2096
2097
2098 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2099 /// has a PHI node as operand #0, see if we can fold the instruction into the
2100 /// PHI (which is only possible if all operands to the PHI are constants).
2101 ///
2102 /// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2103 /// that would normally be unprofitable because they strongly encourage jump
2104 /// threading.
2105 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2106                                          bool AllowAggressive) {
2107   AllowAggressive = false;
2108   PHINode *PN = cast<PHINode>(I.getOperand(0));
2109   unsigned NumPHIValues = PN->getNumIncomingValues();
2110   if (NumPHIValues == 0 ||
2111       // We normally only transform phis with a single use, unless we're trying
2112       // hard to make jump threading happen.
2113       (!PN->hasOneUse() && !AllowAggressive))
2114     return 0;
2115   
2116   
2117   // Check to see if all of the operands of the PHI are simple constants
2118   // (constantint/constantfp/undef).  If there is one non-constant value,
2119   // remember the BB it is in.  If there is more than one or if *it* is a PHI,
2120   // bail out.  We don't do arbitrary constant expressions here because moving
2121   // their computation can be expensive without a cost model.
2122   BasicBlock *NonConstBB = 0;
2123   for (unsigned i = 0; i != NumPHIValues; ++i)
2124     if (!isa<Constant>(PN->getIncomingValue(i)) ||
2125         isa<ConstantExpr>(PN->getIncomingValue(i))) {
2126       if (NonConstBB) return 0;  // More than one non-const value.
2127       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
2128       NonConstBB = PN->getIncomingBlock(i);
2129       
2130       // If the incoming non-constant value is in I's block, we have an infinite
2131       // loop.
2132       if (NonConstBB == I.getParent())
2133         return 0;
2134     }
2135   
2136   // If there is exactly one non-constant value, we can insert a copy of the
2137   // operation in that block.  However, if this is a critical edge, we would be
2138   // inserting the computation one some other paths (e.g. inside a loop).  Only
2139   // do this if the pred block is unconditionally branching into the phi block.
2140   if (NonConstBB != 0 && !AllowAggressive) {
2141     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2142     if (!BI || !BI->isUnconditional()) return 0;
2143   }
2144
2145   // Okay, we can do the transformation: create the new PHI node.
2146   PHINode *NewPN = PHINode::Create(I.getType(), "");
2147   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2148   InsertNewInstBefore(NewPN, *PN);
2149   NewPN->takeName(PN);
2150
2151   // Next, add all of the operands to the PHI.
2152   if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2153     // We only currently try to fold the condition of a select when it is a phi,
2154     // not the true/false values.
2155     Value *TrueV = SI->getTrueValue();
2156     Value *FalseV = SI->getFalseValue();
2157     BasicBlock *PhiTransBB = PN->getParent();
2158     for (unsigned i = 0; i != NumPHIValues; ++i) {
2159       BasicBlock *ThisBB = PN->getIncomingBlock(i);
2160       Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2161       Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
2162       Value *InV = 0;
2163       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2164         InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
2165       } else {
2166         assert(PN->getIncomingBlock(i) == NonConstBB);
2167         InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2168                                  FalseVInPred,
2169                                  "phitmp", NonConstBB->getTerminator());
2170         Worklist.Add(cast<Instruction>(InV));
2171       }
2172       NewPN->addIncoming(InV, ThisBB);
2173     }
2174   } else if (I.getNumOperands() == 2) {
2175     Constant *C = cast<Constant>(I.getOperand(1));
2176     for (unsigned i = 0; i != NumPHIValues; ++i) {
2177       Value *InV = 0;
2178       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2179         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2180           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2181         else
2182           InV = ConstantExpr::get(I.getOpcode(), InC, C);
2183       } else {
2184         assert(PN->getIncomingBlock(i) == NonConstBB);
2185         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2186           InV = BinaryOperator::Create(BO->getOpcode(),
2187                                        PN->getIncomingValue(i), C, "phitmp",
2188                                        NonConstBB->getTerminator());
2189         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2190           InV = CmpInst::Create(CI->getOpcode(),
2191                                 CI->getPredicate(),
2192                                 PN->getIncomingValue(i), C, "phitmp",
2193                                 NonConstBB->getTerminator());
2194         else
2195           llvm_unreachable("Unknown binop!");
2196         
2197         Worklist.Add(cast<Instruction>(InV));
2198       }
2199       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2200     }
2201   } else { 
2202     CastInst *CI = cast<CastInst>(&I);
2203     const Type *RetTy = CI->getType();
2204     for (unsigned i = 0; i != NumPHIValues; ++i) {
2205       Value *InV;
2206       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2207         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2208       } else {
2209         assert(PN->getIncomingBlock(i) == NonConstBB);
2210         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2211                                I.getType(), "phitmp", 
2212                                NonConstBB->getTerminator());
2213         Worklist.Add(cast<Instruction>(InV));
2214       }
2215       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2216     }
2217   }
2218   return ReplaceInstUsesWith(I, NewPN);
2219 }
2220
2221
2222 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2223 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2224 /// This basically requires proving that the add in the original type would not
2225 /// overflow to change the sign bit or have a carry out.
2226 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2227   // There are different heuristics we can use for this.  Here are some simple
2228   // ones.
2229   
2230   // Add has the property that adding any two 2's complement numbers can only 
2231   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2232   // have at least two sign bits, we know that the addition of the two values
2233   // will sign extend fine.
2234   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2235     return true;
2236   
2237   
2238   // If one of the operands only has one non-zero bit, and if the other operand
2239   // has a known-zero bit in a more significant place than it (not including the
2240   // sign bit) the ripple may go up to and fill the zero, but won't change the
2241   // sign.  For example, (X & ~4) + 1.
2242   
2243   // TODO: Implement.
2244   
2245   return false;
2246 }
2247
2248
2249 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2250   bool Changed = SimplifyCommutative(I);
2251   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2252
2253   if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
2254                                  I.hasNoUnsignedWrap(), TD))
2255     return ReplaceInstUsesWith(I, V);
2256
2257   
2258   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2259     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2260       // X + (signbit) --> X ^ signbit
2261       const APInt& Val = CI->getValue();
2262       uint32_t BitWidth = Val.getBitWidth();
2263       if (Val == APInt::getSignBit(BitWidth))
2264         return BinaryOperator::CreateXor(LHS, RHS);
2265       
2266       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2267       // (X & 254)+1 -> (X&254)|1
2268       if (SimplifyDemandedInstructionBits(I))
2269         return &I;
2270
2271       // zext(bool) + C -> bool ? C + 1 : C
2272       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2273         if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2274           return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2275     }
2276
2277     if (isa<PHINode>(LHS))
2278       if (Instruction *NV = FoldOpIntoPhi(I))
2279         return NV;
2280     
2281     ConstantInt *XorRHS = 0;
2282     Value *XorLHS = 0;
2283     if (isa<ConstantInt>(RHSC) &&
2284         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2285       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2286       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2287       
2288       uint32_t Size = TySizeBits / 2;
2289       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2290       APInt CFF80Val(-C0080Val);
2291       do {
2292         if (TySizeBits > Size) {
2293           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2294           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2295           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2296               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2297             // This is a sign extend if the top bits are known zero.
2298             if (!MaskedValueIsZero(XorLHS, 
2299                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2300               Size = 0;  // Not a sign ext, but can't be any others either.
2301             break;
2302           }
2303         }
2304         Size >>= 1;
2305         C0080Val = APIntOps::lshr(C0080Val, Size);
2306         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2307       } while (Size >= 1);
2308       
2309       // FIXME: This shouldn't be necessary. When the backends can handle types
2310       // with funny bit widths then this switch statement should be removed. It
2311       // is just here to get the size of the "middle" type back up to something
2312       // that the back ends can handle.
2313       const Type *MiddleType = 0;
2314       switch (Size) {
2315         default: break;
2316         case 32: MiddleType = Type::getInt32Ty(*Context); break;
2317         case 16: MiddleType = Type::getInt16Ty(*Context); break;
2318         case  8: MiddleType = Type::getInt8Ty(*Context); break;
2319       }
2320       if (MiddleType) {
2321         Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
2322         return new SExtInst(NewTrunc, I.getType(), I.getName());
2323       }
2324     }
2325   }
2326
2327   if (I.getType() == Type::getInt1Ty(*Context))
2328     return BinaryOperator::CreateXor(LHS, RHS);
2329
2330   // X + X --> X << 1
2331   if (I.getType()->isInteger()) {
2332     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2333       return Result;
2334
2335     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2336       if (RHSI->getOpcode() == Instruction::Sub)
2337         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2338           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2339     }
2340     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2341       if (LHSI->getOpcode() == Instruction::Sub)
2342         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2343           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2344     }
2345   }
2346
2347   // -A + B  -->  B - A
2348   // -A + -B  -->  -(A + B)
2349   if (Value *LHSV = dyn_castNegVal(LHS)) {
2350     if (LHS->getType()->isIntOrIntVector()) {
2351       if (Value *RHSV = dyn_castNegVal(RHS)) {
2352         Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
2353         return BinaryOperator::CreateNeg(NewAdd);
2354       }
2355     }
2356     
2357     return BinaryOperator::CreateSub(RHS, LHSV);
2358   }
2359
2360   // A + -B  -->  A - B
2361   if (!isa<Constant>(RHS))
2362     if (Value *V = dyn_castNegVal(RHS))
2363       return BinaryOperator::CreateSub(LHS, V);
2364
2365
2366   ConstantInt *C2;
2367   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2368     if (X == RHS)   // X*C + X --> X * (C+1)
2369       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2370
2371     // X*C1 + X*C2 --> X * (C1+C2)
2372     ConstantInt *C1;
2373     if (X == dyn_castFoldableMul(RHS, C1))
2374       return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2375   }
2376
2377   // X + X*C --> X * (C+1)
2378   if (dyn_castFoldableMul(RHS, C2) == LHS)
2379     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2380
2381   // X + ~X --> -1   since   ~X = -X-1
2382   if (dyn_castNotVal(LHS) == RHS ||
2383       dyn_castNotVal(RHS) == LHS)
2384     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2385   
2386
2387   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2388   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2389     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2390       return R;
2391   
2392   // A+B --> A|B iff A and B have no bits set in common.
2393   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2394     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2395     APInt LHSKnownOne(IT->getBitWidth(), 0);
2396     APInt LHSKnownZero(IT->getBitWidth(), 0);
2397     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2398     if (LHSKnownZero != 0) {
2399       APInt RHSKnownOne(IT->getBitWidth(), 0);
2400       APInt RHSKnownZero(IT->getBitWidth(), 0);
2401       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2402       
2403       // No bits in common -> bitwise or.
2404       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2405         return BinaryOperator::CreateOr(LHS, RHS);
2406     }
2407   }
2408
2409   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2410   if (I.getType()->isIntOrIntVector()) {
2411     Value *W, *X, *Y, *Z;
2412     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2413         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2414       if (W != Y) {
2415         if (W == Z) {
2416           std::swap(Y, Z);
2417         } else if (Y == X) {
2418           std::swap(W, X);
2419         } else if (X == Z) {
2420           std::swap(Y, Z);
2421           std::swap(W, X);
2422         }
2423       }
2424
2425       if (W == Y) {
2426         Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
2427         return BinaryOperator::CreateMul(W, NewAdd);
2428       }
2429     }
2430   }
2431
2432   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2433     Value *X = 0;
2434     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2435       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2436
2437     // (X & FF00) + xx00  -> (X+xx00) & FF00
2438     if (LHS->hasOneUse() &&
2439         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2440       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2441       if (Anded == CRHS) {
2442         // See if all bits from the first bit set in the Add RHS up are included
2443         // in the mask.  First, get the rightmost bit.
2444         const APInt& AddRHSV = CRHS->getValue();
2445
2446         // Form a mask of all bits from the lowest bit added through the top.
2447         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2448
2449         // See if the and mask includes all of these bits.
2450         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2451
2452         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2453           // Okay, the xform is safe.  Insert the new add pronto.
2454           Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
2455           return BinaryOperator::CreateAnd(NewAdd, C2);
2456         }
2457       }
2458     }
2459
2460     // Try to fold constant add into select arguments.
2461     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2462       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2463         return R;
2464   }
2465
2466   // add (select X 0 (sub n A)) A  -->  select X A n
2467   {
2468     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2469     Value *A = RHS;
2470     if (!SI) {
2471       SI = dyn_cast<SelectInst>(RHS);
2472       A = LHS;
2473     }
2474     if (SI && SI->hasOneUse()) {
2475       Value *TV = SI->getTrueValue();
2476       Value *FV = SI->getFalseValue();
2477       Value *N;
2478
2479       // Can we fold the add into the argument of the select?
2480       // We check both true and false select arguments for a matching subtract.
2481       if (match(FV, m_Zero()) &&
2482           match(TV, m_Sub(m_Value(N), m_Specific(A))))
2483         // Fold the add into the true select value.
2484         return SelectInst::Create(SI->getCondition(), N, A);
2485       if (match(TV, m_Zero()) &&
2486           match(FV, m_Sub(m_Value(N), m_Specific(A))))
2487         // Fold the add into the false select value.
2488         return SelectInst::Create(SI->getCondition(), A, N);
2489     }
2490   }
2491
2492   // Check for (add (sext x), y), see if we can merge this into an
2493   // integer add followed by a sext.
2494   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2495     // (add (sext x), cst) --> (sext (add x, cst'))
2496     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2497       Constant *CI = 
2498         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2499       if (LHSConv->hasOneUse() &&
2500           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2501           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2502         // Insert the new, smaller add.
2503         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0), 
2504                                               CI, "addconv");
2505         return new SExtInst(NewAdd, I.getType());
2506       }
2507     }
2508     
2509     // (add (sext x), (sext y)) --> (sext (add int x, y))
2510     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2511       // Only do this if x/y have the same type, if at last one of them has a
2512       // single use (so we don't increase the number of sexts), and if the
2513       // integer add will not overflow.
2514       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2515           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2516           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2517                                    RHSConv->getOperand(0))) {
2518         // Insert the new integer add.
2519         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0), 
2520                                               RHSConv->getOperand(0), "addconv");
2521         return new SExtInst(NewAdd, I.getType());
2522       }
2523     }
2524   }
2525
2526   return Changed ? &I : 0;
2527 }
2528
2529 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2530   bool Changed = SimplifyCommutative(I);
2531   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2532
2533   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2534     // X + 0 --> X
2535     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2536       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2537                               (I.getType())->getValueAPF()))
2538         return ReplaceInstUsesWith(I, LHS);
2539     }
2540
2541     if (isa<PHINode>(LHS))
2542       if (Instruction *NV = FoldOpIntoPhi(I))
2543         return NV;
2544   }
2545
2546   // -A + B  -->  B - A
2547   // -A + -B  -->  -(A + B)
2548   if (Value *LHSV = dyn_castFNegVal(LHS))
2549     return BinaryOperator::CreateFSub(RHS, LHSV);
2550
2551   // A + -B  -->  A - B
2552   if (!isa<Constant>(RHS))
2553     if (Value *V = dyn_castFNegVal(RHS))
2554       return BinaryOperator::CreateFSub(LHS, V);
2555
2556   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2557   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2558     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2559       return ReplaceInstUsesWith(I, LHS);
2560
2561   // Check for (add double (sitofp x), y), see if we can merge this into an
2562   // integer add followed by a promotion.
2563   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2564     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2565     // ... if the constant fits in the integer value.  This is useful for things
2566     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2567     // requires a constant pool load, and generally allows the add to be better
2568     // instcombined.
2569     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2570       Constant *CI = 
2571       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2572       if (LHSConv->hasOneUse() &&
2573           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2574           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2575         // Insert the new integer add.
2576         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2577                                               CI, "addconv");
2578         return new SIToFPInst(NewAdd, I.getType());
2579       }
2580     }
2581     
2582     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2583     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2584       // Only do this if x/y have the same type, if at last one of them has a
2585       // single use (so we don't increase the number of int->fp conversions),
2586       // and if the integer add will not overflow.
2587       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2588           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2589           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2590                                    RHSConv->getOperand(0))) {
2591         // Insert the new integer add.
2592         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0), 
2593                                               RHSConv->getOperand(0),"addconv");
2594         return new SIToFPInst(NewAdd, I.getType());
2595       }
2596     }
2597   }
2598   
2599   return Changed ? &I : 0;
2600 }
2601
2602
2603 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2604 /// code necessary to compute the offset from the base pointer (without adding
2605 /// in the base pointer).  Return the result as a signed integer of intptr size.
2606 static Value *EmitGEPOffset(User *GEP, InstCombiner &IC) {
2607   TargetData &TD = *IC.getTargetData();
2608   gep_type_iterator GTI = gep_type_begin(GEP);
2609   const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
2610   Value *Result = Constant::getNullValue(IntPtrTy);
2611
2612   // Build a mask for high order bits.
2613   unsigned IntPtrWidth = TD.getPointerSizeInBits();
2614   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2615
2616   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
2617        ++i, ++GTI) {
2618     Value *Op = *i;
2619     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
2620     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
2621       if (OpC->isZero()) continue;
2622       
2623       // Handle a struct index, which adds its field offset to the pointer.
2624       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2625         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
2626         
2627         Result = IC.Builder->CreateAdd(Result,
2628                                        ConstantInt::get(IntPtrTy, Size),
2629                                        GEP->getName()+".offs");
2630         continue;
2631       }
2632       
2633       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2634       Constant *OC =
2635               ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
2636       Scale = ConstantExpr::getMul(OC, Scale);
2637       // Emit an add instruction.
2638       Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
2639       continue;
2640     }
2641     // Convert to correct type.
2642     if (Op->getType() != IntPtrTy)
2643       Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
2644     if (Size != 1) {
2645       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2646       // We'll let instcombine(mul) convert this to a shl if possible.
2647       Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
2648     }
2649
2650     // Emit an add instruction.
2651     Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
2652   }
2653   return Result;
2654 }
2655
2656
2657 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
2658 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
2659 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
2660 /// be complex, and scales are involved.  The above expression would also be
2661 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
2662 /// This later form is less amenable to optimization though, and we are allowed
2663 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
2664 ///
2665 /// If we can't emit an optimized form for this expression, this returns null.
2666 /// 
2667 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
2668                                           InstCombiner &IC) {
2669   TargetData &TD = *IC.getTargetData();
2670   gep_type_iterator GTI = gep_type_begin(GEP);
2671
2672   // Check to see if this gep only has a single variable index.  If so, and if
2673   // any constant indices are a multiple of its scale, then we can compute this
2674   // in terms of the scale of the variable index.  For example, if the GEP
2675   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
2676   // because the expression will cross zero at the same point.
2677   unsigned i, e = GEP->getNumOperands();
2678   int64_t Offset = 0;
2679   for (i = 1; i != e; ++i, ++GTI) {
2680     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2681       // Compute the aggregate offset of constant indices.
2682       if (CI->isZero()) continue;
2683
2684       // Handle a struct index, which adds its field offset to the pointer.
2685       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2686         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2687       } else {
2688         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2689         Offset += Size*CI->getSExtValue();
2690       }
2691     } else {
2692       // Found our variable index.
2693       break;
2694     }
2695   }
2696   
2697   // If there are no variable indices, we must have a constant offset, just
2698   // evaluate it the general way.
2699   if (i == e) return 0;
2700   
2701   Value *VariableIdx = GEP->getOperand(i);
2702   // Determine the scale factor of the variable element.  For example, this is
2703   // 4 if the variable index is into an array of i32.
2704   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
2705   
2706   // Verify that there are no other variable indices.  If so, emit the hard way.
2707   for (++i, ++GTI; i != e; ++i, ++GTI) {
2708     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
2709     if (!CI) return 0;
2710    
2711     // Compute the aggregate offset of constant indices.
2712     if (CI->isZero()) continue;
2713     
2714     // Handle a struct index, which adds its field offset to the pointer.
2715     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2716       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2717     } else {
2718       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2719       Offset += Size*CI->getSExtValue();
2720     }
2721   }
2722   
2723   // Okay, we know we have a single variable index, which must be a
2724   // pointer/array/vector index.  If there is no offset, life is simple, return
2725   // the index.
2726   unsigned IntPtrWidth = TD.getPointerSizeInBits();
2727   if (Offset == 0) {
2728     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
2729     // we don't need to bother extending: the extension won't affect where the
2730     // computation crosses zero.
2731     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
2732       VariableIdx = new TruncInst(VariableIdx, 
2733                                   TD.getIntPtrType(VariableIdx->getContext()),
2734                                   VariableIdx->getName(), &I);
2735     return VariableIdx;
2736   }
2737   
2738   // Otherwise, there is an index.  The computation we will do will be modulo
2739   // the pointer size, so get it.
2740   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2741   
2742   Offset &= PtrSizeMask;
2743   VariableScale &= PtrSizeMask;
2744
2745   // To do this transformation, any constant index must be a multiple of the
2746   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
2747   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
2748   // multiple of the variable scale.
2749   int64_t NewOffs = Offset / (int64_t)VariableScale;
2750   if (Offset != NewOffs*(int64_t)VariableScale)
2751     return 0;
2752
2753   // Okay, we can do this evaluation.  Start by converting the index to intptr.
2754   const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
2755   if (VariableIdx->getType() != IntPtrTy)
2756     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
2757                                               true /*SExt*/, 
2758                                               VariableIdx->getName(), &I);
2759   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
2760   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
2761 }
2762
2763
2764 /// Optimize pointer differences into the same array into a size.  Consider:
2765 ///  &A[10] - &A[0]: we should compile this to "10".  LHS/RHS are the pointer
2766 /// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2767 ///
2768 Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
2769                                                const Type *Ty) {
2770   assert(TD && "Must have target data info for this");
2771   
2772   // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
2773   // this.
2774   bool Swapped;
2775   GetElementPtrInst *GEP = 0;
2776   ConstantExpr *CstGEP = 0;
2777   
2778   // TODO: Could also optimize &A[i] - &A[j] -> "i-j", and "&A.foo[i] - &A.foo".
2779   // For now we require one side to be the base pointer "A" or a constant
2780   // expression derived from it.
2781   if (GetElementPtrInst *LHSGEP = dyn_cast<GetElementPtrInst>(LHS)) {
2782     // (gep X, ...) - X
2783     if (LHSGEP->getOperand(0) == RHS) {
2784       GEP = LHSGEP;
2785       Swapped = false;
2786     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(RHS)) {
2787       // (gep X, ...) - (ce_gep X, ...)
2788       if (CE->getOpcode() == Instruction::GetElementPtr &&
2789           LHSGEP->getOperand(0) == CE->getOperand(0)) {
2790         CstGEP = CE;
2791         GEP = LHSGEP;
2792         Swapped = false;
2793       }
2794     }
2795   }
2796   
2797   if (GetElementPtrInst *RHSGEP = dyn_cast<GetElementPtrInst>(RHS)) {
2798     // X - (gep X, ...)
2799     if (RHSGEP->getOperand(0) == LHS) {
2800       GEP = RHSGEP;
2801       Swapped = true;
2802     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(LHS)) {
2803       // (ce_gep X, ...) - (gep X, ...)
2804       if (CE->getOpcode() == Instruction::GetElementPtr &&
2805           RHSGEP->getOperand(0) == CE->getOperand(0)) {
2806         CstGEP = CE;
2807         GEP = RHSGEP;
2808         Swapped = true;
2809       }
2810     }
2811   }
2812   
2813   if (GEP == 0)
2814     return 0;
2815   
2816   // Emit the offset of the GEP and an intptr_t.
2817   Value *Result = EmitGEPOffset(GEP, *this);
2818   
2819   // If we had a constant expression GEP on the other side offsetting the
2820   // pointer, subtract it from the offset we have.
2821   if (CstGEP) {
2822     Value *CstOffset = EmitGEPOffset(CstGEP, *this);
2823     Result = Builder->CreateSub(Result, CstOffset);
2824   }
2825   
2826
2827   // If we have p - gep(p, ...)  then we have to negate the result.
2828   if (Swapped)
2829     Result = Builder->CreateNeg(Result, "diff.neg");
2830
2831   return Builder->CreateIntCast(Result, Ty, true);
2832 }
2833
2834
2835 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2836   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2837
2838   if (Op0 == Op1)                        // sub X, X  -> 0
2839     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2840
2841   // If this is a 'B = x-(-A)', change to B = x+A.  This preserves NSW/NUW.
2842   if (Value *V = dyn_castNegVal(Op1)) {
2843     BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
2844     Res->setHasNoSignedWrap(I.hasNoSignedWrap());
2845     Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
2846     return Res;
2847   }
2848
2849   if (isa<UndefValue>(Op0))
2850     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2851   if (isa<UndefValue>(Op1))
2852     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2853   if (I.getType() == Type::getInt1Ty(*Context))
2854     return BinaryOperator::CreateXor(Op0, Op1);
2855   
2856   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2857     // Replace (-1 - A) with (~A).
2858     if (C->isAllOnesValue())
2859       return BinaryOperator::CreateNot(Op1);
2860
2861     // C - ~X == X + (1+C)
2862     Value *X = 0;
2863     if (match(Op1, m_Not(m_Value(X))))
2864       return BinaryOperator::CreateAdd(X, AddOne(C));
2865
2866     // -(X >>u 31) -> (X >>s 31)
2867     // -(X >>s 31) -> (X >>u 31)
2868     if (C->isZero()) {
2869       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2870         if (SI->getOpcode() == Instruction::LShr) {
2871           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2872             // Check to see if we are shifting out everything but the sign bit.
2873             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2874                 SI->getType()->getPrimitiveSizeInBits()-1) {
2875               // Ok, the transformation is safe.  Insert AShr.
2876               return BinaryOperator::Create(Instruction::AShr, 
2877                                           SI->getOperand(0), CU, SI->getName());
2878             }
2879           }
2880         } else if (SI->getOpcode() == Instruction::AShr) {
2881           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2882             // Check to see if we are shifting out everything but the sign bit.
2883             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2884                 SI->getType()->getPrimitiveSizeInBits()-1) {
2885               // Ok, the transformation is safe.  Insert LShr. 
2886               return BinaryOperator::CreateLShr(
2887                                           SI->getOperand(0), CU, SI->getName());
2888             }
2889           }
2890         }
2891       }
2892     }
2893
2894     // Try to fold constant sub into select arguments.
2895     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2896       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2897         return R;
2898
2899     // C - zext(bool) -> bool ? C - 1 : C
2900     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2901       if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2902         return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2903   }
2904
2905   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2906     if (Op1I->getOpcode() == Instruction::Add) {
2907       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2908         return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2909                                          I.getName());
2910       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2911         return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2912                                          I.getName());
2913       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2914         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2915           // C1-(X+C2) --> (C1-C2)-X
2916           return BinaryOperator::CreateSub(
2917             ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2918       }
2919     }
2920
2921     if (Op1I->hasOneUse()) {
2922       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2923       // is not used by anyone else...
2924       //
2925       if (Op1I->getOpcode() == Instruction::Sub) {
2926         // Swap the two operands of the subexpr...
2927         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2928         Op1I->setOperand(0, IIOp1);
2929         Op1I->setOperand(1, IIOp0);
2930
2931         // Create the new top level add instruction...
2932         return BinaryOperator::CreateAdd(Op0, Op1);
2933       }
2934
2935       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2936       //
2937       if (Op1I->getOpcode() == Instruction::And &&
2938           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2939         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2940
2941         Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
2942         return BinaryOperator::CreateAnd(Op0, NewNot);
2943       }
2944
2945       // 0 - (X sdiv C)  -> (X sdiv -C)
2946       if (Op1I->getOpcode() == Instruction::SDiv)
2947         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2948           if (CSI->isZero())
2949             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2950               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2951                                           ConstantExpr::getNeg(DivRHS));
2952
2953       // X - X*C --> X * (1-C)
2954       ConstantInt *C2 = 0;
2955       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2956         Constant *CP1 = 
2957           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2958                                              C2);
2959         return BinaryOperator::CreateMul(Op0, CP1);
2960       }
2961     }
2962   }
2963
2964   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2965     if (Op0I->getOpcode() == Instruction::Add) {
2966       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2967         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2968       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2969         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2970     } else if (Op0I->getOpcode() == Instruction::Sub) {
2971       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2972         return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2973                                          I.getName());
2974     }
2975   }
2976
2977   ConstantInt *C1;
2978   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2979     if (X == Op1)  // X*C - X --> X * (C-1)
2980       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2981
2982     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2983     if (X == dyn_castFoldableMul(Op1, C2))
2984       return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2985   }
2986   
2987   // Optimize pointer differences into the same array into a size.  Consider:
2988   //  &A[10] - &A[0]: we should compile this to "10".
2989   if (TD) {
2990     Value *LHSOp, *RHSOp;
2991     if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
2992         match(Op1, m_PtrToInt(m_Value(RHSOp))))
2993       if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
2994         return ReplaceInstUsesWith(I, Res);
2995     
2996     // trunc(p)-trunc(q) -> trunc(p-q)
2997     if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
2998         match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
2999       if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
3000         return ReplaceInstUsesWith(I, Res);
3001   }
3002   
3003   return 0;
3004 }
3005
3006 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
3007   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3008
3009   // If this is a 'B = x-(-A)', change to B = x+A...
3010   if (Value *V = dyn_castFNegVal(Op1))
3011     return BinaryOperator::CreateFAdd(Op0, V);
3012
3013   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
3014     if (Op1I->getOpcode() == Instruction::FAdd) {
3015       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
3016         return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
3017                                           I.getName());
3018       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
3019         return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
3020                                           I.getName());
3021     }
3022   }
3023
3024   return 0;
3025 }
3026
3027 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
3028 /// comparison only checks the sign bit.  If it only checks the sign bit, set
3029 /// TrueIfSigned if the result of the comparison is true when the input value is
3030 /// signed.
3031 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
3032                            bool &TrueIfSigned) {
3033   switch (pred) {
3034   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
3035     TrueIfSigned = true;
3036     return RHS->isZero();
3037   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
3038     TrueIfSigned = true;
3039     return RHS->isAllOnesValue();
3040   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
3041     TrueIfSigned = false;
3042     return RHS->isAllOnesValue();
3043   case ICmpInst::ICMP_UGT:
3044     // True if LHS u> RHS and RHS == high-bit-mask - 1
3045     TrueIfSigned = true;
3046     return RHS->getValue() ==
3047       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
3048   case ICmpInst::ICMP_UGE: 
3049     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
3050     TrueIfSigned = true;
3051     return RHS->getValue().isSignBit();
3052   default:
3053     return false;
3054   }
3055 }
3056
3057 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
3058   bool Changed = SimplifyCommutative(I);
3059   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3060
3061   if (isa<UndefValue>(Op1))              // undef * X -> 0
3062     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3063
3064   // Simplify mul instructions with a constant RHS.
3065   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3066     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
3067
3068       // ((X << C1)*C2) == (X * (C2 << C1))
3069       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
3070         if (SI->getOpcode() == Instruction::Shl)
3071           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
3072             return BinaryOperator::CreateMul(SI->getOperand(0),
3073                                         ConstantExpr::getShl(CI, ShOp));
3074
3075       if (CI->isZero())
3076         return ReplaceInstUsesWith(I, Op1C);  // X * 0  == 0
3077       if (CI->equalsInt(1))                  // X * 1  == X
3078         return ReplaceInstUsesWith(I, Op0);
3079       if (CI->isAllOnesValue())              // X * -1 == 0 - X
3080         return BinaryOperator::CreateNeg(Op0, I.getName());
3081
3082       const APInt& Val = cast<ConstantInt>(CI)->getValue();
3083       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
3084         return BinaryOperator::CreateShl(Op0,
3085                  ConstantInt::get(Op0->getType(), Val.logBase2()));
3086       }
3087     } else if (isa<VectorType>(Op1C->getType())) {
3088       if (Op1C->isNullValue())
3089         return ReplaceInstUsesWith(I, Op1C);
3090
3091       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
3092         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
3093           return BinaryOperator::CreateNeg(Op0, I.getName());
3094
3095         // As above, vector X*splat(1.0) -> X in all defined cases.
3096         if (Constant *Splat = Op1V->getSplatValue()) {
3097           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
3098             if (CI->equalsInt(1))
3099               return ReplaceInstUsesWith(I, Op0);
3100         }
3101       }
3102     }
3103     
3104     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3105       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
3106           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
3107         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
3108         Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
3109         Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
3110         return BinaryOperator::CreateAdd(Add, C1C2);
3111         
3112       }
3113
3114     // Try to fold constant mul into select arguments.
3115     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3116       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3117         return R;
3118
3119     if (isa<PHINode>(Op0))
3120       if (Instruction *NV = FoldOpIntoPhi(I))
3121         return NV;
3122   }
3123
3124   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
3125     if (Value *Op1v = dyn_castNegVal(Op1))
3126       return BinaryOperator::CreateMul(Op0v, Op1v);
3127
3128   // (X / Y) *  Y = X - (X % Y)
3129   // (X / Y) * -Y = (X % Y) - X
3130   {
3131     Value *Op1C = Op1;
3132     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
3133     if (!BO ||
3134         (BO->getOpcode() != Instruction::UDiv && 
3135          BO->getOpcode() != Instruction::SDiv)) {
3136       Op1C = Op0;
3137       BO = dyn_cast<BinaryOperator>(Op1);
3138     }
3139     Value *Neg = dyn_castNegVal(Op1C);
3140     if (BO && BO->hasOneUse() &&
3141         (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
3142         (BO->getOpcode() == Instruction::UDiv ||
3143          BO->getOpcode() == Instruction::SDiv)) {
3144       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
3145
3146       // If the division is exact, X % Y is zero.
3147       if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
3148         if (SDiv->isExact()) {
3149           if (Op1BO == Op1C)
3150             return ReplaceInstUsesWith(I, Op0BO);
3151           return BinaryOperator::CreateNeg(Op0BO);
3152         }
3153
3154       Value *Rem;
3155       if (BO->getOpcode() == Instruction::UDiv)
3156         Rem = Builder->CreateURem(Op0BO, Op1BO);
3157       else
3158         Rem = Builder->CreateSRem(Op0BO, Op1BO);
3159       Rem->takeName(BO);
3160
3161       if (Op1BO == Op1C)
3162         return BinaryOperator::CreateSub(Op0BO, Rem);
3163       return BinaryOperator::CreateSub(Rem, Op0BO);
3164     }
3165   }
3166
3167   /// i1 mul -> i1 and.
3168   if (I.getType() == Type::getInt1Ty(*Context))
3169     return BinaryOperator::CreateAnd(Op0, Op1);
3170
3171   // X*(1 << Y) --> X << Y
3172   // (1 << Y)*X --> X << Y
3173   {
3174     Value *Y;
3175     if (match(Op0, m_Shl(m_One(), m_Value(Y))))
3176       return BinaryOperator::CreateShl(Op1, Y);
3177     if (match(Op1, m_Shl(m_One(), m_Value(Y))))
3178       return BinaryOperator::CreateShl(Op0, Y);
3179   }
3180   
3181   // If one of the operands of the multiply is a cast from a boolean value, then
3182   // we know the bool is either zero or one, so this is a 'masking' multiply.
3183   //   X * Y (where Y is 0 or 1) -> X & (0-Y)
3184   if (!isa<VectorType>(I.getType())) {
3185     // -2 is "-1 << 1" so it is all bits set except the low one.
3186     APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
3187     
3188     Value *BoolCast = 0, *OtherOp = 0;
3189     if (MaskedValueIsZero(Op0, Negative2))
3190       BoolCast = Op0, OtherOp = Op1;
3191     else if (MaskedValueIsZero(Op1, Negative2))
3192       BoolCast = Op1, OtherOp = Op0;
3193
3194     if (BoolCast) {
3195       Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
3196                                     BoolCast, "tmp");
3197       return BinaryOperator::CreateAnd(V, OtherOp);
3198     }
3199   }
3200
3201   return Changed ? &I : 0;
3202 }
3203
3204 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
3205   bool Changed = SimplifyCommutative(I);
3206   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3207
3208   // Simplify mul instructions with a constant RHS...
3209   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3210     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
3211       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
3212       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3213       if (Op1F->isExactlyValue(1.0))
3214         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
3215     } else if (isa<VectorType>(Op1C->getType())) {
3216       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
3217         // As above, vector X*splat(1.0) -> X in all defined cases.
3218         if (Constant *Splat = Op1V->getSplatValue()) {
3219           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
3220             if (F->isExactlyValue(1.0))
3221               return ReplaceInstUsesWith(I, Op0);
3222         }
3223       }
3224     }
3225
3226     // Try to fold constant mul into select arguments.
3227     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3228       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3229         return R;
3230
3231     if (isa<PHINode>(Op0))
3232       if (Instruction *NV = FoldOpIntoPhi(I))
3233         return NV;
3234   }
3235
3236   if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
3237     if (Value *Op1v = dyn_castFNegVal(Op1))
3238       return BinaryOperator::CreateFMul(Op0v, Op1v);
3239
3240   return Changed ? &I : 0;
3241 }
3242
3243 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
3244 /// instruction.
3245 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
3246   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
3247   
3248   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
3249   int NonNullOperand = -1;
3250   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3251     if (ST->isNullValue())
3252       NonNullOperand = 2;
3253   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
3254   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3255     if (ST->isNullValue())
3256       NonNullOperand = 1;
3257   
3258   if (NonNullOperand == -1)
3259     return false;
3260   
3261   Value *SelectCond = SI->getOperand(0);
3262   
3263   // Change the div/rem to use 'Y' instead of the select.
3264   I.setOperand(1, SI->getOperand(NonNullOperand));
3265   
3266   // Okay, we know we replace the operand of the div/rem with 'Y' with no
3267   // problem.  However, the select, or the condition of the select may have
3268   // multiple uses.  Based on our knowledge that the operand must be non-zero,
3269   // propagate the known value for the select into other uses of it, and
3270   // propagate a known value of the condition into its other users.
3271   
3272   // If the select and condition only have a single use, don't bother with this,
3273   // early exit.
3274   if (SI->use_empty() && SelectCond->hasOneUse())
3275     return true;
3276   
3277   // Scan the current block backward, looking for other uses of SI.
3278   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
3279   
3280   while (BBI != BBFront) {
3281     --BBI;
3282     // If we found a call to a function, we can't assume it will return, so
3283     // information from below it cannot be propagated above it.
3284     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
3285       break;
3286     
3287     // Replace uses of the select or its condition with the known values.
3288     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
3289          I != E; ++I) {
3290       if (*I == SI) {
3291         *I = SI->getOperand(NonNullOperand);
3292         Worklist.Add(BBI);
3293       } else if (*I == SelectCond) {
3294         *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
3295                                    ConstantInt::getFalse(*Context);
3296         Worklist.Add(BBI);
3297       }
3298     }
3299     
3300     // If we past the instruction, quit looking for it.
3301     if (&*BBI == SI)
3302       SI = 0;
3303     if (&*BBI == SelectCond)
3304       SelectCond = 0;
3305     
3306     // If we ran out of things to eliminate, break out of the loop.
3307     if (SelectCond == 0 && SI == 0)
3308       break;
3309     
3310   }
3311   return true;
3312 }
3313
3314
3315 /// This function implements the transforms on div instructions that work
3316 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3317 /// used by the visitors to those instructions.
3318 /// @brief Transforms common to all three div instructions
3319 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
3320   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3321
3322   // undef / X -> 0        for integer.
3323   // undef / X -> undef    for FP (the undef could be a snan).
3324   if (isa<UndefValue>(Op0)) {
3325     if (Op0->getType()->isFPOrFPVector())
3326       return ReplaceInstUsesWith(I, Op0);
3327     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3328   }
3329
3330   // X / undef -> undef
3331   if (isa<UndefValue>(Op1))
3332     return ReplaceInstUsesWith(I, Op1);
3333
3334   return 0;
3335 }
3336
3337 /// This function implements the transforms common to both integer division
3338 /// instructions (udiv and sdiv). It is called by the visitors to those integer
3339 /// division instructions.
3340 /// @brief Common integer divide transforms
3341 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3342   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3343
3344   // (sdiv X, X) --> 1     (udiv X, X) --> 1
3345   if (Op0 == Op1) {
3346     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
3347       Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
3348       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
3349       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
3350     }
3351
3352     Constant *CI = ConstantInt::get(I.getType(), 1);
3353     return ReplaceInstUsesWith(I, CI);
3354   }
3355   
3356   if (Instruction *Common = commonDivTransforms(I))
3357     return Common;
3358   
3359   // Handle cases involving: [su]div X, (select Cond, Y, Z)
3360   // This does not apply for fdiv.
3361   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3362     return &I;
3363
3364   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3365     // div X, 1 == X
3366     if (RHS->equalsInt(1))
3367       return ReplaceInstUsesWith(I, Op0);
3368
3369     // (X / C1) / C2  -> X / (C1*C2)
3370     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3371       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3372         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3373           if (MultiplyOverflows(RHS, LHSRHS,
3374                                 I.getOpcode()==Instruction::SDiv))
3375             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3376           else 
3377             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
3378                                       ConstantExpr::getMul(RHS, LHSRHS));
3379         }
3380
3381     if (!RHS->isZero()) { // avoid X udiv 0
3382       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3383         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3384           return R;
3385       if (isa<PHINode>(Op0))
3386         if (Instruction *NV = FoldOpIntoPhi(I))
3387           return NV;
3388     }
3389   }
3390
3391   // 0 / X == 0, we don't need to preserve faults!
3392   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3393     if (LHS->equalsInt(0))
3394       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3395
3396   // It can't be division by zero, hence it must be division by one.
3397   if (I.getType() == Type::getInt1Ty(*Context))
3398     return ReplaceInstUsesWith(I, Op0);
3399
3400   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3401     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3402       // div X, 1 == X
3403       if (X->isOne())
3404         return ReplaceInstUsesWith(I, Op0);
3405   }
3406
3407   return 0;
3408 }
3409
3410 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3411   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3412
3413   // Handle the integer div common cases
3414   if (Instruction *Common = commonIDivTransforms(I))
3415     return Common;
3416
3417   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3418     // X udiv C^2 -> X >> C
3419     // Check to see if this is an unsigned division with an exact power of 2,
3420     // if so, convert to a right shift.
3421     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3422       return BinaryOperator::CreateLShr(Op0, 
3423             ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3424
3425     // X udiv C, where C >= signbit
3426     if (C->getValue().isNegative()) {
3427       Value *IC = Builder->CreateICmpULT( Op0, C);
3428       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3429                                 ConstantInt::get(I.getType(), 1));
3430     }
3431   }
3432
3433   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3434   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3435     if (RHSI->getOpcode() == Instruction::Shl &&
3436         isa<ConstantInt>(RHSI->getOperand(0))) {
3437       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3438       if (C1.isPowerOf2()) {
3439         Value *N = RHSI->getOperand(1);
3440         const Type *NTy = N->getType();
3441         if (uint32_t C2 = C1.logBase2())
3442           N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
3443         return BinaryOperator::CreateLShr(Op0, N);
3444       }
3445     }
3446   }
3447   
3448   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3449   // where C1&C2 are powers of two.
3450   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3451     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3452       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3453         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3454         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3455           // Compute the shift amounts
3456           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3457           // Construct the "on true" case of the select
3458           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3459           Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
3460   
3461           // Construct the "on false" case of the select
3462           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3463           Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
3464
3465           // construct the select instruction and return it.
3466           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3467         }
3468       }
3469   return 0;
3470 }
3471
3472 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3473   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3474
3475   // Handle the integer div common cases
3476   if (Instruction *Common = commonIDivTransforms(I))
3477     return Common;
3478
3479   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3480     // sdiv X, -1 == -X
3481     if (RHS->isAllOnesValue())
3482       return BinaryOperator::CreateNeg(Op0);
3483
3484     // sdiv X, C  -->  ashr X, log2(C)
3485     if (cast<SDivOperator>(&I)->isExact() &&
3486         RHS->getValue().isNonNegative() &&
3487         RHS->getValue().isPowerOf2()) {
3488       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3489                                             RHS->getValue().exactLogBase2());
3490       return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3491     }
3492
3493     // -X/C  -->  X/-C  provided the negation doesn't overflow.
3494     if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3495       if (isa<Constant>(Sub->getOperand(0)) &&
3496           cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3497           Sub->hasNoSignedWrap())
3498         return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3499                                           ConstantExpr::getNeg(RHS));
3500   }
3501
3502   // If the sign bits of both operands are zero (i.e. we can prove they are
3503   // unsigned inputs), turn this into a udiv.
3504   if (I.getType()->isInteger()) {
3505     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3506     if (MaskedValueIsZero(Op0, Mask)) {
3507       if (MaskedValueIsZero(Op1, Mask)) {
3508         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3509         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3510       }
3511       ConstantInt *ShiftedInt;
3512       if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3513           ShiftedInt->getValue().isPowerOf2()) {
3514         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3515         // Safe because the only negative value (1 << Y) can take on is
3516         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3517         // the sign bit set.
3518         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3519       }
3520     }
3521   }
3522   
3523   return 0;
3524 }
3525
3526 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3527   return commonDivTransforms(I);
3528 }
3529
3530 /// This function implements the transforms on rem instructions that work
3531 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3532 /// is used by the visitors to those instructions.
3533 /// @brief Transforms common to all three rem instructions
3534 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3535   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3536
3537   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3538     if (I.getType()->isFPOrFPVector())
3539       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3540     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3541   }
3542   if (isa<UndefValue>(Op1))
3543     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3544
3545   // Handle cases involving: rem X, (select Cond, Y, Z)
3546   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3547     return &I;
3548
3549   return 0;
3550 }
3551
3552 /// This function implements the transforms common to both integer remainder
3553 /// instructions (urem and srem). It is called by the visitors to those integer
3554 /// remainder instructions.
3555 /// @brief Common integer remainder transforms
3556 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3557   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3558
3559   if (Instruction *common = commonRemTransforms(I))
3560     return common;
3561
3562   // 0 % X == 0 for integer, we don't need to preserve faults!
3563   if (Constant *LHS = dyn_cast<Constant>(Op0))
3564     if (LHS->isNullValue())
3565       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3566
3567   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3568     // X % 0 == undef, we don't need to preserve faults!
3569     if (RHS->equalsInt(0))
3570       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3571     
3572     if (RHS->equalsInt(1))  // X % 1 == 0
3573       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3574
3575     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3576       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3577         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3578           return R;
3579       } else if (isa<PHINode>(Op0I)) {
3580         if (Instruction *NV = FoldOpIntoPhi(I))
3581           return NV;
3582       }
3583
3584       // See if we can fold away this rem instruction.
3585       if (SimplifyDemandedInstructionBits(I))
3586         return &I;
3587     }
3588   }
3589
3590   return 0;
3591 }
3592
3593 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3594   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3595
3596   if (Instruction *common = commonIRemTransforms(I))
3597     return common;
3598   
3599   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3600     // X urem C^2 -> X and C
3601     // Check to see if this is an unsigned remainder with an exact power of 2,
3602     // if so, convert to a bitwise and.
3603     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3604       if (C->getValue().isPowerOf2())
3605         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3606   }
3607
3608   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3609     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3610     if (RHSI->getOpcode() == Instruction::Shl &&
3611         isa<ConstantInt>(RHSI->getOperand(0))) {
3612       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3613         Constant *N1 = Constant::getAllOnesValue(I.getType());
3614         Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
3615         return BinaryOperator::CreateAnd(Op0, Add);
3616       }
3617     }
3618   }
3619
3620   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3621   // where C1&C2 are powers of two.
3622   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3623     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3624       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3625         // STO == 0 and SFO == 0 handled above.
3626         if ((STO->getValue().isPowerOf2()) && 
3627             (SFO->getValue().isPowerOf2())) {
3628           Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3629                                               SI->getName()+".t");
3630           Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3631                                                SI->getName()+".f");
3632           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3633         }
3634       }
3635   }
3636   
3637   return 0;
3638 }
3639
3640 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3641   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3642
3643   // Handle the integer rem common cases
3644   if (Instruction *Common = commonIRemTransforms(I))
3645     return Common;
3646   
3647   if (Value *RHSNeg = dyn_castNegVal(Op1))
3648     if (!isa<Constant>(RHSNeg) ||
3649         (isa<ConstantInt>(RHSNeg) &&
3650          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3651       // X % -Y -> X % Y
3652       Worklist.AddValue(I.getOperand(1));
3653       I.setOperand(1, RHSNeg);
3654       return &I;
3655     }
3656
3657   // If the sign bits of both operands are zero (i.e. we can prove they are
3658   // unsigned inputs), turn this into a urem.
3659   if (I.getType()->isInteger()) {
3660     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3661     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3662       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3663       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3664     }
3665   }
3666
3667   // If it's a constant vector, flip any negative values positive.
3668   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3669     unsigned VWidth = RHSV->getNumOperands();
3670
3671     bool hasNegative = false;
3672     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3673       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3674         if (RHS->getValue().isNegative())
3675           hasNegative = true;
3676
3677     if (hasNegative) {
3678       std::vector<Constant *> Elts(VWidth);
3679       for (unsigned i = 0; i != VWidth; ++i) {
3680         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3681           if (RHS->getValue().isNegative())
3682             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3683           else
3684             Elts[i] = RHS;
3685         }
3686       }
3687
3688       Constant *NewRHSV = ConstantVector::get(Elts);
3689       if (NewRHSV != RHSV) {
3690         Worklist.AddValue(I.getOperand(1));
3691         I.setOperand(1, NewRHSV);
3692         return &I;
3693       }
3694     }
3695   }
3696
3697   return 0;
3698 }
3699
3700 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3701   return commonRemTransforms(I);
3702 }
3703
3704 // isOneBitSet - Return true if there is exactly one bit set in the specified
3705 // constant.
3706 static bool isOneBitSet(const ConstantInt *CI) {
3707   return CI->getValue().isPowerOf2();
3708 }
3709
3710 // isHighOnes - Return true if the constant is of the form 1+0+.
3711 // This is the same as lowones(~X).
3712 static bool isHighOnes(const ConstantInt *CI) {
3713   return (~CI->getValue() + 1).isPowerOf2();
3714 }
3715
3716 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3717 /// are carefully arranged to allow folding of expressions such as:
3718 ///
3719 ///      (A < B) | (A > B) --> (A != B)
3720 ///
3721 /// Note that this is only valid if the first and second predicates have the
3722 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3723 ///
3724 /// Three bits are used to represent the condition, as follows:
3725 ///   0  A > B
3726 ///   1  A == B
3727 ///   2  A < B
3728 ///
3729 /// <=>  Value  Definition
3730 /// 000     0   Always false
3731 /// 001     1   A >  B
3732 /// 010     2   A == B
3733 /// 011     3   A >= B
3734 /// 100     4   A <  B
3735 /// 101     5   A != B
3736 /// 110     6   A <= B
3737 /// 111     7   Always true
3738 ///  
3739 static unsigned getICmpCode(const ICmpInst *ICI) {
3740   switch (ICI->getPredicate()) {
3741     // False -> 0
3742   case ICmpInst::ICMP_UGT: return 1;  // 001
3743   case ICmpInst::ICMP_SGT: return 1;  // 001
3744   case ICmpInst::ICMP_EQ:  return 2;  // 010
3745   case ICmpInst::ICMP_UGE: return 3;  // 011
3746   case ICmpInst::ICMP_SGE: return 3;  // 011
3747   case ICmpInst::ICMP_ULT: return 4;  // 100
3748   case ICmpInst::ICMP_SLT: return 4;  // 100
3749   case ICmpInst::ICMP_NE:  return 5;  // 101
3750   case ICmpInst::ICMP_ULE: return 6;  // 110
3751   case ICmpInst::ICMP_SLE: return 6;  // 110
3752     // True -> 7
3753   default:
3754     llvm_unreachable("Invalid ICmp predicate!");
3755     return 0;
3756   }
3757 }
3758
3759 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3760 /// predicate into a three bit mask. It also returns whether it is an ordered
3761 /// predicate by reference.
3762 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3763   isOrdered = false;
3764   switch (CC) {
3765   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3766   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3767   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3768   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3769   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3770   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3771   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3772   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3773   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3774   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3775   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3776   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3777   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3778   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3779     // True -> 7
3780   default:
3781     // Not expecting FCMP_FALSE and FCMP_TRUE;
3782     llvm_unreachable("Unexpected FCmp predicate!");
3783     return 0;
3784   }
3785 }
3786
3787 /// getICmpValue - This is the complement of getICmpCode, which turns an
3788 /// opcode and two operands into either a constant true or false, or a brand 
3789 /// new ICmp instruction. The sign is passed in to determine which kind
3790 /// of predicate to use in the new icmp instruction.
3791 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3792                            LLVMContext *Context) {
3793   switch (code) {
3794   default: llvm_unreachable("Illegal ICmp code!");
3795   case  0: return ConstantInt::getFalse(*Context);
3796   case  1: 
3797     if (sign)
3798       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3799     else
3800       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3801   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3802   case  3: 
3803     if (sign)
3804       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3805     else
3806       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3807   case  4: 
3808     if (sign)
3809       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3810     else
3811       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3812   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3813   case  6: 
3814     if (sign)
3815       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3816     else
3817       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3818   case  7: return ConstantInt::getTrue(*Context);
3819   }
3820 }
3821
3822 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3823 /// opcode and two operands into either a FCmp instruction. isordered is passed
3824 /// in to determine which kind of predicate to use in the new fcmp instruction.
3825 static Value *getFCmpValue(bool isordered, unsigned code,
3826                            Value *LHS, Value *RHS, LLVMContext *Context) {
3827   switch (code) {
3828   default: llvm_unreachable("Illegal FCmp code!");
3829   case  0:
3830     if (isordered)
3831       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3832     else
3833       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3834   case  1: 
3835     if (isordered)
3836       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3837     else
3838       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3839   case  2: 
3840     if (isordered)
3841       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3842     else
3843       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3844   case  3: 
3845     if (isordered)
3846       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3847     else
3848       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3849   case  4: 
3850     if (isordered)
3851       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3852     else
3853       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3854   case  5: 
3855     if (isordered)
3856       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3857     else
3858       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3859   case  6: 
3860     if (isordered)
3861       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3862     else
3863       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3864   case  7: return ConstantInt::getTrue(*Context);
3865   }
3866 }
3867
3868 /// PredicatesFoldable - Return true if both predicates match sign or if at
3869 /// least one of them is an equality comparison (which is signless).
3870 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3871   return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3872          (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3873          (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
3874 }
3875
3876 namespace { 
3877 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3878 struct FoldICmpLogical {
3879   InstCombiner &IC;
3880   Value *LHS, *RHS;
3881   ICmpInst::Predicate pred;
3882   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3883     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3884       pred(ICI->getPredicate()) {}
3885   bool shouldApply(Value *V) const {
3886     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3887       if (PredicatesFoldable(pred, ICI->getPredicate()))
3888         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3889                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3890     return false;
3891   }
3892   Instruction *apply(Instruction &Log) const {
3893     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3894     if (ICI->getOperand(0) != LHS) {
3895       assert(ICI->getOperand(1) == LHS);
3896       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3897     }
3898
3899     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3900     unsigned LHSCode = getICmpCode(ICI);
3901     unsigned RHSCode = getICmpCode(RHSICI);
3902     unsigned Code;
3903     switch (Log.getOpcode()) {
3904     case Instruction::And: Code = LHSCode & RHSCode; break;
3905     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3906     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3907     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3908     }
3909
3910     bool isSigned = RHSICI->isSigned() || ICI->isSigned();
3911     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3912     if (Instruction *I = dyn_cast<Instruction>(RV))
3913       return I;
3914     // Otherwise, it's a constant boolean value...
3915     return IC.ReplaceInstUsesWith(Log, RV);
3916   }
3917 };
3918 } // end anonymous namespace
3919
3920 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3921 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3922 // guaranteed to be a binary operator.
3923 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3924                                     ConstantInt *OpRHS,
3925                                     ConstantInt *AndRHS,
3926                                     BinaryOperator &TheAnd) {
3927   Value *X = Op->getOperand(0);
3928   Constant *Together = 0;
3929   if (!Op->isShift())
3930     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3931
3932   switch (Op->getOpcode()) {
3933   case Instruction::Xor:
3934     if (Op->hasOneUse()) {
3935       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3936       Value *And = Builder->CreateAnd(X, AndRHS);
3937       And->takeName(Op);
3938       return BinaryOperator::CreateXor(And, Together);
3939     }
3940     break;
3941   case Instruction::Or:
3942     if (Together == AndRHS) // (X | C) & C --> C
3943       return ReplaceInstUsesWith(TheAnd, AndRHS);
3944
3945     if (Op->hasOneUse() && Together != OpRHS) {
3946       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3947       Value *Or = Builder->CreateOr(X, Together);
3948       Or->takeName(Op);
3949       return BinaryOperator::CreateAnd(Or, AndRHS);
3950     }
3951     break;
3952   case Instruction::Add:
3953     if (Op->hasOneUse()) {
3954       // Adding a one to a single bit bit-field should be turned into an XOR
3955       // of the bit.  First thing to check is to see if this AND is with a
3956       // single bit constant.
3957       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3958
3959       // If there is only one bit set...
3960       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3961         // Ok, at this point, we know that we are masking the result of the
3962         // ADD down to exactly one bit.  If the constant we are adding has
3963         // no bits set below this bit, then we can eliminate the ADD.
3964         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3965
3966         // Check to see if any bits below the one bit set in AndRHSV are set.
3967         if ((AddRHS & (AndRHSV-1)) == 0) {
3968           // If not, the only thing that can effect the output of the AND is
3969           // the bit specified by AndRHSV.  If that bit is set, the effect of
3970           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3971           // no effect.
3972           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3973             TheAnd.setOperand(0, X);
3974             return &TheAnd;
3975           } else {
3976             // Pull the XOR out of the AND.
3977             Value *NewAnd = Builder->CreateAnd(X, AndRHS);
3978             NewAnd->takeName(Op);
3979             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3980           }
3981         }
3982       }
3983     }
3984     break;
3985
3986   case Instruction::Shl: {
3987     // We know that the AND will not produce any of the bits shifted in, so if
3988     // the anded constant includes them, clear them now!
3989     //
3990     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3991     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3992     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3993     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3994
3995     if (CI->getValue() == ShlMask) { 
3996     // Masking out bits that the shift already masks
3997       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3998     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3999       TheAnd.setOperand(1, CI);
4000       return &TheAnd;
4001     }
4002     break;
4003   }
4004   case Instruction::LShr:
4005   {
4006     // We know that the AND will not produce any of the bits shifted in, so if
4007     // the anded constant includes them, clear them now!  This only applies to
4008     // unsigned shifts, because a signed shr may bring in set bits!
4009     //
4010     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
4011     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
4012     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
4013     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
4014
4015     if (CI->getValue() == ShrMask) {   
4016     // Masking out bits that the shift already masks.
4017       return ReplaceInstUsesWith(TheAnd, Op);
4018     } else if (CI != AndRHS) {
4019       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
4020       return &TheAnd;
4021     }
4022     break;
4023   }
4024   case Instruction::AShr:
4025     // Signed shr.
4026     // See if this is shifting in some sign extension, then masking it out
4027     // with an and.
4028     if (Op->hasOneUse()) {
4029       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
4030       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
4031       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
4032       Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
4033       if (C == AndRHS) {          // Masking out bits shifted in.
4034         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
4035         // Make the argument unsigned.
4036         Value *ShVal = Op->getOperand(0);
4037         ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
4038         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
4039       }
4040     }
4041     break;
4042   }
4043   return 0;
4044 }
4045
4046
4047 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
4048 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
4049 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
4050 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
4051 /// insert new instructions.
4052 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
4053                                            bool isSigned, bool Inside, 
4054                                            Instruction &IB) {
4055   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
4056             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
4057          "Lo is not <= Hi in range emission code!");
4058     
4059   if (Inside) {
4060     if (Lo == Hi)  // Trivially false.
4061       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
4062
4063     // V >= Min && V < Hi --> V < Hi
4064     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
4065       ICmpInst::Predicate pred = (isSigned ? 
4066         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
4067       return new ICmpInst(pred, V, Hi);
4068     }
4069
4070     // Emit V-Lo <u Hi-Lo
4071     Constant *NegLo = ConstantExpr::getNeg(Lo);
4072     Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
4073     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
4074     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
4075   }
4076
4077   if (Lo == Hi)  // Trivially true.
4078     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
4079
4080   // V < Min || V >= Hi -> V > Hi-1
4081   Hi = SubOne(cast<ConstantInt>(Hi));
4082   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
4083     ICmpInst::Predicate pred = (isSigned ? 
4084         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
4085     return new ICmpInst(pred, V, Hi);
4086   }
4087
4088   // Emit V-Lo >u Hi-1-Lo
4089   // Note that Hi has already had one subtracted from it, above.
4090   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
4091   Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
4092   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
4093   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
4094 }
4095
4096 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
4097 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
4098 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
4099 // not, since all 1s are not contiguous.
4100 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
4101   const APInt& V = Val->getValue();
4102   uint32_t BitWidth = Val->getType()->getBitWidth();
4103   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
4104
4105   // look for the first zero bit after the run of ones
4106   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
4107   // look for the first non-zero bit
4108   ME = V.getActiveBits(); 
4109   return true;
4110 }
4111
4112 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
4113 /// where isSub determines whether the operator is a sub.  If we can fold one of
4114 /// the following xforms:
4115 /// 
4116 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
4117 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4118 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4119 ///
4120 /// return (A +/- B).
4121 ///
4122 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
4123                                         ConstantInt *Mask, bool isSub,
4124                                         Instruction &I) {
4125   Instruction *LHSI = dyn_cast<Instruction>(LHS);
4126   if (!LHSI || LHSI->getNumOperands() != 2 ||
4127       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
4128
4129   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
4130
4131   switch (LHSI->getOpcode()) {
4132   default: return 0;
4133   case Instruction::And:
4134     if (ConstantExpr::getAnd(N, Mask) == Mask) {
4135       // If the AndRHS is a power of two minus one (0+1+), this is simple.
4136       if ((Mask->getValue().countLeadingZeros() + 
4137            Mask->getValue().countPopulation()) == 
4138           Mask->getValue().getBitWidth())
4139         break;
4140
4141       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4142       // part, we don't need any explicit masks to take them out of A.  If that
4143       // is all N is, ignore it.
4144       uint32_t MB = 0, ME = 0;
4145       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
4146         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
4147         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
4148         if (MaskedValueIsZero(RHS, Mask))
4149           break;
4150       }
4151     }
4152     return 0;
4153   case Instruction::Or:
4154   case Instruction::Xor:
4155     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
4156     if ((Mask->getValue().countLeadingZeros() + 
4157          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
4158         && ConstantExpr::getAnd(N, Mask)->isNullValue())
4159       break;
4160     return 0;
4161   }
4162   
4163   if (isSub)
4164     return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
4165   return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
4166 }
4167
4168 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
4169 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
4170                                           ICmpInst *LHS, ICmpInst *RHS) {
4171   Value *Val, *Val2;
4172   ConstantInt *LHSCst, *RHSCst;
4173   ICmpInst::Predicate LHSCC, RHSCC;
4174   
4175   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
4176   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4177                          m_ConstantInt(LHSCst))) ||
4178       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4179                          m_ConstantInt(RHSCst))))
4180     return 0;
4181   
4182   if (LHSCst == RHSCst && LHSCC == RHSCC) {
4183     // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
4184     // where C is a power of 2
4185     if (LHSCC == ICmpInst::ICMP_ULT &&
4186         LHSCst->getValue().isPowerOf2()) {
4187       Value *NewOr = Builder->CreateOr(Val, Val2);
4188       return new ICmpInst(LHSCC, NewOr, LHSCst);
4189     }
4190     
4191     // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
4192     if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
4193       Value *NewOr = Builder->CreateOr(Val, Val2);
4194       return new ICmpInst(LHSCC, NewOr, LHSCst);
4195     }
4196   }
4197   
4198   // From here on, we only handle:
4199   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
4200   if (Val != Val2) return 0;
4201   
4202   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4203   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4204       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4205       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4206       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4207     return 0;
4208   
4209   // We can't fold (ugt x, C) & (sgt x, C2).
4210   if (!PredicatesFoldable(LHSCC, RHSCC))
4211     return 0;
4212     
4213   // Ensure that the larger constant is on the RHS.
4214   bool ShouldSwap;
4215   if (CmpInst::isSigned(LHSCC) ||
4216       (ICmpInst::isEquality(LHSCC) && 
4217        CmpInst::isSigned(RHSCC)))
4218     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4219   else
4220     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4221     
4222   if (ShouldSwap) {
4223     std::swap(LHS, RHS);
4224     std::swap(LHSCst, RHSCst);
4225     std::swap(LHSCC, RHSCC);
4226   }
4227
4228   // At this point, we know we have have two icmp instructions
4229   // comparing a value against two constants and and'ing the result
4230   // together.  Because of the above check, we know that we only have
4231   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
4232   // (from the FoldICmpLogical check above), that the two constants 
4233   // are not equal and that the larger constant is on the RHS
4234   assert(LHSCst != RHSCst && "Compares not folded above?");
4235
4236   switch (LHSCC) {
4237   default: llvm_unreachable("Unknown integer condition code!");
4238   case ICmpInst::ICMP_EQ:
4239     switch (RHSCC) {
4240     default: llvm_unreachable("Unknown integer condition code!");
4241     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
4242     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
4243     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
4244       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4245     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
4246     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
4247     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
4248       return ReplaceInstUsesWith(I, LHS);
4249     }
4250   case ICmpInst::ICMP_NE:
4251     switch (RHSCC) {
4252     default: llvm_unreachable("Unknown integer condition code!");
4253     case ICmpInst::ICMP_ULT:
4254       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4255         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
4256       break;                        // (X != 13 & X u< 15) -> no change
4257     case ICmpInst::ICMP_SLT:
4258       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4259         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
4260       break;                        // (X != 13 & X s< 15) -> no change
4261     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
4262     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
4263     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
4264       return ReplaceInstUsesWith(I, RHS);
4265     case ICmpInst::ICMP_NE:
4266       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
4267         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4268         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4269         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4270                             ConstantInt::get(Add->getType(), 1));
4271       }
4272       break;                        // (X != 13 & X != 15) -> no change
4273     }
4274     break;
4275   case ICmpInst::ICMP_ULT:
4276     switch (RHSCC) {
4277     default: llvm_unreachable("Unknown integer condition code!");
4278     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
4279     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
4280       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4281     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
4282       break;
4283     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
4284     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
4285       return ReplaceInstUsesWith(I, LHS);
4286     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
4287       break;
4288     }
4289     break;
4290   case ICmpInst::ICMP_SLT:
4291     switch (RHSCC) {
4292     default: llvm_unreachable("Unknown integer condition code!");
4293     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
4294     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
4295       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4296     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
4297       break;
4298     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
4299     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
4300       return ReplaceInstUsesWith(I, LHS);
4301     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
4302       break;
4303     }
4304     break;
4305   case ICmpInst::ICMP_UGT:
4306     switch (RHSCC) {
4307     default: llvm_unreachable("Unknown integer condition code!");
4308     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
4309     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
4310       return ReplaceInstUsesWith(I, RHS);
4311     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
4312       break;
4313     case ICmpInst::ICMP_NE:
4314       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4315         return new ICmpInst(LHSCC, Val, RHSCst);
4316       break;                        // (X u> 13 & X != 15) -> no change
4317     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
4318       return InsertRangeTest(Val, AddOne(LHSCst),
4319                              RHSCst, false, true, I);
4320     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
4321       break;
4322     }
4323     break;
4324   case ICmpInst::ICMP_SGT:
4325     switch (RHSCC) {
4326     default: llvm_unreachable("Unknown integer condition code!");
4327     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
4328     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
4329       return ReplaceInstUsesWith(I, RHS);
4330     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
4331       break;
4332     case ICmpInst::ICMP_NE:
4333       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4334         return new ICmpInst(LHSCC, Val, RHSCst);
4335       break;                        // (X s> 13 & X != 15) -> no change
4336     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
4337       return InsertRangeTest(Val, AddOne(LHSCst),
4338                              RHSCst, true, true, I);
4339     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
4340       break;
4341     }
4342     break;
4343   }
4344  
4345   return 0;
4346 }
4347
4348 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4349                                           FCmpInst *RHS) {
4350   
4351   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4352       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4353     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4354     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4355       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4356         // If either of the constants are nans, then the whole thing returns
4357         // false.
4358         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4359           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4360         return new FCmpInst(FCmpInst::FCMP_ORD,
4361                             LHS->getOperand(0), RHS->getOperand(0));
4362       }
4363     
4364     // Handle vector zeros.  This occurs because the canonical form of
4365     // "fcmp ord x,x" is "fcmp ord x, 0".
4366     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4367         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4368       return new FCmpInst(FCmpInst::FCMP_ORD,
4369                           LHS->getOperand(0), RHS->getOperand(0));
4370     return 0;
4371   }
4372   
4373   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4374   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4375   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4376   
4377   
4378   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4379     // Swap RHS operands to match LHS.
4380     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4381     std::swap(Op1LHS, Op1RHS);
4382   }
4383   
4384   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4385     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4386     if (Op0CC == Op1CC)
4387       return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4388     
4389     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
4390       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4391     if (Op0CC == FCmpInst::FCMP_TRUE)
4392       return ReplaceInstUsesWith(I, RHS);
4393     if (Op1CC == FCmpInst::FCMP_TRUE)
4394       return ReplaceInstUsesWith(I, LHS);
4395     
4396     bool Op0Ordered;
4397     bool Op1Ordered;
4398     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4399     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4400     if (Op1Pred == 0) {
4401       std::swap(LHS, RHS);
4402       std::swap(Op0Pred, Op1Pred);
4403       std::swap(Op0Ordered, Op1Ordered);
4404     }
4405     if (Op0Pred == 0) {
4406       // uno && ueq -> uno && (uno || eq) -> ueq
4407       // ord && olt -> ord && (ord && lt) -> olt
4408       if (Op0Ordered == Op1Ordered)
4409         return ReplaceInstUsesWith(I, RHS);
4410       
4411       // uno && oeq -> uno && (ord && eq) -> false
4412       // uno && ord -> false
4413       if (!Op0Ordered)
4414         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4415       // ord && ueq -> ord && (uno || eq) -> oeq
4416       return cast<Instruction>(getFCmpValue(true, Op1Pred,
4417                                             Op0LHS, Op0RHS, Context));
4418     }
4419   }
4420
4421   return 0;
4422 }
4423
4424
4425 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4426   bool Changed = SimplifyCommutative(I);
4427   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4428
4429   if (Value *V = SimplifyAndInst(Op0, Op1, TD))
4430     return ReplaceInstUsesWith(I, V);
4431
4432   // See if we can simplify any instructions used by the instruction whose sole 
4433   // purpose is to compute bits we don't care about.
4434   if (SimplifyDemandedInstructionBits(I))
4435     return &I;
4436   
4437
4438   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4439     const APInt &AndRHSMask = AndRHS->getValue();
4440     APInt NotAndRHS(~AndRHSMask);
4441
4442     // Optimize a variety of ((val OP C1) & C2) combinations...
4443     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4444       Value *Op0LHS = Op0I->getOperand(0);
4445       Value *Op0RHS = Op0I->getOperand(1);
4446       switch (Op0I->getOpcode()) {
4447       default: break;
4448       case Instruction::Xor:
4449       case Instruction::Or:
4450         // If the mask is only needed on one incoming arm, push it up.
4451         if (!Op0I->hasOneUse()) break;
4452           
4453         if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4454           // Not masking anything out for the LHS, move to RHS.
4455           Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4456                                              Op0RHS->getName()+".masked");
4457           return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4458         }
4459         if (!isa<Constant>(Op0RHS) &&
4460             MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4461           // Not masking anything out for the RHS, move to LHS.
4462           Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4463                                              Op0LHS->getName()+".masked");
4464           return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
4465         }
4466
4467         break;
4468       case Instruction::Add:
4469         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4470         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4471         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4472         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4473           return BinaryOperator::CreateAnd(V, AndRHS);
4474         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4475           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4476         break;
4477
4478       case Instruction::Sub:
4479         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4480         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4481         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4482         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4483           return BinaryOperator::CreateAnd(V, AndRHS);
4484
4485         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4486         // has 1's for all bits that the subtraction with A might affect.
4487         if (Op0I->hasOneUse()) {
4488           uint32_t BitWidth = AndRHSMask.getBitWidth();
4489           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4490           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4491
4492           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4493           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4494               MaskedValueIsZero(Op0LHS, Mask)) {
4495             Value *NewNeg = Builder->CreateNeg(Op0RHS);
4496             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4497           }
4498         }
4499         break;
4500
4501       case Instruction::Shl:
4502       case Instruction::LShr:
4503         // (1 << x) & 1 --> zext(x == 0)
4504         // (1 >> x) & 1 --> zext(x == 0)
4505         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4506           Value *NewICmp =
4507             Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
4508           return new ZExtInst(NewICmp, I.getType());
4509         }
4510         break;
4511       }
4512
4513       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4514         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4515           return Res;
4516     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4517       // If this is an integer truncation or change from signed-to-unsigned, and
4518       // if the source is an and/or with immediate, transform it.  This
4519       // frequently occurs for bitfield accesses.
4520       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4521         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4522             CastOp->getNumOperands() == 2)
4523           if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
4524             if (CastOp->getOpcode() == Instruction::And) {
4525               // Change: and (cast (and X, C1) to T), C2
4526               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4527               // This will fold the two constants together, which may allow 
4528               // other simplifications.
4529               Value *NewCast = Builder->CreateTruncOrBitCast(
4530                 CastOp->getOperand(0), I.getType(), 
4531                 CastOp->getName()+".shrunk");
4532               // trunc_or_bitcast(C1)&C2
4533               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4534               C3 = ConstantExpr::getAnd(C3, AndRHS);
4535               return BinaryOperator::CreateAnd(NewCast, C3);
4536             } else if (CastOp->getOpcode() == Instruction::Or) {
4537               // Change: and (cast (or X, C1) to T), C2
4538               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4539               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4540               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4541                 // trunc(C1)&C2
4542                 return ReplaceInstUsesWith(I, AndRHS);
4543             }
4544           }
4545       }
4546     }
4547
4548     // Try to fold constant and into select arguments.
4549     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4550       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4551         return R;
4552     if (isa<PHINode>(Op0))
4553       if (Instruction *NV = FoldOpIntoPhi(I))
4554         return NV;
4555   }
4556
4557
4558   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4559   if (Value *Op0NotVal = dyn_castNotVal(Op0))
4560     if (Value *Op1NotVal = dyn_castNotVal(Op1))
4561       if (Op0->hasOneUse() && Op1->hasOneUse()) {
4562         Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4563                                       I.getName()+".demorgan");
4564         return BinaryOperator::CreateNot(Or);
4565       }
4566
4567   {
4568     Value *A = 0, *B = 0, *C = 0, *D = 0;
4569     // (A|B) & ~(A&B) -> A^B
4570     if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
4571         match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4572         ((A == C && B == D) || (A == D && B == C)))
4573       return BinaryOperator::CreateXor(A, B);
4574     
4575     // ~(A&B) & (A|B) -> A^B
4576     if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
4577         match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4578         ((A == C && B == D) || (A == D && B == C)))
4579       return BinaryOperator::CreateXor(A, B);
4580     
4581     if (Op0->hasOneUse() &&
4582         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4583       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4584         I.swapOperands();     // Simplify below
4585         std::swap(Op0, Op1);
4586       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4587         cast<BinaryOperator>(Op0)->swapOperands();
4588         I.swapOperands();     // Simplify below
4589         std::swap(Op0, Op1);
4590       }
4591     }
4592
4593     if (Op1->hasOneUse() &&
4594         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4595       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4596         cast<BinaryOperator>(Op1)->swapOperands();
4597         std::swap(A, B);
4598       }
4599       if (A == Op0)                                // A&(A^B) -> A & ~B
4600         return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
4601     }
4602
4603     // (A&((~A)|B)) -> A&B
4604     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4605         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4606       return BinaryOperator::CreateAnd(A, Op1);
4607     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4608         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4609       return BinaryOperator::CreateAnd(A, Op0);
4610   }
4611   
4612   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4613     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4614     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4615       return R;
4616
4617     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4618       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4619         return Res;
4620   }
4621
4622   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4623   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4624     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4625       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4626         const Type *SrcTy = Op0C->getOperand(0)->getType();
4627         if (SrcTy == Op1C->getOperand(0)->getType() &&
4628             SrcTy->isIntOrIntVector() &&
4629             // Only do this if the casts both really cause code to be generated.
4630             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4631                               I.getType(), TD) &&
4632             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4633                               I.getType(), TD)) {
4634           Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4635                                             Op1C->getOperand(0), I.getName());
4636           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4637         }
4638       }
4639     
4640   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4641   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4642     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4643       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4644           SI0->getOperand(1) == SI1->getOperand(1) &&
4645           (SI0->hasOneUse() || SI1->hasOneUse())) {
4646         Value *NewOp =
4647           Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4648                              SI0->getName());
4649         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4650                                       SI1->getOperand(1));
4651       }
4652   }
4653
4654   // If and'ing two fcmp, try combine them into one.
4655   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4656     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4657       if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4658         return Res;
4659   }
4660
4661   return Changed ? &I : 0;
4662 }
4663
4664 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4665 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4666 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4667 /// the expression came from the corresponding "byte swapped" byte in some other
4668 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4669 /// we know that the expression deposits the low byte of %X into the high byte
4670 /// of the bswap result and that all other bytes are zero.  This expression is
4671 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4672 /// match.
4673 ///
4674 /// This function returns true if the match was unsuccessful and false if so.
4675 /// On entry to the function the "OverallLeftShift" is a signed integer value
4676 /// indicating the number of bytes that the subexpression is later shifted.  For
4677 /// example, if the expression is later right shifted by 16 bits, the
4678 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4679 /// byte of ByteValues is actually being set.
4680 ///
4681 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4682 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4683 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4684 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4685 /// always in the local (OverallLeftShift) coordinate space.
4686 ///
4687 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4688                               SmallVector<Value*, 8> &ByteValues) {
4689   if (Instruction *I = dyn_cast<Instruction>(V)) {
4690     // If this is an or instruction, it may be an inner node of the bswap.
4691     if (I->getOpcode() == Instruction::Or) {
4692       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4693                                ByteValues) ||
4694              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4695                                ByteValues);
4696     }
4697   
4698     // If this is a logical shift by a constant multiple of 8, recurse with
4699     // OverallLeftShift and ByteMask adjusted.
4700     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4701       unsigned ShAmt = 
4702         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4703       // Ensure the shift amount is defined and of a byte value.
4704       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4705         return true;
4706
4707       unsigned ByteShift = ShAmt >> 3;
4708       if (I->getOpcode() == Instruction::Shl) {
4709         // X << 2 -> collect(X, +2)
4710         OverallLeftShift += ByteShift;
4711         ByteMask >>= ByteShift;
4712       } else {
4713         // X >>u 2 -> collect(X, -2)
4714         OverallLeftShift -= ByteShift;
4715         ByteMask <<= ByteShift;
4716         ByteMask &= (~0U >> (32-ByteValues.size()));
4717       }
4718
4719       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4720       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4721
4722       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4723                                ByteValues);
4724     }
4725
4726     // If this is a logical 'and' with a mask that clears bytes, clear the
4727     // corresponding bytes in ByteMask.
4728     if (I->getOpcode() == Instruction::And &&
4729         isa<ConstantInt>(I->getOperand(1))) {
4730       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4731       unsigned NumBytes = ByteValues.size();
4732       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4733       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4734       
4735       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4736         // If this byte is masked out by a later operation, we don't care what
4737         // the and mask is.
4738         if ((ByteMask & (1 << i)) == 0)
4739           continue;
4740         
4741         // If the AndMask is all zeros for this byte, clear the bit.
4742         APInt MaskB = AndMask & Byte;
4743         if (MaskB == 0) {
4744           ByteMask &= ~(1U << i);
4745           continue;
4746         }
4747         
4748         // If the AndMask is not all ones for this byte, it's not a bytezap.
4749         if (MaskB != Byte)
4750           return true;
4751
4752         // Otherwise, this byte is kept.
4753       }
4754
4755       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4756                                ByteValues);
4757     }
4758   }
4759   
4760   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4761   // the input value to the bswap.  Some observations: 1) if more than one byte
4762   // is demanded from this input, then it could not be successfully assembled
4763   // into a byteswap.  At least one of the two bytes would not be aligned with
4764   // their ultimate destination.
4765   if (!isPowerOf2_32(ByteMask)) return true;
4766   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4767   
4768   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4769   // is demanded, it needs to go into byte 0 of the result.  This means that the
4770   // byte needs to be shifted until it lands in the right byte bucket.  The
4771   // shift amount depends on the position: if the byte is coming from the high
4772   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4773   // low part, it must be shifted left.
4774   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4775   if (InputByteNo < ByteValues.size()/2) {
4776     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4777       return true;
4778   } else {
4779     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4780       return true;
4781   }
4782   
4783   // If the destination byte value is already defined, the values are or'd
4784   // together, which isn't a bswap (unless it's an or of the same bits).
4785   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4786     return true;
4787   ByteValues[DestByteNo] = V;
4788   return false;
4789 }
4790
4791 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4792 /// If so, insert the new bswap intrinsic and return it.
4793 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4794   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4795   if (!ITy || ITy->getBitWidth() % 16 || 
4796       // ByteMask only allows up to 32-byte values.
4797       ITy->getBitWidth() > 32*8) 
4798     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4799   
4800   /// ByteValues - For each byte of the result, we keep track of which value
4801   /// defines each byte.
4802   SmallVector<Value*, 8> ByteValues;
4803   ByteValues.resize(ITy->getBitWidth()/8);
4804     
4805   // Try to find all the pieces corresponding to the bswap.
4806   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4807   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4808     return 0;
4809   
4810   // Check to see if all of the bytes come from the same value.
4811   Value *V = ByteValues[0];
4812   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4813   
4814   // Check to make sure that all of the bytes come from the same value.
4815   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4816     if (ByteValues[i] != V)
4817       return 0;
4818   const Type *Tys[] = { ITy };
4819   Module *M = I.getParent()->getParent()->getParent();
4820   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4821   return CallInst::Create(F, V);
4822 }
4823
4824 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4825 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4826 /// we can simplify this expression to "cond ? C : D or B".
4827 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4828                                          Value *C, Value *D,
4829                                          LLVMContext *Context) {
4830   // If A is not a select of -1/0, this cannot match.
4831   Value *Cond = 0;
4832   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4833     return 0;
4834
4835   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4836   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4837     return SelectInst::Create(Cond, C, B);
4838   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4839     return SelectInst::Create(Cond, C, B);
4840   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4841   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4842     return SelectInst::Create(Cond, C, D);
4843   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4844     return SelectInst::Create(Cond, C, D);
4845   return 0;
4846 }
4847
4848 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4849 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4850                                          ICmpInst *LHS, ICmpInst *RHS) {
4851   Value *Val, *Val2;
4852   ConstantInt *LHSCst, *RHSCst;
4853   ICmpInst::Predicate LHSCC, RHSCC;
4854   
4855   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4856   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4857       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4858     return 0;
4859
4860   
4861   // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
4862   if (LHSCst == RHSCst && LHSCC == RHSCC &&
4863       LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
4864     Value *NewOr = Builder->CreateOr(Val, Val2);
4865     return new ICmpInst(LHSCC, NewOr, LHSCst);
4866   }
4867   
4868   // From here on, we only handle:
4869   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4870   if (Val != Val2) return 0;
4871   
4872   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4873   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4874       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4875       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4876       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4877     return 0;
4878   
4879   // We can't fold (ugt x, C) | (sgt x, C2).
4880   if (!PredicatesFoldable(LHSCC, RHSCC))
4881     return 0;
4882   
4883   // Ensure that the larger constant is on the RHS.
4884   bool ShouldSwap;
4885   if (CmpInst::isSigned(LHSCC) ||
4886       (ICmpInst::isEquality(LHSCC) && 
4887        CmpInst::isSigned(RHSCC)))
4888     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4889   else
4890     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4891   
4892   if (ShouldSwap) {
4893     std::swap(LHS, RHS);
4894     std::swap(LHSCst, RHSCst);
4895     std::swap(LHSCC, RHSCC);
4896   }
4897   
4898   // At this point, we know we have have two icmp instructions
4899   // comparing a value against two constants and or'ing the result
4900   // together.  Because of the above check, we know that we only have
4901   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4902   // FoldICmpLogical check above), that the two constants are not
4903   // equal.
4904   assert(LHSCst != RHSCst && "Compares not folded above?");
4905
4906   switch (LHSCC) {
4907   default: llvm_unreachable("Unknown integer condition code!");
4908   case ICmpInst::ICMP_EQ:
4909     switch (RHSCC) {
4910     default: llvm_unreachable("Unknown integer condition code!");
4911     case ICmpInst::ICMP_EQ:
4912       if (LHSCst == SubOne(RHSCst)) {
4913         // (X == 13 | X == 14) -> X-13 <u 2
4914         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4915         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4916         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4917         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4918       }
4919       break;                         // (X == 13 | X == 15) -> no change
4920     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4921     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4922       break;
4923     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4924     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4925     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4926       return ReplaceInstUsesWith(I, RHS);
4927     }
4928     break;
4929   case ICmpInst::ICMP_NE:
4930     switch (RHSCC) {
4931     default: llvm_unreachable("Unknown integer condition code!");
4932     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4933     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4934     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4935       return ReplaceInstUsesWith(I, LHS);
4936     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4937     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4938     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4939       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4940     }
4941     break;
4942   case ICmpInst::ICMP_ULT:
4943     switch (RHSCC) {
4944     default: llvm_unreachable("Unknown integer condition code!");
4945     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4946       break;
4947     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4948       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4949       // this can cause overflow.
4950       if (RHSCst->isMaxValue(false))
4951         return ReplaceInstUsesWith(I, LHS);
4952       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4953                              false, false, I);
4954     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4955       break;
4956     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4957     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4958       return ReplaceInstUsesWith(I, RHS);
4959     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4960       break;
4961     }
4962     break;
4963   case ICmpInst::ICMP_SLT:
4964     switch (RHSCC) {
4965     default: llvm_unreachable("Unknown integer condition code!");
4966     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4967       break;
4968     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4969       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4970       // this can cause overflow.
4971       if (RHSCst->isMaxValue(true))
4972         return ReplaceInstUsesWith(I, LHS);
4973       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4974                              true, false, I);
4975     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4976       break;
4977     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4978     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4979       return ReplaceInstUsesWith(I, RHS);
4980     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4981       break;
4982     }
4983     break;
4984   case ICmpInst::ICMP_UGT:
4985     switch (RHSCC) {
4986     default: llvm_unreachable("Unknown integer condition code!");
4987     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4988     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4989       return ReplaceInstUsesWith(I, LHS);
4990     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4991       break;
4992     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4993     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4994       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4995     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4996       break;
4997     }
4998     break;
4999   case ICmpInst::ICMP_SGT:
5000     switch (RHSCC) {
5001     default: llvm_unreachable("Unknown integer condition code!");
5002     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
5003     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
5004       return ReplaceInstUsesWith(I, LHS);
5005     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
5006       break;
5007     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
5008     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
5009       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5010     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
5011       break;
5012     }
5013     break;
5014   }
5015   return 0;
5016 }
5017
5018 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
5019                                          FCmpInst *RHS) {
5020   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
5021       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
5022       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
5023     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
5024       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
5025         // If either of the constants are nans, then the whole thing returns
5026         // true.
5027         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
5028           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5029         
5030         // Otherwise, no need to compare the two constants, compare the
5031         // rest.
5032         return new FCmpInst(FCmpInst::FCMP_UNO,
5033                             LHS->getOperand(0), RHS->getOperand(0));
5034       }
5035     
5036     // Handle vector zeros.  This occurs because the canonical form of
5037     // "fcmp uno x,x" is "fcmp uno x, 0".
5038     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
5039         isa<ConstantAggregateZero>(RHS->getOperand(1)))
5040       return new FCmpInst(FCmpInst::FCMP_UNO,
5041                           LHS->getOperand(0), RHS->getOperand(0));
5042     
5043     return 0;
5044   }
5045   
5046   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
5047   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
5048   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
5049   
5050   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
5051     // Swap RHS operands to match LHS.
5052     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
5053     std::swap(Op1LHS, Op1RHS);
5054   }
5055   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
5056     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
5057     if (Op0CC == Op1CC)
5058       return new FCmpInst((FCmpInst::Predicate)Op0CC,
5059                           Op0LHS, Op0RHS);
5060     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
5061       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5062     if (Op0CC == FCmpInst::FCMP_FALSE)
5063       return ReplaceInstUsesWith(I, RHS);
5064     if (Op1CC == FCmpInst::FCMP_FALSE)
5065       return ReplaceInstUsesWith(I, LHS);
5066     bool Op0Ordered;
5067     bool Op1Ordered;
5068     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
5069     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
5070     if (Op0Ordered == Op1Ordered) {
5071       // If both are ordered or unordered, return a new fcmp with
5072       // or'ed predicates.
5073       Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
5074                                Op0LHS, Op0RHS, Context);
5075       if (Instruction *I = dyn_cast<Instruction>(RV))
5076         return I;
5077       // Otherwise, it's a constant boolean value...
5078       return ReplaceInstUsesWith(I, RV);
5079     }
5080   }
5081   return 0;
5082 }
5083
5084 /// FoldOrWithConstants - This helper function folds:
5085 ///
5086 ///     ((A | B) & C1) | (B & C2)
5087 ///
5088 /// into:
5089 /// 
5090 ///     (A & C1) | B
5091 ///
5092 /// when the XOR of the two constants is "all ones" (-1).
5093 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
5094                                                Value *A, Value *B, Value *C) {
5095   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
5096   if (!CI1) return 0;
5097
5098   Value *V1 = 0;
5099   ConstantInt *CI2 = 0;
5100   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
5101
5102   APInt Xor = CI1->getValue() ^ CI2->getValue();
5103   if (!Xor.isAllOnesValue()) return 0;
5104
5105   if (V1 == A || V1 == B) {
5106     Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
5107     return BinaryOperator::CreateOr(NewOp, V1);
5108   }
5109
5110   return 0;
5111 }
5112
5113 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
5114   bool Changed = SimplifyCommutative(I);
5115   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5116
5117   if (Value *V = SimplifyOrInst(Op0, Op1, TD))
5118     return ReplaceInstUsesWith(I, V);
5119   
5120   
5121   // See if we can simplify any instructions used by the instruction whose sole 
5122   // purpose is to compute bits we don't care about.
5123   if (SimplifyDemandedInstructionBits(I))
5124     return &I;
5125
5126   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5127     ConstantInt *C1 = 0; Value *X = 0;
5128     // (X & C1) | C2 --> (X | C2) & (C1|C2)
5129     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
5130         isOnlyUse(Op0)) {
5131       Value *Or = Builder->CreateOr(X, RHS);
5132       Or->takeName(Op0);
5133       return BinaryOperator::CreateAnd(Or, 
5134                ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
5135     }
5136
5137     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
5138     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
5139         isOnlyUse(Op0)) {
5140       Value *Or = Builder->CreateOr(X, RHS);
5141       Or->takeName(Op0);
5142       return BinaryOperator::CreateXor(Or,
5143                  ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
5144     }
5145
5146     // Try to fold constant and into select arguments.
5147     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5148       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5149         return R;
5150     if (isa<PHINode>(Op0))
5151       if (Instruction *NV = FoldOpIntoPhi(I))
5152         return NV;
5153   }
5154
5155   Value *A = 0, *B = 0;
5156   ConstantInt *C1 = 0, *C2 = 0;
5157
5158   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
5159   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
5160   if (match(Op0, m_Or(m_Value(), m_Value())) ||
5161       match(Op1, m_Or(m_Value(), m_Value())) ||
5162       (match(Op0, m_Shift(m_Value(), m_Value())) &&
5163        match(Op1, m_Shift(m_Value(), m_Value())))) {
5164     if (Instruction *BSwap = MatchBSwap(I))
5165       return BSwap;
5166   }
5167   
5168   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
5169   if (Op0->hasOneUse() &&
5170       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
5171       MaskedValueIsZero(Op1, C1->getValue())) {
5172     Value *NOr = Builder->CreateOr(A, Op1);
5173     NOr->takeName(Op0);
5174     return BinaryOperator::CreateXor(NOr, C1);
5175   }
5176
5177   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
5178   if (Op1->hasOneUse() &&
5179       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
5180       MaskedValueIsZero(Op0, C1->getValue())) {
5181     Value *NOr = Builder->CreateOr(A, Op0);
5182     NOr->takeName(Op0);
5183     return BinaryOperator::CreateXor(NOr, C1);
5184   }
5185
5186   // (A & C)|(B & D)
5187   Value *C = 0, *D = 0;
5188   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
5189       match(Op1, m_And(m_Value(B), m_Value(D)))) {
5190     Value *V1 = 0, *V2 = 0, *V3 = 0;
5191     C1 = dyn_cast<ConstantInt>(C);
5192     C2 = dyn_cast<ConstantInt>(D);
5193     if (C1 && C2) {  // (A & C1)|(B & C2)
5194       // If we have: ((V + N) & C1) | (V & C2)
5195       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
5196       // replace with V+N.
5197       if (C1->getValue() == ~C2->getValue()) {
5198         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
5199             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
5200           // Add commutes, try both ways.
5201           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
5202             return ReplaceInstUsesWith(I, A);
5203           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
5204             return ReplaceInstUsesWith(I, A);
5205         }
5206         // Or commutes, try both ways.
5207         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
5208             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
5209           // Add commutes, try both ways.
5210           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
5211             return ReplaceInstUsesWith(I, B);
5212           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
5213             return ReplaceInstUsesWith(I, B);
5214         }
5215       }
5216       V1 = 0; V2 = 0; V3 = 0;
5217     }
5218     
5219     // Check to see if we have any common things being and'ed.  If so, find the
5220     // terms for V1 & (V2|V3).
5221     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
5222       if (A == B)      // (A & C)|(A & D) == A & (C|D)
5223         V1 = A, V2 = C, V3 = D;
5224       else if (A == D) // (A & C)|(B & A) == A & (B|C)
5225         V1 = A, V2 = B, V3 = C;
5226       else if (C == B) // (A & C)|(C & D) == C & (A|D)
5227         V1 = C, V2 = A, V3 = D;
5228       else if (C == D) // (A & C)|(B & C) == C & (A|B)
5229         V1 = C, V2 = A, V3 = B;
5230       
5231       if (V1) {
5232         Value *Or = Builder->CreateOr(V2, V3, "tmp");
5233         return BinaryOperator::CreateAnd(V1, Or);
5234       }
5235     }
5236
5237     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
5238     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
5239       return Match;
5240     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
5241       return Match;
5242     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
5243       return Match;
5244     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
5245       return Match;
5246
5247     // ((A&~B)|(~A&B)) -> A^B
5248     if ((match(C, m_Not(m_Specific(D))) &&
5249          match(B, m_Not(m_Specific(A)))))
5250       return BinaryOperator::CreateXor(A, D);
5251     // ((~B&A)|(~A&B)) -> A^B
5252     if ((match(A, m_Not(m_Specific(D))) &&
5253          match(B, m_Not(m_Specific(C)))))
5254       return BinaryOperator::CreateXor(C, D);
5255     // ((A&~B)|(B&~A)) -> A^B
5256     if ((match(C, m_Not(m_Specific(B))) &&
5257          match(D, m_Not(m_Specific(A)))))
5258       return BinaryOperator::CreateXor(A, B);
5259     // ((~B&A)|(B&~A)) -> A^B
5260     if ((match(A, m_Not(m_Specific(B))) &&
5261          match(D, m_Not(m_Specific(C)))))
5262       return BinaryOperator::CreateXor(C, B);
5263   }
5264   
5265   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
5266   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
5267     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
5268       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
5269           SI0->getOperand(1) == SI1->getOperand(1) &&
5270           (SI0->hasOneUse() || SI1->hasOneUse())) {
5271         Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
5272                                          SI0->getName());
5273         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
5274                                       SI1->getOperand(1));
5275       }
5276   }
5277
5278   // ((A|B)&1)|(B&-2) -> (A&1) | B
5279   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5280       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
5281     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
5282     if (Ret) return Ret;
5283   }
5284   // (B&-2)|((A|B)&1) -> (A&1) | B
5285   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5286       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
5287     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
5288     if (Ret) return Ret;
5289   }
5290
5291   // (~A | ~B) == (~(A & B)) - De Morgan's Law
5292   if (Value *Op0NotVal = dyn_castNotVal(Op0))
5293     if (Value *Op1NotVal = dyn_castNotVal(Op1))
5294       if (Op0->hasOneUse() && Op1->hasOneUse()) {
5295         Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
5296                                         I.getName()+".demorgan");
5297         return BinaryOperator::CreateNot(And);
5298       }
5299
5300   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5301   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
5302     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5303       return R;
5304
5305     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5306       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5307         return Res;
5308   }
5309     
5310   // fold (or (cast A), (cast B)) -> (cast (or A, B))
5311   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5312     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5313       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
5314         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5315             !isa<ICmpInst>(Op1C->getOperand(0))) {
5316           const Type *SrcTy = Op0C->getOperand(0)->getType();
5317           if (SrcTy == Op1C->getOperand(0)->getType() &&
5318               SrcTy->isIntOrIntVector() &&
5319               // Only do this if the casts both really cause code to be
5320               // generated.
5321               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5322                                 I.getType(), TD) &&
5323               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5324                                 I.getType(), TD)) {
5325             Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5326                                              Op1C->getOperand(0), I.getName());
5327             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5328           }
5329         }
5330       }
5331   }
5332   
5333     
5334   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
5335   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
5336     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5337       if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5338         return Res;
5339   }
5340
5341   return Changed ? &I : 0;
5342 }
5343
5344 namespace {
5345
5346 // XorSelf - Implements: X ^ X --> 0
5347 struct XorSelf {
5348   Value *RHS;
5349   XorSelf(Value *rhs) : RHS(rhs) {}
5350   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5351   Instruction *apply(BinaryOperator &Xor) const {
5352     return &Xor;
5353   }
5354 };
5355
5356 }
5357
5358 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5359   bool Changed = SimplifyCommutative(I);
5360   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5361
5362   if (isa<UndefValue>(Op1)) {
5363     if (isa<UndefValue>(Op0))
5364       // Handle undef ^ undef -> 0 special case. This is a common
5365       // idiom (misuse).
5366       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5367     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5368   }
5369
5370   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5371   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
5372     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5373     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5374   }
5375   
5376   // See if we can simplify any instructions used by the instruction whose sole 
5377   // purpose is to compute bits we don't care about.
5378   if (SimplifyDemandedInstructionBits(I))
5379     return &I;
5380   if (isa<VectorType>(I.getType()))
5381     if (isa<ConstantAggregateZero>(Op1))
5382       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5383
5384   // Is this a ~ operation?
5385   if (Value *NotOp = dyn_castNotVal(&I)) {
5386     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5387       if (Op0I->getOpcode() == Instruction::And || 
5388           Op0I->getOpcode() == Instruction::Or) {
5389         // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5390         // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5391         if (dyn_castNotVal(Op0I->getOperand(1)))
5392           Op0I->swapOperands();
5393         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5394           Value *NotY =
5395             Builder->CreateNot(Op0I->getOperand(1),
5396                                Op0I->getOperand(1)->getName()+".not");
5397           if (Op0I->getOpcode() == Instruction::And)
5398             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5399           return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5400         }
5401         
5402         // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5403         // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5404         if (isFreeToInvert(Op0I->getOperand(0)) && 
5405             isFreeToInvert(Op0I->getOperand(1))) {
5406           Value *NotX =
5407             Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5408           Value *NotY =
5409             Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5410           if (Op0I->getOpcode() == Instruction::And)
5411             return BinaryOperator::CreateOr(NotX, NotY);
5412           return BinaryOperator::CreateAnd(NotX, NotY);
5413         }
5414       }
5415     }
5416   }
5417   
5418   
5419   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5420     if (RHS->isOne() && Op0->hasOneUse()) {
5421       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5422       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5423         return new ICmpInst(ICI->getInversePredicate(),
5424                             ICI->getOperand(0), ICI->getOperand(1));
5425
5426       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5427         return new FCmpInst(FCI->getInversePredicate(),
5428                             FCI->getOperand(0), FCI->getOperand(1));
5429     }
5430
5431     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5432     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5433       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5434         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5435           Instruction::CastOps Opcode = Op0C->getOpcode();
5436           if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5437               (RHS == ConstantExpr::getCast(Opcode, 
5438                                             ConstantInt::getTrue(*Context),
5439                                             Op0C->getDestTy()))) {
5440             CI->setPredicate(CI->getInversePredicate());
5441             return CastInst::Create(Opcode, CI, Op0C->getType());
5442           }
5443         }
5444       }
5445     }
5446
5447     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5448       // ~(c-X) == X-c-1 == X+(-c-1)
5449       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5450         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5451           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5452           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5453                                       ConstantInt::get(I.getType(), 1));
5454           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5455         }
5456           
5457       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5458         if (Op0I->getOpcode() == Instruction::Add) {
5459           // ~(X-c) --> (-c-1)-X
5460           if (RHS->isAllOnesValue()) {
5461             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5462             return BinaryOperator::CreateSub(
5463                            ConstantExpr::getSub(NegOp0CI,
5464                                       ConstantInt::get(I.getType(), 1)),
5465                                       Op0I->getOperand(0));
5466           } else if (RHS->getValue().isSignBit()) {
5467             // (X + C) ^ signbit -> (X + C + signbit)
5468             Constant *C = ConstantInt::get(*Context,
5469                                            RHS->getValue() + Op0CI->getValue());
5470             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5471
5472           }
5473         } else if (Op0I->getOpcode() == Instruction::Or) {
5474           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5475           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5476             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5477             // Anything in both C1 and C2 is known to be zero, remove it from
5478             // NewRHS.
5479             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5480             NewRHS = ConstantExpr::getAnd(NewRHS, 
5481                                        ConstantExpr::getNot(CommonBits));
5482             Worklist.Add(Op0I);
5483             I.setOperand(0, Op0I->getOperand(0));
5484             I.setOperand(1, NewRHS);
5485             return &I;
5486           }
5487         }
5488       }
5489     }
5490
5491     // Try to fold constant and into select arguments.
5492     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5493       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5494         return R;
5495     if (isa<PHINode>(Op0))
5496       if (Instruction *NV = FoldOpIntoPhi(I))
5497         return NV;
5498   }
5499
5500   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5501     if (X == Op1)
5502       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5503
5504   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5505     if (X == Op0)
5506       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5507
5508   
5509   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5510   if (Op1I) {
5511     Value *A, *B;
5512     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5513       if (A == Op0) {              // B^(B|A) == (A|B)^B
5514         Op1I->swapOperands();
5515         I.swapOperands();
5516         std::swap(Op0, Op1);
5517       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5518         I.swapOperands();     // Simplified below.
5519         std::swap(Op0, Op1);
5520       }
5521     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5522       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5523     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5524       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5525     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && 
5526                Op1I->hasOneUse()){
5527       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5528         Op1I->swapOperands();
5529         std::swap(A, B);
5530       }
5531       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5532         I.swapOperands();     // Simplified below.
5533         std::swap(Op0, Op1);
5534       }
5535     }
5536   }
5537   
5538   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5539   if (Op0I) {
5540     Value *A, *B;
5541     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5542         Op0I->hasOneUse()) {
5543       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5544         std::swap(A, B);
5545       if (B == Op1)                                  // (A|B)^B == A & ~B
5546         return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
5547     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5548       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5549     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5550       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5551     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && 
5552                Op0I->hasOneUse()){
5553       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5554         std::swap(A, B);
5555       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5556           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5557         return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
5558       }
5559     }
5560   }
5561   
5562   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5563   if (Op0I && Op1I && Op0I->isShift() && 
5564       Op0I->getOpcode() == Op1I->getOpcode() && 
5565       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5566       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5567     Value *NewOp =
5568       Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5569                          Op0I->getName());
5570     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5571                                   Op1I->getOperand(1));
5572   }
5573     
5574   if (Op0I && Op1I) {
5575     Value *A, *B, *C, *D;
5576     // (A & B)^(A | B) -> A ^ B
5577     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5578         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5579       if ((A == C && B == D) || (A == D && B == C)) 
5580         return BinaryOperator::CreateXor(A, B);
5581     }
5582     // (A | B)^(A & B) -> A ^ B
5583     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5584         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5585       if ((A == C && B == D) || (A == D && B == C)) 
5586         return BinaryOperator::CreateXor(A, B);
5587     }
5588     
5589     // (A & B)^(C & D)
5590     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5591         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5592         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5593       // (X & Y)^(X & Y) -> (Y^Z) & X
5594       Value *X = 0, *Y = 0, *Z = 0;
5595       if (A == C)
5596         X = A, Y = B, Z = D;
5597       else if (A == D)
5598         X = A, Y = B, Z = C;
5599       else if (B == C)
5600         X = B, Y = A, Z = D;
5601       else if (B == D)
5602         X = B, Y = A, Z = C;
5603       
5604       if (X) {
5605         Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
5606         return BinaryOperator::CreateAnd(NewOp, X);
5607       }
5608     }
5609   }
5610     
5611   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5612   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5613     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5614       return R;
5615
5616   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5617   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5618     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5619       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5620         const Type *SrcTy = Op0C->getOperand(0)->getType();
5621         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5622             // Only do this if the casts both really cause code to be generated.
5623             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5624                               I.getType(), TD) &&
5625             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5626                               I.getType(), TD)) {
5627           Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5628                                             Op1C->getOperand(0), I.getName());
5629           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5630         }
5631       }
5632   }
5633
5634   return Changed ? &I : 0;
5635 }
5636
5637 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5638                                    LLVMContext *Context) {
5639   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5640 }
5641
5642 static bool HasAddOverflow(ConstantInt *Result,
5643                            ConstantInt *In1, ConstantInt *In2,
5644                            bool IsSigned) {
5645   if (IsSigned)
5646     if (In2->getValue().isNegative())
5647       return Result->getValue().sgt(In1->getValue());
5648     else
5649       return Result->getValue().slt(In1->getValue());
5650   else
5651     return Result->getValue().ult(In1->getValue());
5652 }
5653
5654 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5655 /// overflowed for this type.
5656 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5657                             Constant *In2, LLVMContext *Context,
5658                             bool IsSigned = false) {
5659   Result = ConstantExpr::getAdd(In1, In2);
5660
5661   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5662     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5663       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5664       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5665                          ExtractElement(In1, Idx, Context),
5666                          ExtractElement(In2, Idx, Context),
5667                          IsSigned))
5668         return true;
5669     }
5670     return false;
5671   }
5672
5673   return HasAddOverflow(cast<ConstantInt>(Result),
5674                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5675                         IsSigned);
5676 }
5677
5678 static bool HasSubOverflow(ConstantInt *Result,
5679                            ConstantInt *In1, ConstantInt *In2,
5680                            bool IsSigned) {
5681   if (IsSigned)
5682     if (In2->getValue().isNegative())
5683       return Result->getValue().slt(In1->getValue());
5684     else
5685       return Result->getValue().sgt(In1->getValue());
5686   else
5687     return Result->getValue().ugt(In1->getValue());
5688 }
5689
5690 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5691 /// overflowed for this type.
5692 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5693                             Constant *In2, LLVMContext *Context,
5694                             bool IsSigned = false) {
5695   Result = ConstantExpr::getSub(In1, In2);
5696
5697   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5698     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5699       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5700       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5701                          ExtractElement(In1, Idx, Context),
5702                          ExtractElement(In2, Idx, Context),
5703                          IsSigned))
5704         return true;
5705     }
5706     return false;
5707   }
5708
5709   return HasSubOverflow(cast<ConstantInt>(Result),
5710                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5711                         IsSigned);
5712 }
5713
5714
5715 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5716 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5717 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5718                                        ICmpInst::Predicate Cond,
5719                                        Instruction &I) {
5720   // Look through bitcasts.
5721   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5722     RHS = BCI->getOperand(0);
5723
5724   Value *PtrBase = GEPLHS->getOperand(0);
5725   if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5726     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5727     // This transformation (ignoring the base and scales) is valid because we
5728     // know pointers can't overflow since the gep is inbounds.  See if we can
5729     // output an optimized form.
5730     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5731     
5732     // If not, synthesize the offset the hard way.
5733     if (Offset == 0)
5734       Offset = EmitGEPOffset(GEPLHS, *this);
5735     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5736                         Constant::getNullValue(Offset->getType()));
5737   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5738     // If the base pointers are different, but the indices are the same, just
5739     // compare the base pointer.
5740     if (PtrBase != GEPRHS->getOperand(0)) {
5741       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5742       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5743                         GEPRHS->getOperand(0)->getType();
5744       if (IndicesTheSame)
5745         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5746           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5747             IndicesTheSame = false;
5748             break;
5749           }
5750
5751       // If all indices are the same, just compare the base pointers.
5752       if (IndicesTheSame)
5753         return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5754                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5755
5756       // Otherwise, the base pointers are different and the indices are
5757       // different, bail out.
5758       return 0;
5759     }
5760
5761     // If one of the GEPs has all zero indices, recurse.
5762     bool AllZeros = true;
5763     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5764       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5765           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5766         AllZeros = false;
5767         break;
5768       }
5769     if (AllZeros)
5770       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5771                           ICmpInst::getSwappedPredicate(Cond), I);
5772
5773     // If the other GEP has all zero indices, recurse.
5774     AllZeros = true;
5775     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5776       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5777           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5778         AllZeros = false;
5779         break;
5780       }
5781     if (AllZeros)
5782       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5783
5784     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5785       // If the GEPs only differ by one index, compare it.
5786       unsigned NumDifferences = 0;  // Keep track of # differences.
5787       unsigned DiffOperand = 0;     // The operand that differs.
5788       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5789         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5790           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5791                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5792             // Irreconcilable differences.
5793             NumDifferences = 2;
5794             break;
5795           } else {
5796             if (NumDifferences++) break;
5797             DiffOperand = i;
5798           }
5799         }
5800
5801       if (NumDifferences == 0)   // SAME GEP?
5802         return ReplaceInstUsesWith(I, // No comparison is needed here.
5803                                    ConstantInt::get(Type::getInt1Ty(*Context),
5804                                              ICmpInst::isTrueWhenEqual(Cond)));
5805
5806       else if (NumDifferences == 1) {
5807         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5808         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5809         // Make sure we do a signed comparison here.
5810         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5811       }
5812     }
5813
5814     // Only lower this if the icmp is the only user of the GEP or if we expect
5815     // the result to fold to a constant!
5816     if (TD &&
5817         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5818         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5819       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5820       Value *L = EmitGEPOffset(GEPLHS, *this);
5821       Value *R = EmitGEPOffset(GEPRHS, *this);
5822       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5823     }
5824   }
5825   return 0;
5826 }
5827
5828 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5829 ///
5830 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5831                                                 Instruction *LHSI,
5832                                                 Constant *RHSC) {
5833   if (!isa<ConstantFP>(RHSC)) return 0;
5834   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5835   
5836   // Get the width of the mantissa.  We don't want to hack on conversions that
5837   // might lose information from the integer, e.g. "i64 -> float"
5838   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5839   if (MantissaWidth == -1) return 0;  // Unknown.
5840   
5841   // Check to see that the input is converted from an integer type that is small
5842   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5843   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5844   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5845   
5846   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5847   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5848   if (LHSUnsigned)
5849     ++InputSize;
5850   
5851   // If the conversion would lose info, don't hack on this.
5852   if ((int)InputSize > MantissaWidth)
5853     return 0;
5854   
5855   // Otherwise, we can potentially simplify the comparison.  We know that it
5856   // will always come through as an integer value and we know the constant is
5857   // not a NAN (it would have been previously simplified).
5858   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5859   
5860   ICmpInst::Predicate Pred;
5861   switch (I.getPredicate()) {
5862   default: llvm_unreachable("Unexpected predicate!");
5863   case FCmpInst::FCMP_UEQ:
5864   case FCmpInst::FCMP_OEQ:
5865     Pred = ICmpInst::ICMP_EQ;
5866     break;
5867   case FCmpInst::FCMP_UGT:
5868   case FCmpInst::FCMP_OGT:
5869     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5870     break;
5871   case FCmpInst::FCMP_UGE:
5872   case FCmpInst::FCMP_OGE:
5873     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5874     break;
5875   case FCmpInst::FCMP_ULT:
5876   case FCmpInst::FCMP_OLT:
5877     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5878     break;
5879   case FCmpInst::FCMP_ULE:
5880   case FCmpInst::FCMP_OLE:
5881     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5882     break;
5883   case FCmpInst::FCMP_UNE:
5884   case FCmpInst::FCMP_ONE:
5885     Pred = ICmpInst::ICMP_NE;
5886     break;
5887   case FCmpInst::FCMP_ORD:
5888     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5889   case FCmpInst::FCMP_UNO:
5890     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5891   }
5892   
5893   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5894   
5895   // Now we know that the APFloat is a normal number, zero or inf.
5896   
5897   // See if the FP constant is too large for the integer.  For example,
5898   // comparing an i8 to 300.0.
5899   unsigned IntWidth = IntTy->getScalarSizeInBits();
5900   
5901   if (!LHSUnsigned) {
5902     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5903     // and large values.
5904     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5905     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5906                           APFloat::rmNearestTiesToEven);
5907     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5908       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5909           Pred == ICmpInst::ICMP_SLE)
5910         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5911       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5912     }
5913   } else {
5914     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5915     // +INF and large values.
5916     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5917     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5918                           APFloat::rmNearestTiesToEven);
5919     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5920       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5921           Pred == ICmpInst::ICMP_ULE)
5922         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5923       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5924     }
5925   }
5926   
5927   if (!LHSUnsigned) {
5928     // See if the RHS value is < SignedMin.
5929     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5930     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5931                           APFloat::rmNearestTiesToEven);
5932     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5933       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5934           Pred == ICmpInst::ICMP_SGE)
5935         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5936       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5937     }
5938   }
5939
5940   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5941   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5942   // casting the FP value to the integer value and back, checking for equality.
5943   // Don't do this for zero, because -0.0 is not fractional.
5944   Constant *RHSInt = LHSUnsigned
5945     ? ConstantExpr::getFPToUI(RHSC, IntTy)
5946     : ConstantExpr::getFPToSI(RHSC, IntTy);
5947   if (!RHS.isZero()) {
5948     bool Equal = LHSUnsigned
5949       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5950       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5951     if (!Equal) {
5952       // If we had a comparison against a fractional value, we have to adjust
5953       // the compare predicate and sometimes the value.  RHSC is rounded towards
5954       // zero at this point.
5955       switch (Pred) {
5956       default: llvm_unreachable("Unexpected integer comparison!");
5957       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5958         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5959       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5960         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5961       case ICmpInst::ICMP_ULE:
5962         // (float)int <= 4.4   --> int <= 4
5963         // (float)int <= -4.4  --> false
5964         if (RHS.isNegative())
5965           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5966         break;
5967       case ICmpInst::ICMP_SLE:
5968         // (float)int <= 4.4   --> int <= 4
5969         // (float)int <= -4.4  --> int < -4
5970         if (RHS.isNegative())
5971           Pred = ICmpInst::ICMP_SLT;
5972         break;
5973       case ICmpInst::ICMP_ULT:
5974         // (float)int < -4.4   --> false
5975         // (float)int < 4.4    --> int <= 4
5976         if (RHS.isNegative())
5977           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5978         Pred = ICmpInst::ICMP_ULE;
5979         break;
5980       case ICmpInst::ICMP_SLT:
5981         // (float)int < -4.4   --> int < -4
5982         // (float)int < 4.4    --> int <= 4
5983         if (!RHS.isNegative())
5984           Pred = ICmpInst::ICMP_SLE;
5985         break;
5986       case ICmpInst::ICMP_UGT:
5987         // (float)int > 4.4    --> int > 4
5988         // (float)int > -4.4   --> true
5989         if (RHS.isNegative())
5990           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5991         break;
5992       case ICmpInst::ICMP_SGT:
5993         // (float)int > 4.4    --> int > 4
5994         // (float)int > -4.4   --> int >= -4
5995         if (RHS.isNegative())
5996           Pred = ICmpInst::ICMP_SGE;
5997         break;
5998       case ICmpInst::ICMP_UGE:
5999         // (float)int >= -4.4   --> true
6000         // (float)int >= 4.4    --> int > 4
6001         if (!RHS.isNegative())
6002           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6003         Pred = ICmpInst::ICMP_UGT;
6004         break;
6005       case ICmpInst::ICMP_SGE:
6006         // (float)int >= -4.4   --> int >= -4
6007         // (float)int >= 4.4    --> int > 4
6008         if (!RHS.isNegative())
6009           Pred = ICmpInst::ICMP_SGT;
6010         break;
6011       }
6012     }
6013   }
6014
6015   // Lower this FP comparison into an appropriate integer version of the
6016   // comparison.
6017   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
6018 }
6019
6020
6021 /// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
6022 ///   cmp pred (load (gep GV, ...)), cmpcst
6023 /// where GV is a global variable with a constant initializer.  Try to simplify
6024 /// this into one or two simpler comparisons that do not need the load.  For
6025 /// example, we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into
6026 /// "icmp eq i, 3".  We assume that eliminating a load is always goodness.
6027 Instruction *InstCombiner::
6028 FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
6029                              CmpInst &ICI) {
6030   
6031   // There are many forms of this optimization we can handle, for now, just do
6032   // the simple index into a single-dimensional array.
6033   //
6034   // Require: GEP GV, 0, i
6035   if (GEP->getNumOperands() != 3 ||
6036       !isa<ConstantInt>(GEP->getOperand(1)) ||
6037       !cast<ConstantInt>(GEP->getOperand(1))->isZero())
6038     return 0;
6039   
6040   ConstantArray *Init = dyn_cast<ConstantArray>(GV->getInitializer());
6041   if (Init == 0 || Init->getNumOperands() > 1024) return 0;
6042   
6043   
6044   // Variables for our state machines.
6045   
6046   // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
6047   // "i == 47 | i == 87", where 47 is the first index the condition is true for,
6048   // and 87 is the second (and last) index.  FirstTrueElement is -1 when
6049   // undefined, otherwise set to the first true element.  SecondTrueElement is
6050   // -1 when undefined, -2 when overdefined and >= 0 when that index is true.
6051   int FirstTrueElement = -1, SecondTrueElement = -1;
6052
6053   // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
6054   // form "i != 47 & i != 87".  Same state transitions as for true elements.
6055   int FirstFalseElement = -1, SecondFalseElement = -1;
6056   
6057   // MagicBitvector - This is a magic bitvector where we set a bit if the
6058   // comparison is true for element 'i'.  If there are 64 elements or less in
6059   // the array, this will fully represent all the comparison results.
6060   uint64_t MagicBitvector = 0;
6061   
6062   
6063   // Scan the array and see if one of our patterns matches.
6064   Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
6065   for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
6066     // Find out if the comparison would be true or false for the i'th element.
6067     Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(),
6068                                                   Init->getOperand(i),
6069                                                   CompareRHS, TD);
6070     // If the result is undef for this element, ignore it.
6071     if (isa<UndefValue>(C)) continue;
6072     
6073     // If we can't compute the result for any of the elements, we have to give
6074     // up evaluating the entire conditional.
6075     if (!isa<ConstantInt>(C)) return 0;
6076     
6077     // Otherwise, we know if the comparison is true or false for this element,
6078     // update our state machines.
6079     bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
6080     
6081     // State machine for single index comparison.
6082     if (IsTrueForElt) {
6083       // Update the TrueElement state machine.
6084       if (FirstTrueElement == -1)
6085         FirstTrueElement = i;
6086       else if (SecondTrueElement == -1)
6087         SecondTrueElement = i;
6088       else
6089         SecondTrueElement = -2;
6090     } else {
6091       // Update the FalseElement state machine.
6092       if (FirstFalseElement == -1)
6093         FirstFalseElement = i;
6094       else if (SecondFalseElement == -1)
6095         SecondFalseElement = i;
6096       else
6097         SecondFalseElement = -2;
6098     }
6099     
6100     // If this element is in range, update our magic bitvector.
6101     if (i < 64 && IsTrueForElt)
6102       MagicBitvector |= 1ULL << i;
6103     
6104     // If all of our states become overdefined, bail out early.
6105     if (i >= 64 && SecondTrueElement == -2 && SecondFalseElement == -2)
6106       return 0;
6107   }
6108
6109   // Now that we've scanned the entire array, emit our new comparison(s).  We
6110   // order the state machines in complexity of the generated code.
6111   Value *Idx = GEP->getOperand(2);
6112
6113   // If the comparison is only true for one or two elements, emit direct
6114   // comparisons.
6115   if (SecondTrueElement != -2) {
6116     // None true -> false.
6117     if (FirstTrueElement == -1)
6118       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6119     
6120     Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
6121     
6122     // True for one element -> 'i == 47'.
6123     if (SecondTrueElement == -1)
6124       return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
6125     
6126     // True for two elements -> 'i == 47 | i == 72'.
6127     Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
6128     Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
6129     Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
6130     return BinaryOperator::CreateOr(C1, C2);
6131   }
6132
6133   // If the comparison is only false for one or two elements, emit direct
6134   // comparisons.
6135   if (SecondFalseElement != -2) {
6136     // None false -> true.
6137     if (FirstFalseElement == -1)
6138       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6139     
6140     Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
6141
6142     // False for one element -> 'i != 47'.
6143     if (SecondFalseElement == -1)
6144       return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
6145      
6146     // False for two elements -> 'i != 47 & i != 72'.
6147     Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
6148     Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
6149     Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
6150     return BinaryOperator::CreateAnd(C1, C2);
6151   }
6152   
6153   // If a 32-bit or 64-bit magic bitvector captures the entire comparison state
6154   // of this load, replace it with computation that does:
6155   //   ((magic_cst >> i) & 1) != 0
6156   if (Init->getNumOperands() <= 32 ||
6157       (TD && Init->getNumOperands() <= 64 && TD->isLegalInteger(64))) {
6158     const Type *Ty;
6159     if (Init->getNumOperands() <= 32)
6160       Ty = Type::getInt32Ty(Init->getContext());
6161     else
6162       Ty = Type::getInt64Ty(Init->getContext());
6163     Value *V = Builder->CreateIntCast(Idx, Ty, false);
6164     V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
6165     V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
6166     return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
6167   }
6168   
6169   // TODO: Range check
6170   // TODO: GEP 0, i, 4
6171   return 0;
6172 }
6173
6174
6175 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
6176   bool Changed = false;
6177   
6178   /// Orders the operands of the compare so that they are listed from most
6179   /// complex to least complex.  This puts constants before unary operators,
6180   /// before binary operators.
6181   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6182     I.swapOperands();
6183     Changed = true;
6184   }
6185
6186   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6187   
6188   if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
6189     return ReplaceInstUsesWith(I, V);
6190
6191   // Simplify 'fcmp pred X, X'
6192   if (Op0 == Op1) {
6193     switch (I.getPredicate()) {
6194     default: llvm_unreachable("Unknown predicate!");
6195     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
6196     case FCmpInst::FCMP_ULT:    // True if unordered or less than
6197     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
6198     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
6199       // Canonicalize these to be 'fcmp uno %X, 0.0'.
6200       I.setPredicate(FCmpInst::FCMP_UNO);
6201       I.setOperand(1, Constant::getNullValue(Op0->getType()));
6202       return &I;
6203       
6204     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
6205     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
6206     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
6207     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
6208       // Canonicalize these to be 'fcmp ord %X, 0.0'.
6209       I.setPredicate(FCmpInst::FCMP_ORD);
6210       I.setOperand(1, Constant::getNullValue(Op0->getType()));
6211       return &I;
6212     }
6213   }
6214     
6215   // Handle fcmp with constant RHS
6216   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6217     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6218       switch (LHSI->getOpcode()) {
6219       case Instruction::PHI:
6220         // Only fold fcmp into the PHI if the phi and fcmp are in the same
6221         // block.  If in the same block, we're encouraging jump threading.  If
6222         // not, we are just pessimizing the code by making an i1 phi.
6223         if (LHSI->getParent() == I.getParent())
6224           if (Instruction *NV = FoldOpIntoPhi(I, true))
6225             return NV;
6226         break;
6227       case Instruction::SIToFP:
6228       case Instruction::UIToFP:
6229         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
6230           return NV;
6231         break;
6232       case Instruction::Select: {
6233         // If either operand of the select is a constant, we can fold the
6234         // comparison into the select arms, which will cause one to be
6235         // constant folded and the select turned into a bitwise or.
6236         Value *Op1 = 0, *Op2 = 0;
6237         if (LHSI->hasOneUse()) {
6238           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6239             // Fold the known value into the constant operand.
6240             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
6241             // Insert a new FCmp of the other select operand.
6242             Op2 = Builder->CreateFCmp(I.getPredicate(),
6243                                       LHSI->getOperand(2), RHSC, I.getName());
6244           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6245             // Fold the known value into the constant operand.
6246             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
6247             // Insert a new FCmp of the other select operand.
6248             Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
6249                                       RHSC, I.getName());
6250           }
6251         }
6252
6253         if (Op1)
6254           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6255         break;
6256       }
6257     case Instruction::Load:
6258       if (GetElementPtrInst *GEP =
6259           dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
6260         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
6261           if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
6262               !cast<LoadInst>(LHSI)->isVolatile())
6263             if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
6264               return Res;
6265             //errs() << "NOT HANDLED: " << *GV << "\n";
6266             //errs() << "\t" << *GEP << "\n";
6267             //errs() << "\t " << I << "\n\n\n";
6268       }
6269       break;
6270     }
6271   }
6272
6273   return Changed ? &I : 0;
6274 }
6275
6276 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
6277   bool Changed = false;
6278   
6279   /// Orders the operands of the compare so that they are listed from most
6280   /// complex to least complex.  This puts constants before unary operators,
6281   /// before binary operators.
6282   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6283     I.swapOperands();
6284     Changed = true;
6285   }
6286   
6287   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6288   
6289   if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
6290     return ReplaceInstUsesWith(I, V);
6291   
6292   const Type *Ty = Op0->getType();
6293
6294   // icmp's with boolean values can always be turned into bitwise operations
6295   if (Ty == Type::getInt1Ty(*Context)) {
6296     switch (I.getPredicate()) {
6297     default: llvm_unreachable("Invalid icmp instruction!");
6298     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
6299       Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
6300       return BinaryOperator::CreateNot(Xor);
6301     }
6302     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
6303       return BinaryOperator::CreateXor(Op0, Op1);
6304
6305     case ICmpInst::ICMP_UGT:
6306       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
6307       // FALL THROUGH
6308     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
6309       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
6310       return BinaryOperator::CreateAnd(Not, Op1);
6311     }
6312     case ICmpInst::ICMP_SGT:
6313       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
6314       // FALL THROUGH
6315     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
6316       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
6317       return BinaryOperator::CreateAnd(Not, Op0);
6318     }
6319     case ICmpInst::ICMP_UGE:
6320       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6321       // FALL THROUGH
6322     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6323       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
6324       return BinaryOperator::CreateOr(Not, Op1);
6325     }
6326     case ICmpInst::ICMP_SGE:
6327       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6328       // FALL THROUGH
6329     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6330       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
6331       return BinaryOperator::CreateOr(Not, Op0);
6332     }
6333     }
6334   }
6335
6336   unsigned BitWidth = 0;
6337   if (TD)
6338     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6339   else if (Ty->isIntOrIntVector())
6340     BitWidth = Ty->getScalarSizeInBits();
6341
6342   bool isSignBit = false;
6343
6344   // See if we are doing a comparison with a constant.
6345   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6346     Value *A = 0, *B = 0;
6347     
6348     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6349     if (I.isEquality() && CI->isZero() &&
6350         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
6351       // (icmp cond A B) if cond is equality
6352       return new ICmpInst(I.getPredicate(), A, B);
6353     }
6354     
6355     // If we have an icmp le or icmp ge instruction, turn it into the
6356     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6357     // them being folded in the code below.  The SimplifyICmpInst code has
6358     // already handled the edge cases for us, so we just assert on them.
6359     switch (I.getPredicate()) {
6360     default: break;
6361     case ICmpInst::ICMP_ULE:
6362       assert(!CI->isMaxValue(false));                 // A <=u MAX -> TRUE
6363       return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
6364                           AddOne(CI));
6365     case ICmpInst::ICMP_SLE:
6366       assert(!CI->isMaxValue(true));                  // A <=s MAX -> TRUE
6367       return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6368                           AddOne(CI));
6369     case ICmpInst::ICMP_UGE:
6370       assert(!CI->isMinValue(false));                  // A >=u MIN -> TRUE
6371       return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
6372                           SubOne(CI));
6373     case ICmpInst::ICMP_SGE:
6374       assert(!CI->isMinValue(true));                   // A >=s MIN -> TRUE
6375       return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6376                           SubOne(CI));
6377     }
6378     
6379     // If this comparison is a normal comparison, it demands all
6380     // bits, if it is a sign bit comparison, it only demands the sign bit.
6381     bool UnusedBit;
6382     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6383   }
6384
6385   // See if we can fold the comparison based on range information we can get
6386   // by checking whether bits are known to be zero or one in the input.
6387   if (BitWidth != 0) {
6388     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6389     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6390
6391     if (SimplifyDemandedBits(I.getOperandUse(0),
6392                              isSignBit ? APInt::getSignBit(BitWidth)
6393                                        : APInt::getAllOnesValue(BitWidth),
6394                              Op0KnownZero, Op0KnownOne, 0))
6395       return &I;
6396     if (SimplifyDemandedBits(I.getOperandUse(1),
6397                              APInt::getAllOnesValue(BitWidth),
6398                              Op1KnownZero, Op1KnownOne, 0))
6399       return &I;
6400
6401     // Given the known and unknown bits, compute a range that the LHS could be
6402     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6403     // EQ and NE we use unsigned values.
6404     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6405     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6406     if (I.isSigned()) {
6407       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6408                                              Op0Min, Op0Max);
6409       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6410                                              Op1Min, Op1Max);
6411     } else {
6412       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6413                                                Op0Min, Op0Max);
6414       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6415                                                Op1Min, Op1Max);
6416     }
6417
6418     // If Min and Max are known to be the same, then SimplifyDemandedBits
6419     // figured out that the LHS is a constant.  Just constant fold this now so
6420     // that code below can assume that Min != Max.
6421     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6422       return new ICmpInst(I.getPredicate(),
6423                           ConstantInt::get(*Context, Op0Min), Op1);
6424     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6425       return new ICmpInst(I.getPredicate(), Op0,
6426                           ConstantInt::get(*Context, Op1Min));
6427
6428     // Based on the range information we know about the LHS, see if we can
6429     // simplify this comparison.  For example, (x&4) < 8  is always true.
6430     switch (I.getPredicate()) {
6431     default: llvm_unreachable("Unknown icmp opcode!");
6432     case ICmpInst::ICMP_EQ:
6433       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6434         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6435       break;
6436     case ICmpInst::ICMP_NE:
6437       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6438         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6439       break;
6440     case ICmpInst::ICMP_ULT:
6441       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6442         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6443       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6444         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6445       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6446         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6447       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6448         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6449           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6450                               SubOne(CI));
6451
6452         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6453         if (CI->isMinValue(true))
6454           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6455                            Constant::getAllOnesValue(Op0->getType()));
6456       }
6457       break;
6458     case ICmpInst::ICMP_UGT:
6459       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6460         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6461       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6462         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6463
6464       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6465         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6466       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6467         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6468           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6469                               AddOne(CI));
6470
6471         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6472         if (CI->isMaxValue(true))
6473           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6474                               Constant::getNullValue(Op0->getType()));
6475       }
6476       break;
6477     case ICmpInst::ICMP_SLT:
6478       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6479         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6480       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6481         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6482       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6483         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6484       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6485         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6486           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6487                               SubOne(CI));
6488       }
6489       break;
6490     case ICmpInst::ICMP_SGT:
6491       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6492         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6493       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6494         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6495
6496       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6497         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6498       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6499         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6500           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6501                               AddOne(CI));
6502       }
6503       break;
6504     case ICmpInst::ICMP_SGE:
6505       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6506       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6507         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6508       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6509         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6510       break;
6511     case ICmpInst::ICMP_SLE:
6512       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6513       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6514         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6515       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6516         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6517       break;
6518     case ICmpInst::ICMP_UGE:
6519       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6520       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6521         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6522       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6523         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6524       break;
6525     case ICmpInst::ICMP_ULE:
6526       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6527       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6528         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6529       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6530         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6531       break;
6532     }
6533
6534     // Turn a signed comparison into an unsigned one if both operands
6535     // are known to have the same sign.
6536     if (I.isSigned() &&
6537         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6538          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6539       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6540   }
6541
6542   // Test if the ICmpInst instruction is used exclusively by a select as
6543   // part of a minimum or maximum operation. If so, refrain from doing
6544   // any other folding. This helps out other analyses which understand
6545   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6546   // and CodeGen. And in this case, at least one of the comparison
6547   // operands has at least one user besides the compare (the select),
6548   // which would often largely negate the benefit of folding anyway.
6549   if (I.hasOneUse())
6550     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6551       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6552           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6553         return 0;
6554
6555   // See if we are doing a comparison between a constant and an instruction that
6556   // can be folded into the comparison.
6557   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6558     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6559     // instruction, see if that instruction also has constants so that the 
6560     // instruction can be folded into the icmp 
6561     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6562       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6563         return Res;
6564   }
6565
6566   // Handle icmp with constant (but not simple integer constant) RHS
6567   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6568     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6569       switch (LHSI->getOpcode()) {
6570       case Instruction::GetElementPtr:
6571           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6572         if (RHSC->isNullValue() &&
6573             cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
6574           return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6575                   Constant::getNullValue(LHSI->getOperand(0)->getType()));
6576         break;
6577       case Instruction::PHI:
6578         // Only fold icmp into the PHI if the phi and icmp are in the same
6579         // block.  If in the same block, we're encouraging jump threading.  If
6580         // not, we are just pessimizing the code by making an i1 phi.
6581         if (LHSI->getParent() == I.getParent())
6582           if (Instruction *NV = FoldOpIntoPhi(I, true))
6583             return NV;
6584         break;
6585       case Instruction::Select: {
6586         // If either operand of the select is a constant, we can fold the
6587         // comparison into the select arms, which will cause one to be
6588         // constant folded and the select turned into a bitwise or.
6589         Value *Op1 = 0, *Op2 = 0;
6590         if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
6591           Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6592         if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
6593           Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6594
6595         // We only want to perform this transformation if it will not lead to
6596         // additional code. This is true if either both sides of the select
6597         // fold to a constant (in which case the icmp is replaced with a select
6598         // which will usually simplify) or this is the only user of the
6599         // select (in which case we are trading a select+icmp for a simpler
6600         // select+icmp).
6601         if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
6602           if (!Op1)
6603             Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6604                                       RHSC, I.getName());
6605           if (!Op2)
6606             Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6607                                       RHSC, I.getName());
6608           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6609         }
6610         break;
6611       }
6612       case Instruction::Call:
6613         // If we have (malloc != null), and if the malloc has a single use, we
6614         // can assume it is successful and remove the malloc.
6615         if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6616             isa<ConstantPointerNull>(RHSC)) {
6617           // Need to explicitly erase malloc call here, instead of adding it to
6618           // Worklist, because it won't get DCE'd from the Worklist since
6619           // isInstructionTriviallyDead() returns false for function calls.
6620           // It is OK to replace LHSI/MallocCall with Undef because the 
6621           // instruction that uses it will be erased via Worklist.
6622           if (extractMallocCall(LHSI)) {
6623             LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6624             EraseInstFromFunction(*LHSI);
6625             return ReplaceInstUsesWith(I,
6626                                      ConstantInt::get(Type::getInt1Ty(*Context),
6627                                                       !I.isTrueWhenEqual()));
6628           }
6629           if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6630             if (MallocCall->hasOneUse()) {
6631               MallocCall->replaceAllUsesWith(
6632                                         UndefValue::get(MallocCall->getType()));
6633               EraseInstFromFunction(*MallocCall);
6634               Worklist.Add(LHSI); // The malloc's bitcast use.
6635               return ReplaceInstUsesWith(I,
6636                                      ConstantInt::get(Type::getInt1Ty(*Context),
6637                                                       !I.isTrueWhenEqual()));
6638             }
6639         }
6640         break;
6641       case Instruction::IntToPtr:
6642         // icmp pred inttoptr(X), null -> icmp pred X, 0
6643         if (RHSC->isNullValue() && TD &&
6644             TD->getIntPtrType(RHSC->getContext()) == 
6645                LHSI->getOperand(0)->getType())
6646           return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6647                         Constant::getNullValue(LHSI->getOperand(0)->getType()));
6648         break;
6649
6650       case Instruction::Load:
6651         if (GetElementPtrInst *GEP =
6652               dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
6653           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
6654             if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
6655                 !cast<LoadInst>(LHSI)->isVolatile())
6656               if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
6657                 return Res;
6658           //errs() << "NOT HANDLED: " << *GV << "\n";
6659           //errs() << "\t" << *GEP << "\n";
6660           //errs() << "\t " << I << "\n\n\n";
6661         }
6662         break;
6663       }
6664   }
6665
6666   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6667   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6668     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6669       return NI;
6670   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6671     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6672                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6673       return NI;
6674
6675   // Test to see if the operands of the icmp are casted versions of other
6676   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6677   // now.
6678   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6679     if (isa<PointerType>(Op0->getType()) && 
6680         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6681       // We keep moving the cast from the left operand over to the right
6682       // operand, where it can often be eliminated completely.
6683       Op0 = CI->getOperand(0);
6684
6685       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6686       // so eliminate it as well.
6687       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6688         Op1 = CI2->getOperand(0);
6689
6690       // If Op1 is a constant, we can fold the cast into the constant.
6691       if (Op0->getType() != Op1->getType()) {
6692         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6693           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6694         } else {
6695           // Otherwise, cast the RHS right before the icmp
6696           Op1 = Builder->CreateBitCast(Op1, Op0->getType());
6697         }
6698       }
6699       return new ICmpInst(I.getPredicate(), Op0, Op1);
6700     }
6701   }
6702   
6703   if (isa<CastInst>(Op0)) {
6704     // Handle the special case of: icmp (cast bool to X), <cst>
6705     // This comes up when you have code like
6706     //   int X = A < B;
6707     //   if (X) ...
6708     // For generality, we handle any zero-extension of any operand comparison
6709     // with a constant or another cast from the same type.
6710     if (isa<Constant>(Op1) || isa<CastInst>(Op1))
6711       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6712         return R;
6713   }
6714   
6715   // See if it's the same type of instruction on the left and right.
6716   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6717     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6718       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6719           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6720         switch (Op0I->getOpcode()) {
6721         default: break;
6722         case Instruction::Add:
6723         case Instruction::Sub:
6724         case Instruction::Xor:
6725           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6726             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6727                                 Op1I->getOperand(0));
6728           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6729           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6730             if (CI->getValue().isSignBit()) {
6731               ICmpInst::Predicate Pred = I.isSigned()
6732                                              ? I.getUnsignedPredicate()
6733                                              : I.getSignedPredicate();
6734               return new ICmpInst(Pred, Op0I->getOperand(0),
6735                                   Op1I->getOperand(0));
6736             }
6737             
6738             if (CI->getValue().isMaxSignedValue()) {
6739               ICmpInst::Predicate Pred = I.isSigned()
6740                                              ? I.getUnsignedPredicate()
6741                                              : I.getSignedPredicate();
6742               Pred = I.getSwappedPredicate(Pred);
6743               return new ICmpInst(Pred, Op0I->getOperand(0),
6744                                   Op1I->getOperand(0));
6745             }
6746           }
6747           break;
6748         case Instruction::Mul:
6749           if (!I.isEquality())
6750             break;
6751
6752           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6753             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6754             // Mask = -1 >> count-trailing-zeros(Cst).
6755             if (!CI->isZero() && !CI->isOne()) {
6756               const APInt &AP = CI->getValue();
6757               ConstantInt *Mask = ConstantInt::get(*Context, 
6758                                       APInt::getLowBitsSet(AP.getBitWidth(),
6759                                                            AP.getBitWidth() -
6760                                                       AP.countTrailingZeros()));
6761               Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6762               Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
6763               return new ICmpInst(I.getPredicate(), And1, And2);
6764             }
6765           }
6766           break;
6767         }
6768       }
6769     }
6770   }
6771   
6772   // ~x < ~y --> y < x
6773   { Value *A, *B;
6774     if (match(Op0, m_Not(m_Value(A))) &&
6775         match(Op1, m_Not(m_Value(B))))
6776       return new ICmpInst(I.getPredicate(), B, A);
6777   }
6778   
6779   if (I.isEquality()) {
6780     Value *A, *B, *C, *D;
6781     
6782     // -x == -y --> x == y
6783     if (match(Op0, m_Neg(m_Value(A))) &&
6784         match(Op1, m_Neg(m_Value(B))))
6785       return new ICmpInst(I.getPredicate(), A, B);
6786     
6787     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6788       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6789         Value *OtherVal = A == Op1 ? B : A;
6790         return new ICmpInst(I.getPredicate(), OtherVal,
6791                             Constant::getNullValue(A->getType()));
6792       }
6793
6794       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6795         // A^c1 == C^c2 --> A == C^(c1^c2)
6796         ConstantInt *C1, *C2;
6797         if (match(B, m_ConstantInt(C1)) &&
6798             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6799           Constant *NC = 
6800                    ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6801           Value *Xor = Builder->CreateXor(C, NC, "tmp");
6802           return new ICmpInst(I.getPredicate(), A, Xor);
6803         }
6804         
6805         // A^B == A^D -> B == D
6806         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6807         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6808         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6809         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6810       }
6811     }
6812     
6813     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6814         (A == Op0 || B == Op0)) {
6815       // A == (A^B)  ->  B == 0
6816       Value *OtherVal = A == Op0 ? B : A;
6817       return new ICmpInst(I.getPredicate(), OtherVal,
6818                           Constant::getNullValue(A->getType()));
6819     }
6820
6821     // (A-B) == A  ->  B == 0
6822     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6823       return new ICmpInst(I.getPredicate(), B, 
6824                           Constant::getNullValue(B->getType()));
6825
6826     // A == (A-B)  ->  B == 0
6827     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6828       return new ICmpInst(I.getPredicate(), B,
6829                           Constant::getNullValue(B->getType()));
6830     
6831     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6832     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6833         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6834         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6835       Value *X = 0, *Y = 0, *Z = 0;
6836       
6837       if (A == C) {
6838         X = B; Y = D; Z = A;
6839       } else if (A == D) {
6840         X = B; Y = C; Z = A;
6841       } else if (B == C) {
6842         X = A; Y = D; Z = B;
6843       } else if (B == D) {
6844         X = A; Y = C; Z = B;
6845       }
6846       
6847       if (X) {   // Build (X^Y) & Z
6848         Op1 = Builder->CreateXor(X, Y, "tmp");
6849         Op1 = Builder->CreateAnd(Op1, Z, "tmp");
6850         I.setOperand(0, Op1);
6851         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6852         return &I;
6853       }
6854     }
6855   }
6856   
6857   {
6858     Value *X; ConstantInt *Cst;
6859     // icmp X+Cst, X
6860     if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
6861       return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0);
6862
6863     // icmp X, X+Cst
6864     if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
6865       return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1);
6866   }
6867   return Changed ? &I : 0;
6868 }
6869
6870 /// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
6871 Instruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI,
6872                                             Value *X, ConstantInt *CI,
6873                                             ICmpInst::Predicate Pred,
6874                                             Value *TheAdd) {
6875   // If we have X+0, exit early (simplifying logic below) and let it get folded
6876   // elsewhere.   icmp X+0, X  -> icmp X, X
6877   if (CI->isZero()) {
6878     bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
6879     return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6880   }
6881   
6882   // (X+4) == X -> false.
6883   if (Pred == ICmpInst::ICMP_EQ)
6884     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
6885
6886   // (X+4) != X -> true.
6887   if (Pred == ICmpInst::ICMP_NE)
6888     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
6889
6890   // If this is an instruction (as opposed to constantexpr) get NUW/NSW info.
6891   bool isNUW = false, isNSW = false;
6892   if (BinaryOperator *Add = dyn_cast<BinaryOperator>(TheAdd)) {
6893     isNUW = Add->hasNoUnsignedWrap();
6894     isNSW = Add->hasNoSignedWrap();
6895   }      
6896   
6897   // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
6898   // so the values can never be equal.  Similiarly for all other "or equals"
6899   // operators.
6900   
6901   // (X+1) <u X        --> X >u (MAXUINT-1)        --> X != 255
6902   // (X+2) <u X        --> X >u (MAXUINT-2)        --> X > 253
6903   // (X+MAXUINT) <u X  --> X >u (MAXUINT-MAXUINT)  --> X != 0
6904   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
6905     // If this is an NUW add, then this is always false.
6906     if (isNUW)
6907       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext())); 
6908     
6909     Value *R = ConstantExpr::getSub(ConstantInt::get(CI->getType(), -1ULL), CI);
6910     return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
6911   }
6912   
6913   // (X+1) >u X        --> X <u (0-1)        --> X != 255
6914   // (X+2) >u X        --> X <u (0-2)        --> X <u 254
6915   // (X+MAXUINT) >u X  --> X <u (0-MAXUINT)  --> X <u 1  --> X == 0
6916   if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
6917     // If this is an NUW add, then this is always true.
6918     if (isNUW)
6919       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext())); 
6920     return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
6921   }
6922   
6923   unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
6924   ConstantInt *SMax = ConstantInt::get(X->getContext(),
6925                                        APInt::getSignedMaxValue(BitWidth));
6926
6927   // (X+ 1) <s X       --> X >s (MAXSINT-1)          --> X == 127
6928   // (X+ 2) <s X       --> X >s (MAXSINT-2)          --> X >s 125
6929   // (X+MAXSINT) <s X  --> X >s (MAXSINT-MAXSINT)    --> X >s 0
6930   // (X+MINSINT) <s X  --> X >s (MAXSINT-MINSINT)    --> X >s -1
6931   // (X+ -2) <s X      --> X >s (MAXSINT- -2)        --> X >s 126
6932   // (X+ -1) <s X      --> X >s (MAXSINT- -1)        --> X != 127
6933   if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
6934     // If this is an NSW add, then we have two cases: if the constant is
6935     // positive, then this is always false, if negative, this is always true.
6936     if (isNSW) {
6937       bool isTrue = CI->getValue().isNegative();
6938       return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6939     }
6940     
6941     return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
6942   }
6943   
6944   // (X+ 1) >s X       --> X <s (MAXSINT-(1-1))       --> X != 127
6945   // (X+ 2) >s X       --> X <s (MAXSINT-(2-1))       --> X <s 126
6946   // (X+MAXSINT) >s X  --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
6947   // (X+MINSINT) >s X  --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
6948   // (X+ -2) >s X      --> X <s (MAXSINT-(-2-1))      --> X <s -126
6949   // (X+ -1) >s X      --> X <s (MAXSINT-(-1-1))      --> X == -128
6950   
6951   // If this is an NSW add, then we have two cases: if the constant is
6952   // positive, then this is always true, if negative, this is always false.
6953   if (isNSW) {
6954     bool isTrue = !CI->getValue().isNegative();
6955     return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6956   }
6957   
6958   assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
6959   Constant *C = ConstantInt::get(X->getContext(), CI->getValue()-1);
6960   return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
6961 }
6962
6963 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6964 /// and CmpRHS are both known to be integer constants.
6965 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6966                                           ConstantInt *DivRHS) {
6967   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6968   const APInt &CmpRHSV = CmpRHS->getValue();
6969   
6970   // FIXME: If the operand types don't match the type of the divide 
6971   // then don't attempt this transform. The code below doesn't have the
6972   // logic to deal with a signed divide and an unsigned compare (and
6973   // vice versa). This is because (x /s C1) <s C2  produces different 
6974   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6975   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6976   // work. :(  The if statement below tests that condition and bails 
6977   // if it finds it. 
6978   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6979   if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
6980     return 0;
6981   if (DivRHS->isZero())
6982     return 0; // The ProdOV computation fails on divide by zero.
6983   if (DivIsSigned && DivRHS->isAllOnesValue())
6984     return 0; // The overflow computation also screws up here
6985   if (DivRHS->isOne())
6986     return 0; // Not worth bothering, and eliminates some funny cases
6987               // with INT_MIN.
6988
6989   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6990   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6991   // C2 (CI). By solving for X we can turn this into a range check 
6992   // instead of computing a divide. 
6993   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6994
6995   // Determine if the product overflows by seeing if the product is
6996   // not equal to the divide. Make sure we do the same kind of divide
6997   // as in the LHS instruction that we're folding. 
6998   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6999                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
7000
7001   // Get the ICmp opcode
7002   ICmpInst::Predicate Pred = ICI.getPredicate();
7003
7004   // Figure out the interval that is being checked.  For example, a comparison
7005   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
7006   // Compute this interval based on the constants involved and the signedness of
7007   // the compare/divide.  This computes a half-open interval, keeping track of
7008   // whether either value in the interval overflows.  After analysis each
7009   // overflow variable is set to 0 if it's corresponding bound variable is valid
7010   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
7011   int LoOverflow = 0, HiOverflow = 0;
7012   Constant *LoBound = 0, *HiBound = 0;
7013   
7014   if (!DivIsSigned) {  // udiv
7015     // e.g. X/5 op 3  --> [15, 20)
7016     LoBound = Prod;
7017     HiOverflow = LoOverflow = ProdOV;
7018     if (!HiOverflow)
7019       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
7020   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
7021     if (CmpRHSV == 0) {       // (X / pos) op 0
7022       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
7023       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
7024       HiBound = DivRHS;
7025     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
7026       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
7027       HiOverflow = LoOverflow = ProdOV;
7028       if (!HiOverflow)
7029         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
7030     } else {                       // (X / pos) op neg
7031       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
7032       HiBound = AddOne(Prod);
7033       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
7034       if (!LoOverflow) {
7035         ConstantInt* DivNeg =
7036                          cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
7037         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
7038                                      true) ? -1 : 0;
7039        }
7040     }
7041   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
7042     if (CmpRHSV == 0) {       // (X / neg) op 0
7043       // e.g. X/-5 op 0  --> [-4, 5)
7044       LoBound = AddOne(DivRHS);
7045       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
7046       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
7047         HiOverflow = 1;            // [INTMIN+1, overflow)
7048         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
7049       }
7050     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
7051       // e.g. X/-5 op 3  --> [-19, -14)
7052       HiBound = AddOne(Prod);
7053       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
7054       if (!LoOverflow)
7055         LoOverflow = AddWithOverflow(LoBound, HiBound,
7056                                      DivRHS, Context, true) ? -1 : 0;
7057     } else {                       // (X / neg) op neg
7058       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
7059       LoOverflow = HiOverflow = ProdOV;
7060       if (!HiOverflow)
7061         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
7062     }
7063     
7064     // Dividing by a negative swaps the condition.  LT <-> GT
7065     Pred = ICmpInst::getSwappedPredicate(Pred);
7066   }
7067
7068   Value *X = DivI->getOperand(0);
7069   switch (Pred) {
7070   default: llvm_unreachable("Unhandled icmp opcode!");
7071   case ICmpInst::ICMP_EQ:
7072     if (LoOverflow && HiOverflow)
7073       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7074     else if (HiOverflow)
7075       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
7076                           ICmpInst::ICMP_UGE, X, LoBound);
7077     else if (LoOverflow)
7078       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
7079                           ICmpInst::ICMP_ULT, X, HiBound);
7080     else
7081       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
7082   case ICmpInst::ICMP_NE:
7083     if (LoOverflow && HiOverflow)
7084       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7085     else if (HiOverflow)
7086       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
7087                           ICmpInst::ICMP_ULT, X, LoBound);
7088     else if (LoOverflow)
7089       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
7090                           ICmpInst::ICMP_UGE, X, HiBound);
7091     else
7092       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
7093   case ICmpInst::ICMP_ULT:
7094   case ICmpInst::ICMP_SLT:
7095     if (LoOverflow == +1)   // Low bound is greater than input range.
7096       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7097     if (LoOverflow == -1)   // Low bound is less than input range.
7098       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7099     return new ICmpInst(Pred, X, LoBound);
7100   case ICmpInst::ICMP_UGT:
7101   case ICmpInst::ICMP_SGT:
7102     if (HiOverflow == +1)       // High bound greater than input range.
7103       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7104     else if (HiOverflow == -1)  // High bound less than input range.
7105       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7106     if (Pred == ICmpInst::ICMP_UGT)
7107       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
7108     else
7109       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
7110   }
7111 }
7112
7113
7114 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
7115 ///
7116 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
7117                                                           Instruction *LHSI,
7118                                                           ConstantInt *RHS) {
7119   const APInt &RHSV = RHS->getValue();
7120   
7121   switch (LHSI->getOpcode()) {
7122   case Instruction::Trunc:
7123     if (ICI.isEquality() && LHSI->hasOneUse()) {
7124       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
7125       // of the high bits truncated out of x are known.
7126       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
7127              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
7128       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
7129       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
7130       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
7131       
7132       // If all the high bits are known, we can do this xform.
7133       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
7134         // Pull in the high bits from known-ones set.
7135         APInt NewRHS(RHS->getValue());
7136         NewRHS.zext(SrcBits);
7137         NewRHS |= KnownOne;
7138         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
7139                             ConstantInt::get(*Context, NewRHS));
7140       }
7141     }
7142     break;
7143       
7144   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
7145     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
7146       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
7147       // fold the xor.
7148       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
7149           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
7150         Value *CompareVal = LHSI->getOperand(0);
7151         
7152         // If the sign bit of the XorCST is not set, there is no change to
7153         // the operation, just stop using the Xor.
7154         if (!XorCST->getValue().isNegative()) {
7155           ICI.setOperand(0, CompareVal);
7156           Worklist.Add(LHSI);
7157           return &ICI;
7158         }
7159         
7160         // Was the old condition true if the operand is positive?
7161         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
7162         
7163         // If so, the new one isn't.
7164         isTrueIfPositive ^= true;
7165         
7166         if (isTrueIfPositive)
7167           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
7168                               SubOne(RHS));
7169         else
7170           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
7171                               AddOne(RHS));
7172       }
7173
7174       if (LHSI->hasOneUse()) {
7175         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
7176         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
7177           const APInt &SignBit = XorCST->getValue();
7178           ICmpInst::Predicate Pred = ICI.isSigned()
7179                                          ? ICI.getUnsignedPredicate()
7180                                          : ICI.getSignedPredicate();
7181           return new ICmpInst(Pred, LHSI->getOperand(0),
7182                               ConstantInt::get(*Context, RHSV ^ SignBit));
7183         }
7184
7185         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
7186         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
7187           const APInt &NotSignBit = XorCST->getValue();
7188           ICmpInst::Predicate Pred = ICI.isSigned()
7189                                          ? ICI.getUnsignedPredicate()
7190                                          : ICI.getSignedPredicate();
7191           Pred = ICI.getSwappedPredicate(Pred);
7192           return new ICmpInst(Pred, LHSI->getOperand(0),
7193                               ConstantInt::get(*Context, RHSV ^ NotSignBit));
7194         }
7195       }
7196     }
7197     break;
7198   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
7199     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
7200         LHSI->getOperand(0)->hasOneUse()) {
7201       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
7202       
7203       // If the LHS is an AND of a truncating cast, we can widen the
7204       // and/compare to be the input width without changing the value
7205       // produced, eliminating a cast.
7206       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
7207         // We can do this transformation if either the AND constant does not
7208         // have its sign bit set or if it is an equality comparison. 
7209         // Extending a relational comparison when we're checking the sign
7210         // bit would not work.
7211         if (Cast->hasOneUse() &&
7212             (ICI.isEquality() ||
7213              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
7214           uint32_t BitWidth = 
7215             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
7216           APInt NewCST = AndCST->getValue();
7217           NewCST.zext(BitWidth);
7218           APInt NewCI = RHSV;
7219           NewCI.zext(BitWidth);
7220           Value *NewAnd = 
7221             Builder->CreateAnd(Cast->getOperand(0),
7222                            ConstantInt::get(*Context, NewCST), LHSI->getName());
7223           return new ICmpInst(ICI.getPredicate(), NewAnd,
7224                               ConstantInt::get(*Context, NewCI));
7225         }
7226       }
7227       
7228       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
7229       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
7230       // happens a LOT in code produced by the C front-end, for bitfield
7231       // access.
7232       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
7233       if (Shift && !Shift->isShift())
7234         Shift = 0;
7235       
7236       ConstantInt *ShAmt;
7237       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
7238       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
7239       const Type *AndTy = AndCST->getType();          // Type of the and.
7240       
7241       // We can fold this as long as we can't shift unknown bits
7242       // into the mask.  This can only happen with signed shift
7243       // rights, as they sign-extend.
7244       if (ShAmt) {
7245         bool CanFold = Shift->isLogicalShift();
7246         if (!CanFold) {
7247           // To test for the bad case of the signed shr, see if any
7248           // of the bits shifted in could be tested after the mask.
7249           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
7250           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
7251           
7252           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
7253           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
7254                AndCST->getValue()) == 0)
7255             CanFold = true;
7256         }
7257         
7258         if (CanFold) {
7259           Constant *NewCst;
7260           if (Shift->getOpcode() == Instruction::Shl)
7261             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
7262           else
7263             NewCst = ConstantExpr::getShl(RHS, ShAmt);
7264           
7265           // Check to see if we are shifting out any of the bits being
7266           // compared.
7267           if (ConstantExpr::get(Shift->getOpcode(),
7268                                        NewCst, ShAmt) != RHS) {
7269             // If we shifted bits out, the fold is not going to work out.
7270             // As a special case, check to see if this means that the
7271             // result is always true or false now.
7272             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7273               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7274             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7275               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7276           } else {
7277             ICI.setOperand(1, NewCst);
7278             Constant *NewAndCST;
7279             if (Shift->getOpcode() == Instruction::Shl)
7280               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
7281             else
7282               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
7283             LHSI->setOperand(1, NewAndCST);
7284             LHSI->setOperand(0, Shift->getOperand(0));
7285             Worklist.Add(Shift); // Shift is dead.
7286             return &ICI;
7287           }
7288         }
7289       }
7290       
7291       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
7292       // preferable because it allows the C<<Y expression to be hoisted out
7293       // of a loop if Y is invariant and X is not.
7294       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
7295           ICI.isEquality() && !Shift->isArithmeticShift() &&
7296           !isa<Constant>(Shift->getOperand(0))) {
7297         // Compute C << Y.
7298         Value *NS;
7299         if (Shift->getOpcode() == Instruction::LShr) {
7300           NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
7301         } else {
7302           // Insert a logical shift.
7303           NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
7304         }
7305         
7306         // Compute X & (C << Y).
7307         Value *NewAnd = 
7308           Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
7309         
7310         ICI.setOperand(0, NewAnd);
7311         return &ICI;
7312       }
7313     }
7314     break;
7315     
7316   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
7317     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7318     if (!ShAmt) break;
7319     
7320     uint32_t TypeBits = RHSV.getBitWidth();
7321     
7322     // Check that the shift amount is in range.  If not, don't perform
7323     // undefined shifts.  When the shift is visited it will be
7324     // simplified.
7325     if (ShAmt->uge(TypeBits))
7326       break;
7327     
7328     if (ICI.isEquality()) {
7329       // If we are comparing against bits always shifted out, the
7330       // comparison cannot succeed.
7331       Constant *Comp =
7332         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
7333                                                                  ShAmt);
7334       if (Comp != RHS) {// Comparing against a bit that we know is zero.
7335         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7336         Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
7337         return ReplaceInstUsesWith(ICI, Cst);
7338       }
7339       
7340       if (LHSI->hasOneUse()) {
7341         // Otherwise strength reduce the shift into an and.
7342         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
7343         Constant *Mask =
7344           ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits, 
7345                                                        TypeBits-ShAmtVal));
7346         
7347         Value *And =
7348           Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
7349         return new ICmpInst(ICI.getPredicate(), And,
7350                             ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
7351       }
7352     }
7353     
7354     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
7355     bool TrueIfSigned = false;
7356     if (LHSI->hasOneUse() &&
7357         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
7358       // (X << 31) <s 0  --> (X&1) != 0
7359       Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
7360                                            (TypeBits-ShAmt->getZExtValue()-1));
7361       Value *And =
7362         Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
7363       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
7364                           And, Constant::getNullValue(And->getType()));
7365     }
7366     break;
7367   }
7368     
7369   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
7370   case Instruction::AShr: {
7371     // Only handle equality comparisons of shift-by-constant.
7372     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7373     if (!ShAmt || !ICI.isEquality()) break;
7374
7375     // Check that the shift amount is in range.  If not, don't perform
7376     // undefined shifts.  When the shift is visited it will be
7377     // simplified.
7378     uint32_t TypeBits = RHSV.getBitWidth();
7379     if (ShAmt->uge(TypeBits))
7380       break;
7381     
7382     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
7383       
7384     // If we are comparing against bits always shifted out, the
7385     // comparison cannot succeed.
7386     APInt Comp = RHSV << ShAmtVal;
7387     if (LHSI->getOpcode() == Instruction::LShr)
7388       Comp = Comp.lshr(ShAmtVal);
7389     else
7390       Comp = Comp.ashr(ShAmtVal);
7391     
7392     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7393       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7394       Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
7395       return ReplaceInstUsesWith(ICI, Cst);
7396     }
7397     
7398     // Otherwise, check to see if the bits shifted out are known to be zero.
7399     // If so, we can compare against the unshifted value:
7400     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
7401     if (LHSI->hasOneUse() &&
7402         MaskedValueIsZero(LHSI->getOperand(0), 
7403                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
7404       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
7405                           ConstantExpr::getShl(RHS, ShAmt));
7406     }
7407       
7408     if (LHSI->hasOneUse()) {
7409       // Otherwise strength reduce the shift into an and.
7410       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7411       Constant *Mask = ConstantInt::get(*Context, Val);
7412       
7413       Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7414                                       Mask, LHSI->getName()+".mask");
7415       return new ICmpInst(ICI.getPredicate(), And,
7416                           ConstantExpr::getShl(RHS, ShAmt));
7417     }
7418     break;
7419   }
7420     
7421   case Instruction::SDiv:
7422   case Instruction::UDiv:
7423     // Fold: icmp pred ([us]div X, C1), C2 -> range test
7424     // Fold this div into the comparison, producing a range check. 
7425     // Determine, based on the divide type, what the range is being 
7426     // checked.  If there is an overflow on the low or high side, remember 
7427     // it, otherwise compute the range [low, hi) bounding the new value.
7428     // See: InsertRangeTest above for the kinds of replacements possible.
7429     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7430       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7431                                           DivRHS))
7432         return R;
7433     break;
7434
7435   case Instruction::Add:
7436     // Fold: icmp pred (add X, C1), C2
7437     if (!ICI.isEquality()) {
7438       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7439       if (!LHSC) break;
7440       const APInt &LHSV = LHSC->getValue();
7441
7442       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7443                             .subtract(LHSV);
7444
7445       if (ICI.isSigned()) {
7446         if (CR.getLower().isSignBit()) {
7447           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7448                               ConstantInt::get(*Context, CR.getUpper()));
7449         } else if (CR.getUpper().isSignBit()) {
7450           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7451                               ConstantInt::get(*Context, CR.getLower()));
7452         }
7453       } else {
7454         if (CR.getLower().isMinValue()) {
7455           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7456                               ConstantInt::get(*Context, CR.getUpper()));
7457         } else if (CR.getUpper().isMinValue()) {
7458           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7459                               ConstantInt::get(*Context, CR.getLower()));
7460         }
7461       }
7462     }
7463     break;
7464   }
7465   
7466   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7467   if (ICI.isEquality()) {
7468     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7469     
7470     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7471     // the second operand is a constant, simplify a bit.
7472     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7473       switch (BO->getOpcode()) {
7474       case Instruction::SRem:
7475         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7476         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7477           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7478           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7479             Value *NewRem =
7480               Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7481                                   BO->getName());
7482             return new ICmpInst(ICI.getPredicate(), NewRem,
7483                                 Constant::getNullValue(BO->getType()));
7484           }
7485         }
7486         break;
7487       case Instruction::Add:
7488         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7489         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7490           if (BO->hasOneUse())
7491             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7492                                 ConstantExpr::getSub(RHS, BOp1C));
7493         } else if (RHSV == 0) {
7494           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7495           // efficiently invertible, or if the add has just this one use.
7496           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7497           
7498           if (Value *NegVal = dyn_castNegVal(BOp1))
7499             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
7500           else if (Value *NegVal = dyn_castNegVal(BOp0))
7501             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
7502           else if (BO->hasOneUse()) {
7503             Value *Neg = Builder->CreateNeg(BOp1);
7504             Neg->takeName(BO);
7505             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
7506           }
7507         }
7508         break;
7509       case Instruction::Xor:
7510         // For the xor case, we can xor two constants together, eliminating
7511         // the explicit xor.
7512         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7513           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
7514                               ConstantExpr::getXor(RHS, BOC));
7515         
7516         // FALLTHROUGH
7517       case Instruction::Sub:
7518         // Replace (([sub|xor] A, B) != 0) with (A != B)
7519         if (RHSV == 0)
7520           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7521                               BO->getOperand(1));
7522         break;
7523         
7524       case Instruction::Or:
7525         // If bits are being or'd in that are not present in the constant we
7526         // are comparing against, then the comparison could never succeed!
7527         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7528           Constant *NotCI = ConstantExpr::getNot(RHS);
7529           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7530             return ReplaceInstUsesWith(ICI,
7531                                        ConstantInt::get(Type::getInt1Ty(*Context), 
7532                                        isICMP_NE));
7533         }
7534         break;
7535         
7536       case Instruction::And:
7537         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7538           // If bits are being compared against that are and'd out, then the
7539           // comparison can never succeed!
7540           if ((RHSV & ~BOC->getValue()) != 0)
7541             return ReplaceInstUsesWith(ICI,
7542                                        ConstantInt::get(Type::getInt1Ty(*Context),
7543                                        isICMP_NE));
7544           
7545           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7546           if (RHS == BOC && RHSV.isPowerOf2())
7547             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7548                                 ICmpInst::ICMP_NE, LHSI,
7549                                 Constant::getNullValue(RHS->getType()));
7550           
7551           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7552           if (BOC->getValue().isSignBit()) {
7553             Value *X = BO->getOperand(0);
7554             Constant *Zero = Constant::getNullValue(X->getType());
7555             ICmpInst::Predicate pred = isICMP_NE ? 
7556               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7557             return new ICmpInst(pred, X, Zero);
7558           }
7559           
7560           // ((X & ~7) == 0) --> X < 8
7561           if (RHSV == 0 && isHighOnes(BOC)) {
7562             Value *X = BO->getOperand(0);
7563             Constant *NegX = ConstantExpr::getNeg(BOC);
7564             ICmpInst::Predicate pred = isICMP_NE ? 
7565               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7566             return new ICmpInst(pred, X, NegX);
7567           }
7568         }
7569       default: break;
7570       }
7571     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7572       // Handle icmp {eq|ne} <intrinsic>, intcst.
7573       if (II->getIntrinsicID() == Intrinsic::bswap) {
7574         Worklist.Add(II);
7575         ICI.setOperand(0, II->getOperand(1));
7576         ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7577         return &ICI;
7578       }
7579     }
7580   }
7581   return 0;
7582 }
7583
7584 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7585 /// We only handle extending casts so far.
7586 ///
7587 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7588   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7589   Value *LHSCIOp        = LHSCI->getOperand(0);
7590   const Type *SrcTy     = LHSCIOp->getType();
7591   const Type *DestTy    = LHSCI->getType();
7592   Value *RHSCIOp;
7593
7594   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7595   // integer type is the same size as the pointer type.
7596   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7597       TD->getPointerSizeInBits() ==
7598          cast<IntegerType>(DestTy)->getBitWidth()) {
7599     Value *RHSOp = 0;
7600     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7601       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7602     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7603       RHSOp = RHSC->getOperand(0);
7604       // If the pointer types don't match, insert a bitcast.
7605       if (LHSCIOp->getType() != RHSOp->getType())
7606         RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
7607     }
7608
7609     if (RHSOp)
7610       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7611   }
7612   
7613   // The code below only handles extension cast instructions, so far.
7614   // Enforce this.
7615   if (LHSCI->getOpcode() != Instruction::ZExt &&
7616       LHSCI->getOpcode() != Instruction::SExt)
7617     return 0;
7618
7619   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7620   bool isSignedCmp = ICI.isSigned();
7621
7622   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7623     // Not an extension from the same type?
7624     RHSCIOp = CI->getOperand(0);
7625     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7626       return 0;
7627     
7628     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7629     // and the other is a zext), then we can't handle this.
7630     if (CI->getOpcode() != LHSCI->getOpcode())
7631       return 0;
7632
7633     // Deal with equality cases early.
7634     if (ICI.isEquality())
7635       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7636
7637     // A signed comparison of sign extended values simplifies into a
7638     // signed comparison.
7639     if (isSignedCmp && isSignedExt)
7640       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7641
7642     // The other three cases all fold into an unsigned comparison.
7643     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7644   }
7645
7646   // If we aren't dealing with a constant on the RHS, exit early
7647   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7648   if (!CI)
7649     return 0;
7650
7651   // Compute the constant that would happen if we truncated to SrcTy then
7652   // reextended to DestTy.
7653   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7654   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7655                                                 Res1, DestTy);
7656
7657   // If the re-extended constant didn't change...
7658   if (Res2 == CI) {
7659     // Deal with equality cases early.
7660     if (ICI.isEquality())
7661       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7662
7663     // A signed comparison of sign extended values simplifies into a
7664     // signed comparison.
7665     if (isSignedExt && isSignedCmp)
7666       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7667
7668     // The other three cases all fold into an unsigned comparison.
7669     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
7670   }
7671
7672   // The re-extended constant changed so the constant cannot be represented 
7673   // in the shorter type. Consequently, we cannot emit a simple comparison.
7674
7675   // First, handle some easy cases. We know the result cannot be equal at this
7676   // point so handle the ICI.isEquality() cases
7677   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7678     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7679   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7680     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7681
7682   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7683   // should have been folded away previously and not enter in here.
7684   Value *Result;
7685   if (isSignedCmp) {
7686     // We're performing a signed comparison.
7687     if (cast<ConstantInt>(CI)->getValue().isNegative())
7688       Result = ConstantInt::getFalse(*Context);          // X < (small) --> false
7689     else
7690       Result = ConstantInt::getTrue(*Context);           // X < (large) --> true
7691   } else {
7692     // We're performing an unsigned comparison.
7693     if (isSignedExt) {
7694       // We're performing an unsigned comp with a sign extended value.
7695       // This is true if the input is >= 0. [aka >s -1]
7696       Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7697       Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
7698     } else {
7699       // Unsigned extend & unsigned compare -> always true.
7700       Result = ConstantInt::getTrue(*Context);
7701     }
7702   }
7703
7704   // Finally, return the value computed.
7705   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7706       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7707     return ReplaceInstUsesWith(ICI, Result);
7708
7709   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7710           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7711          "ICmp should be folded!");
7712   if (Constant *CI = dyn_cast<Constant>(Result))
7713     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7714   return BinaryOperator::CreateNot(Result);
7715 }
7716
7717 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7718   return commonShiftTransforms(I);
7719 }
7720
7721 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7722   return commonShiftTransforms(I);
7723 }
7724
7725 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7726   if (Instruction *R = commonShiftTransforms(I))
7727     return R;
7728   
7729   Value *Op0 = I.getOperand(0);
7730   
7731   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7732   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7733     if (CSI->isAllOnesValue())
7734       return ReplaceInstUsesWith(I, CSI);
7735
7736   // See if we can turn a signed shr into an unsigned shr.
7737   if (MaskedValueIsZero(Op0,
7738                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7739     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7740
7741   // Arithmetic shifting an all-sign-bit value is a no-op.
7742   unsigned NumSignBits = ComputeNumSignBits(Op0);
7743   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7744     return ReplaceInstUsesWith(I, Op0);
7745
7746   return 0;
7747 }
7748
7749 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7750   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7751   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7752
7753   // shl X, 0 == X and shr X, 0 == X
7754   // shl 0, X == 0 and shr 0, X == 0
7755   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7756       Op0 == Constant::getNullValue(Op0->getType()))
7757     return ReplaceInstUsesWith(I, Op0);
7758   
7759   if (isa<UndefValue>(Op0)) {            
7760     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7761       return ReplaceInstUsesWith(I, Op0);
7762     else                                    // undef << X -> 0, undef >>u X -> 0
7763       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7764   }
7765   if (isa<UndefValue>(Op1)) {
7766     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7767       return ReplaceInstUsesWith(I, Op0);          
7768     else                                     // X << undef, X >>u undef -> 0
7769       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7770   }
7771
7772   // See if we can fold away this shift.
7773   if (SimplifyDemandedInstructionBits(I))
7774     return &I;
7775
7776   // Try to fold constant and into select arguments.
7777   if (isa<Constant>(Op0))
7778     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7779       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7780         return R;
7781
7782   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7783     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7784       return Res;
7785   return 0;
7786 }
7787
7788 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7789                                                BinaryOperator &I) {
7790   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7791
7792   // See if we can simplify any instructions used by the instruction whose sole 
7793   // purpose is to compute bits we don't care about.
7794   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7795   
7796   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7797   // a signed shift.
7798   //
7799   if (Op1->uge(TypeBits)) {
7800     if (I.getOpcode() != Instruction::AShr)
7801       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7802     else {
7803       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7804       return &I;
7805     }
7806   }
7807   
7808   // ((X*C1) << C2) == (X * (C1 << C2))
7809   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7810     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7811       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7812         return BinaryOperator::CreateMul(BO->getOperand(0),
7813                                         ConstantExpr::getShl(BOOp, Op1));
7814   
7815   // Try to fold constant and into select arguments.
7816   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7817     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7818       return R;
7819   if (isa<PHINode>(Op0))
7820     if (Instruction *NV = FoldOpIntoPhi(I))
7821       return NV;
7822   
7823   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7824   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7825     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7826     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7827     // place.  Don't try to do this transformation in this case.  Also, we
7828     // require that the input operand is a shift-by-constant so that we have
7829     // confidence that the shifts will get folded together.  We could do this
7830     // xform in more cases, but it is unlikely to be profitable.
7831     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7832         isa<ConstantInt>(TrOp->getOperand(1))) {
7833       // Okay, we'll do this xform.  Make the shift of shift.
7834       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7835       // (shift2 (shift1 & 0x00FF), c2)
7836       Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
7837
7838       // For logical shifts, the truncation has the effect of making the high
7839       // part of the register be zeros.  Emulate this by inserting an AND to
7840       // clear the top bits as needed.  This 'and' will usually be zapped by
7841       // other xforms later if dead.
7842       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7843       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7844       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7845       
7846       // The mask we constructed says what the trunc would do if occurring
7847       // between the shifts.  We want to know the effect *after* the second
7848       // shift.  We know that it is a logical shift by a constant, so adjust the
7849       // mask as appropriate.
7850       if (I.getOpcode() == Instruction::Shl)
7851         MaskV <<= Op1->getZExtValue();
7852       else {
7853         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7854         MaskV = MaskV.lshr(Op1->getZExtValue());
7855       }
7856
7857       // shift1 & 0x00FF
7858       Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7859                                       TI->getName());
7860
7861       // Return the value truncated to the interesting size.
7862       return new TruncInst(And, I.getType());
7863     }
7864   }
7865   
7866   if (Op0->hasOneUse()) {
7867     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7868       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7869       Value *V1, *V2;
7870       ConstantInt *CC;
7871       switch (Op0BO->getOpcode()) {
7872         default: break;
7873         case Instruction::Add:
7874         case Instruction::And:
7875         case Instruction::Or:
7876         case Instruction::Xor: {
7877           // These operators commute.
7878           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7879           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7880               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7881                     m_Specific(Op1)))) {
7882             Value *YS =         // (Y << C)
7883               Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7884             // (X + (Y << C))
7885             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7886                                             Op0BO->getOperand(1)->getName());
7887             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7888             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7889                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7890           }
7891           
7892           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7893           Value *Op0BOOp1 = Op0BO->getOperand(1);
7894           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7895               match(Op0BOOp1, 
7896                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7897                           m_ConstantInt(CC))) &&
7898               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7899             Value *YS =   // (Y << C)
7900               Builder->CreateShl(Op0BO->getOperand(0), Op1,
7901                                            Op0BO->getName());
7902             // X & (CC << C)
7903             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7904                                            V1->getName()+".mask");
7905             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7906           }
7907         }
7908           
7909         // FALL THROUGH.
7910         case Instruction::Sub: {
7911           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7912           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7913               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7914                     m_Specific(Op1)))) {
7915             Value *YS =  // (Y << C)
7916               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7917             // (X + (Y << C))
7918             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7919                                             Op0BO->getOperand(0)->getName());
7920             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7921             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7922                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7923           }
7924           
7925           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7926           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7927               match(Op0BO->getOperand(0),
7928                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7929                           m_ConstantInt(CC))) && V2 == Op1 &&
7930               cast<BinaryOperator>(Op0BO->getOperand(0))
7931                   ->getOperand(0)->hasOneUse()) {
7932             Value *YS = // (Y << C)
7933               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7934             // X & (CC << C)
7935             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7936                                            V1->getName()+".mask");
7937             
7938             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7939           }
7940           
7941           break;
7942         }
7943       }
7944       
7945       
7946       // If the operand is an bitwise operator with a constant RHS, and the
7947       // shift is the only use, we can pull it out of the shift.
7948       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7949         bool isValid = true;     // Valid only for And, Or, Xor
7950         bool highBitSet = false; // Transform if high bit of constant set?
7951         
7952         switch (Op0BO->getOpcode()) {
7953           default: isValid = false; break;   // Do not perform transform!
7954           case Instruction::Add:
7955             isValid = isLeftShift;
7956             break;
7957           case Instruction::Or:
7958           case Instruction::Xor:
7959             highBitSet = false;
7960             break;
7961           case Instruction::And:
7962             highBitSet = true;
7963             break;
7964         }
7965         
7966         // If this is a signed shift right, and the high bit is modified
7967         // by the logical operation, do not perform the transformation.
7968         // The highBitSet boolean indicates the value of the high bit of
7969         // the constant which would cause it to be modified for this
7970         // operation.
7971         //
7972         if (isValid && I.getOpcode() == Instruction::AShr)
7973           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7974         
7975         if (isValid) {
7976           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7977           
7978           Value *NewShift =
7979             Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
7980           NewShift->takeName(Op0BO);
7981           
7982           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7983                                         NewRHS);
7984         }
7985       }
7986     }
7987   }
7988   
7989   // Find out if this is a shift of a shift by a constant.
7990   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7991   if (ShiftOp && !ShiftOp->isShift())
7992     ShiftOp = 0;
7993   
7994   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7995     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7996     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7997     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7998     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7999     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
8000     Value *X = ShiftOp->getOperand(0);
8001     
8002     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
8003     
8004     const IntegerType *Ty = cast<IntegerType>(I.getType());
8005     
8006     // Check for (X << c1) << c2  and  (X >> c1) >> c2
8007     if (I.getOpcode() == ShiftOp->getOpcode()) {
8008       // If this is oversized composite shift, then unsigned shifts get 0, ashr
8009       // saturates.
8010       if (AmtSum >= TypeBits) {
8011         if (I.getOpcode() != Instruction::AShr)
8012           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
8013         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
8014       }
8015       
8016       return BinaryOperator::Create(I.getOpcode(), X,
8017                                     ConstantInt::get(Ty, AmtSum));
8018     }
8019     
8020     if (ShiftOp->getOpcode() == Instruction::LShr &&
8021         I.getOpcode() == Instruction::AShr) {
8022       if (AmtSum >= TypeBits)
8023         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
8024       
8025       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
8026       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
8027     }
8028     
8029     if (ShiftOp->getOpcode() == Instruction::AShr &&
8030         I.getOpcode() == Instruction::LShr) {
8031       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
8032       if (AmtSum >= TypeBits)
8033         AmtSum = TypeBits-1;
8034       
8035       Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
8036
8037       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
8038       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
8039     }
8040     
8041     // Okay, if we get here, one shift must be left, and the other shift must be
8042     // right.  See if the amounts are equal.
8043     if (ShiftAmt1 == ShiftAmt2) {
8044       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
8045       if (I.getOpcode() == Instruction::Shl) {
8046         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
8047         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
8048       }
8049       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
8050       if (I.getOpcode() == Instruction::LShr) {
8051         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
8052         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
8053       }
8054       // We can simplify ((X << C) >>s C) into a trunc + sext.
8055       // NOTE: we could do this for any C, but that would make 'unusual' integer
8056       // types.  For now, just stick to ones well-supported by the code
8057       // generators.
8058       const Type *SExtType = 0;
8059       switch (Ty->getBitWidth() - ShiftAmt1) {
8060       case 1  :
8061       case 8  :
8062       case 16 :
8063       case 32 :
8064       case 64 :
8065       case 128:
8066         SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
8067         break;
8068       default: break;
8069       }
8070       if (SExtType)
8071         return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
8072       // Otherwise, we can't handle it yet.
8073     } else if (ShiftAmt1 < ShiftAmt2) {
8074       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
8075       
8076       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
8077       if (I.getOpcode() == Instruction::Shl) {
8078         assert(ShiftOp->getOpcode() == Instruction::LShr ||
8079                ShiftOp->getOpcode() == Instruction::AShr);
8080         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
8081         
8082         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
8083         return BinaryOperator::CreateAnd(Shift,
8084                                          ConstantInt::get(*Context, Mask));
8085       }
8086       
8087       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
8088       if (I.getOpcode() == Instruction::LShr) {
8089         assert(ShiftOp->getOpcode() == Instruction::Shl);
8090         Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
8091         
8092         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
8093         return BinaryOperator::CreateAnd(Shift,
8094                                          ConstantInt::get(*Context, Mask));
8095       }
8096       
8097       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
8098     } else {
8099       assert(ShiftAmt2 < ShiftAmt1);
8100       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
8101
8102       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
8103       if (I.getOpcode() == Instruction::Shl) {
8104         assert(ShiftOp->getOpcode() == Instruction::LShr ||
8105                ShiftOp->getOpcode() == Instruction::AShr);
8106         Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
8107                                             ConstantInt::get(Ty, ShiftDiff));
8108         
8109         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
8110         return BinaryOperator::CreateAnd(Shift,
8111                                          ConstantInt::get(*Context, Mask));
8112       }
8113       
8114       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
8115       if (I.getOpcode() == Instruction::LShr) {
8116         assert(ShiftOp->getOpcode() == Instruction::Shl);
8117         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
8118         
8119         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
8120         return BinaryOperator::CreateAnd(Shift,
8121                                          ConstantInt::get(*Context, Mask));
8122       }
8123       
8124       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
8125     }
8126   }
8127   return 0;
8128 }
8129
8130
8131 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
8132 /// expression.  If so, decompose it, returning some value X, such that Val is
8133 /// X*Scale+Offset.
8134 ///
8135 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
8136                                         int &Offset, LLVMContext *Context) {
8137   assert(Val->getType() == Type::getInt32Ty(*Context) && 
8138          "Unexpected allocation size type!");
8139   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
8140     Offset = CI->getZExtValue();
8141     Scale  = 0;
8142     return ConstantInt::get(Type::getInt32Ty(*Context), 0);
8143   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
8144     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8145       if (I->getOpcode() == Instruction::Shl) {
8146         // This is a value scaled by '1 << the shift amt'.
8147         Scale = 1U << RHS->getZExtValue();
8148         Offset = 0;
8149         return I->getOperand(0);
8150       } else if (I->getOpcode() == Instruction::Mul) {
8151         // This value is scaled by 'RHS'.
8152         Scale = RHS->getZExtValue();
8153         Offset = 0;
8154         return I->getOperand(0);
8155       } else if (I->getOpcode() == Instruction::Add) {
8156         // We have X+C.  Check to see if we really have (X*C2)+C1, 
8157         // where C1 is divisible by C2.
8158         unsigned SubScale;
8159         Value *SubVal = 
8160           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
8161                                     Offset, Context);
8162         Offset += RHS->getZExtValue();
8163         Scale = SubScale;
8164         return SubVal;
8165       }
8166     }
8167   }
8168
8169   // Otherwise, we can't look past this.
8170   Scale = 1;
8171   Offset = 0;
8172   return Val;
8173 }
8174
8175
8176 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
8177 /// try to eliminate the cast by moving the type information into the alloc.
8178 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
8179                                                    AllocaInst &AI) {
8180   const PointerType *PTy = cast<PointerType>(CI.getType());
8181   
8182   BuilderTy AllocaBuilder(*Builder);
8183   AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
8184   
8185   // Remove any uses of AI that are dead.
8186   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
8187   
8188   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
8189     Instruction *User = cast<Instruction>(*UI++);
8190     if (isInstructionTriviallyDead(User)) {
8191       while (UI != E && *UI == User)
8192         ++UI; // If this instruction uses AI more than once, don't break UI.
8193       
8194       ++NumDeadInst;
8195       DEBUG(errs() << "IC: DCE: " << *User << '\n');
8196       EraseInstFromFunction(*User);
8197     }
8198   }
8199
8200   // This requires TargetData to get the alloca alignment and size information.
8201   if (!TD) return 0;
8202
8203   // Get the type really allocated and the type casted to.
8204   const Type *AllocElTy = AI.getAllocatedType();
8205   const Type *CastElTy = PTy->getElementType();
8206   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
8207
8208   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
8209   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
8210   if (CastElTyAlign < AllocElTyAlign) return 0;
8211
8212   // If the allocation has multiple uses, only promote it if we are strictly
8213   // increasing the alignment of the resultant allocation.  If we keep it the
8214   // same, we open the door to infinite loops of various kinds.  (A reference
8215   // from a dbg.declare doesn't count as a use for this purpose.)
8216   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
8217       CastElTyAlign == AllocElTyAlign) return 0;
8218
8219   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
8220   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
8221   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
8222
8223   // See if we can satisfy the modulus by pulling a scale out of the array
8224   // size argument.
8225   unsigned ArraySizeScale;
8226   int ArrayOffset;
8227   Value *NumElements = // See if the array size is a decomposable linear expr.
8228     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
8229                               ArrayOffset, Context);
8230  
8231   // If we can now satisfy the modulus, by using a non-1 scale, we really can
8232   // do the xform.
8233   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
8234       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
8235
8236   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
8237   Value *Amt = 0;
8238   if (Scale == 1) {
8239     Amt = NumElements;
8240   } else {
8241     Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
8242     // Insert before the alloca, not before the cast.
8243     Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
8244   }
8245   
8246   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
8247     Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
8248     Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
8249   }
8250   
8251   AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
8252   New->setAlignment(AI.getAlignment());
8253   New->takeName(&AI);
8254   
8255   // If the allocation has one real use plus a dbg.declare, just remove the
8256   // declare.
8257   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
8258     EraseInstFromFunction(*DI);
8259   }
8260   // If the allocation has multiple real uses, insert a cast and change all
8261   // things that used it to use the new cast.  This will also hack on CI, but it
8262   // will die soon.
8263   else if (!AI.hasOneUse()) {
8264     // New is the allocation instruction, pointer typed. AI is the original
8265     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
8266     Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
8267     AI.replaceAllUsesWith(NewCast);
8268   }
8269   return ReplaceInstUsesWith(CI, New);
8270 }
8271
8272 /// CanEvaluateInDifferentType - Return true if we can take the specified value
8273 /// and return it as type Ty without inserting any new casts and without
8274 /// changing the computed value.  This is used by code that tries to decide
8275 /// whether promoting or shrinking integer operations to wider or smaller types
8276 /// will allow us to eliminate a truncate or extend.
8277 ///
8278 /// This is a truncation operation if Ty is smaller than V->getType(), or an
8279 /// extension operation if Ty is larger.
8280 ///
8281 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
8282 /// should return true if trunc(V) can be computed by computing V in the smaller
8283 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
8284 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
8285 /// efficiently truncated.
8286 ///
8287 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
8288 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
8289 /// the final result.
8290 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
8291                                               unsigned CastOpc,
8292                                               int &NumCastsRemoved){
8293   // We can always evaluate constants in another type.
8294   if (isa<Constant>(V))
8295     return true;
8296   
8297   Instruction *I = dyn_cast<Instruction>(V);
8298   if (!I) return false;
8299   
8300   const Type *OrigTy = V->getType();
8301   
8302   // If this is an extension or truncate, we can often eliminate it.
8303   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
8304     // If this is a cast from the destination type, we can trivially eliminate
8305     // it, and this will remove a cast overall.
8306     if (I->getOperand(0)->getType() == Ty) {
8307       // If the first operand is itself a cast, and is eliminable, do not count
8308       // this as an eliminable cast.  We would prefer to eliminate those two
8309       // casts first.
8310       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
8311         ++NumCastsRemoved;
8312       return true;
8313     }
8314   }
8315
8316   // We can't extend or shrink something that has multiple uses: doing so would
8317   // require duplicating the instruction in general, which isn't profitable.
8318   if (!I->hasOneUse()) return false;
8319
8320   unsigned Opc = I->getOpcode();
8321   switch (Opc) {
8322   case Instruction::Add:
8323   case Instruction::Sub:
8324   case Instruction::Mul:
8325   case Instruction::And:
8326   case Instruction::Or:
8327   case Instruction::Xor:
8328     // These operators can all arbitrarily be extended or truncated.
8329     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8330                                       NumCastsRemoved) &&
8331            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8332                                       NumCastsRemoved);
8333
8334   case Instruction::UDiv:
8335   case Instruction::URem: {
8336     // UDiv and URem can be truncated if all the truncated bits are zero.
8337     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8338     uint32_t BitWidth = Ty->getScalarSizeInBits();
8339     if (BitWidth < OrigBitWidth) {
8340       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
8341       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
8342           MaskedValueIsZero(I->getOperand(1), Mask)) {
8343         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8344                                           NumCastsRemoved) &&
8345                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8346                                           NumCastsRemoved);
8347       }
8348     }
8349     break;
8350   }
8351   case Instruction::Shl:
8352     // If we are truncating the result of this SHL, and if it's a shift of a
8353     // constant amount, we can always perform a SHL in a smaller type.
8354     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8355       uint32_t BitWidth = Ty->getScalarSizeInBits();
8356       if (BitWidth < OrigTy->getScalarSizeInBits() &&
8357           CI->getLimitedValue(BitWidth) < BitWidth)
8358         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8359                                           NumCastsRemoved);
8360     }
8361     break;
8362   case Instruction::LShr:
8363     // If this is a truncate of a logical shr, we can truncate it to a smaller
8364     // lshr iff we know that the bits we would otherwise be shifting in are
8365     // already zeros.
8366     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8367       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8368       uint32_t BitWidth = Ty->getScalarSizeInBits();
8369       if (BitWidth < OrigBitWidth &&
8370           MaskedValueIsZero(I->getOperand(0),
8371             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8372           CI->getLimitedValue(BitWidth) < BitWidth) {
8373         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8374                                           NumCastsRemoved);
8375       }
8376     }
8377     break;
8378   case Instruction::ZExt:
8379   case Instruction::SExt:
8380   case Instruction::Trunc:
8381     // If this is the same kind of case as our original (e.g. zext+zext), we
8382     // can safely replace it.  Note that replacing it does not reduce the number
8383     // of casts in the input.
8384     if (Opc == CastOpc)
8385       return true;
8386
8387     // sext (zext ty1), ty2 -> zext ty2
8388     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8389       return true;
8390     break;
8391   case Instruction::Select: {
8392     SelectInst *SI = cast<SelectInst>(I);
8393     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8394                                       NumCastsRemoved) &&
8395            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8396                                       NumCastsRemoved);
8397   }
8398   case Instruction::PHI: {
8399     // We can change a phi if we can change all operands.
8400     PHINode *PN = cast<PHINode>(I);
8401     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8402       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8403                                       NumCastsRemoved))
8404         return false;
8405     return true;
8406   }
8407   default:
8408     // TODO: Can handle more cases here.
8409     break;
8410   }
8411   
8412   return false;
8413 }
8414
8415 /// EvaluateInDifferentType - Given an expression that 
8416 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8417 /// evaluate the expression.
8418 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
8419                                              bool isSigned) {
8420   if (Constant *C = dyn_cast<Constant>(V))
8421     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
8422
8423   // Otherwise, it must be an instruction.
8424   Instruction *I = cast<Instruction>(V);
8425   Instruction *Res = 0;
8426   unsigned Opc = I->getOpcode();
8427   switch (Opc) {
8428   case Instruction::Add:
8429   case Instruction::Sub:
8430   case Instruction::Mul:
8431   case Instruction::And:
8432   case Instruction::Or:
8433   case Instruction::Xor:
8434   case Instruction::AShr:
8435   case Instruction::LShr:
8436   case Instruction::Shl:
8437   case Instruction::UDiv:
8438   case Instruction::URem: {
8439     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8440     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8441     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8442     break;
8443   }    
8444   case Instruction::Trunc:
8445   case Instruction::ZExt:
8446   case Instruction::SExt:
8447     // If the source type of the cast is the type we're trying for then we can
8448     // just return the source.  There's no need to insert it because it is not
8449     // new.
8450     if (I->getOperand(0)->getType() == Ty)
8451       return I->getOperand(0);
8452     
8453     // Otherwise, must be the same type of cast, so just reinsert a new one.
8454     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
8455     break;
8456   case Instruction::Select: {
8457     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8458     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8459     Res = SelectInst::Create(I->getOperand(0), True, False);
8460     break;
8461   }
8462   case Instruction::PHI: {
8463     PHINode *OPN = cast<PHINode>(I);
8464     PHINode *NPN = PHINode::Create(Ty);
8465     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8466       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8467       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8468     }
8469     Res = NPN;
8470     break;
8471   }
8472   default: 
8473     // TODO: Can handle more cases here.
8474     llvm_unreachable("Unreachable!");
8475     break;
8476   }
8477   
8478   Res->takeName(I);
8479   return InsertNewInstBefore(Res, *I);
8480 }
8481
8482 /// @brief Implement the transforms common to all CastInst visitors.
8483 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8484   Value *Src = CI.getOperand(0);
8485
8486   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8487   // eliminate it now.
8488   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8489     if (Instruction::CastOps opc = 
8490         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8491       // The first cast (CSrc) is eliminable so we need to fix up or replace
8492       // the second cast (CI). CSrc will then have a good chance of being dead.
8493       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8494     }
8495   }
8496
8497   // If we are casting a select then fold the cast into the select
8498   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8499     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8500       return NV;
8501
8502   // If we are casting a PHI then fold the cast into the PHI
8503   if (isa<PHINode>(Src)) {
8504     // We don't do this if this would create a PHI node with an illegal type if
8505     // it is currently legal.
8506     if (!isa<IntegerType>(Src->getType()) ||
8507         !isa<IntegerType>(CI.getType()) ||
8508         ShouldChangeType(CI.getType(), Src->getType(), TD))
8509       if (Instruction *NV = FoldOpIntoPhi(CI))
8510         return NV;
8511   }
8512   
8513   return 0;
8514 }
8515
8516 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8517 /// or not there is a sequence of GEP indices into the type that will land us at
8518 /// the specified offset.  If so, fill them into NewIndices and return the
8519 /// resultant element type, otherwise return null.
8520 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8521                                        SmallVectorImpl<Value*> &NewIndices,
8522                                        const TargetData *TD,
8523                                        LLVMContext *Context) {
8524   if (!TD) return 0;
8525   if (!Ty->isSized()) return 0;
8526   
8527   // Start with the index over the outer type.  Note that the type size
8528   // might be zero (even if the offset isn't zero) if the indexed type
8529   // is something like [0 x {int, int}]
8530   const Type *IntPtrTy = TD->getIntPtrType(*Context);
8531   int64_t FirstIdx = 0;
8532   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8533     FirstIdx = Offset/TySize;
8534     Offset -= FirstIdx*TySize;
8535     
8536     // Handle hosts where % returns negative instead of values [0..TySize).
8537     if (Offset < 0) {
8538       --FirstIdx;
8539       Offset += TySize;
8540       assert(Offset >= 0);
8541     }
8542     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8543   }
8544   
8545   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8546     
8547   // Index into the types.  If we fail, set OrigBase to null.
8548   while (Offset) {
8549     // Indexing into tail padding between struct/array elements.
8550     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8551       return 0;
8552     
8553     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8554       const StructLayout *SL = TD->getStructLayout(STy);
8555       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8556              "Offset must stay within the indexed type");
8557       
8558       unsigned Elt = SL->getElementContainingOffset(Offset);
8559       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8560       
8561       Offset -= SL->getElementOffset(Elt);
8562       Ty = STy->getElementType(Elt);
8563     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8564       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8565       assert(EltSize && "Cannot index into a zero-sized array");
8566       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8567       Offset %= EltSize;
8568       Ty = AT->getElementType();
8569     } else {
8570       // Otherwise, we can't index into the middle of this atomic type, bail.
8571       return 0;
8572     }
8573   }
8574   
8575   return Ty;
8576 }
8577
8578 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8579 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8580   Value *Src = CI.getOperand(0);
8581   
8582   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8583     // If casting the result of a getelementptr instruction with no offset, turn
8584     // this into a cast of the original pointer!
8585     if (GEP->hasAllZeroIndices()) {
8586       // Changing the cast operand is usually not a good idea but it is safe
8587       // here because the pointer operand is being replaced with another 
8588       // pointer operand so the opcode doesn't need to change.
8589       Worklist.Add(GEP);
8590       CI.setOperand(0, GEP->getOperand(0));
8591       return &CI;
8592     }
8593     
8594     // If the GEP has a single use, and the base pointer is a bitcast, and the
8595     // GEP computes a constant offset, see if we can convert these three
8596     // instructions into fewer.  This typically happens with unions and other
8597     // non-type-safe code.
8598     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8599       if (GEP->hasAllConstantIndices()) {
8600         // We are guaranteed to get a constant from EmitGEPOffset.
8601         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, *this));
8602         int64_t Offset = OffsetV->getSExtValue();
8603         
8604         // Get the base pointer input of the bitcast, and the type it points to.
8605         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8606         const Type *GEPIdxTy =
8607           cast<PointerType>(OrigBase->getType())->getElementType();
8608         SmallVector<Value*, 8> NewIndices;
8609         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8610           // If we were able to index down into an element, create the GEP
8611           // and bitcast the result.  This eliminates one bitcast, potentially
8612           // two.
8613           Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8614             Builder->CreateInBoundsGEP(OrigBase,
8615                                        NewIndices.begin(), NewIndices.end()) :
8616             Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
8617           NGEP->takeName(GEP);
8618           
8619           if (isa<BitCastInst>(CI))
8620             return new BitCastInst(NGEP, CI.getType());
8621           assert(isa<PtrToIntInst>(CI));
8622           return new PtrToIntInst(NGEP, CI.getType());
8623         }
8624       }      
8625     }
8626   }
8627     
8628   return commonCastTransforms(CI);
8629 }
8630
8631 /// commonIntCastTransforms - This function implements the common transforms
8632 /// for trunc, zext, and sext.
8633 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8634   if (Instruction *Result = commonCastTransforms(CI))
8635     return Result;
8636
8637   Value *Src = CI.getOperand(0);
8638   const Type *SrcTy = Src->getType();
8639   const Type *DestTy = CI.getType();
8640   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8641   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8642
8643   // See if we can simplify any instructions used by the LHS whose sole 
8644   // purpose is to compute bits we don't care about.
8645   if (SimplifyDemandedInstructionBits(CI))
8646     return &CI;
8647
8648   // If the source isn't an instruction or has more than one use then we
8649   // can't do anything more. 
8650   Instruction *SrcI = dyn_cast<Instruction>(Src);
8651   if (!SrcI || !Src->hasOneUse())
8652     return 0;
8653
8654   // Attempt to propagate the cast into the instruction for int->int casts.
8655   int NumCastsRemoved = 0;
8656   // Only do this if the dest type is a simple type, don't convert the
8657   // expression tree to something weird like i93 unless the source is also
8658   // strange.
8659   if ((isa<VectorType>(DestTy) ||
8660        ShouldChangeType(SrcI->getType(), DestTy, TD)) &&
8661       CanEvaluateInDifferentType(SrcI, DestTy,
8662                                  CI.getOpcode(), NumCastsRemoved)) {
8663     // If this cast is a truncate, evaluting in a different type always
8664     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8665     // we need to do an AND to maintain the clear top-part of the computation,
8666     // so we require that the input have eliminated at least one cast.  If this
8667     // is a sign extension, we insert two new casts (to do the extension) so we
8668     // require that two casts have been eliminated.
8669     bool DoXForm = false;
8670     bool JustReplace = false;
8671     switch (CI.getOpcode()) {
8672     default:
8673       // All the others use floating point so we shouldn't actually 
8674       // get here because of the check above.
8675       llvm_unreachable("Unknown cast type");
8676     case Instruction::Trunc:
8677       DoXForm = true;
8678       break;
8679     case Instruction::ZExt: {
8680       DoXForm = NumCastsRemoved >= 1;
8681       
8682       if (!DoXForm && 0) {
8683         // If it's unnecessary to issue an AND to clear the high bits, it's
8684         // always profitable to do this xform.
8685         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8686         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8687         if (MaskedValueIsZero(TryRes, Mask))
8688           return ReplaceInstUsesWith(CI, TryRes);
8689         
8690         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8691           if (TryI->use_empty())
8692             EraseInstFromFunction(*TryI);
8693       }
8694       break;
8695     }
8696     case Instruction::SExt: {
8697       DoXForm = NumCastsRemoved >= 2;
8698       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8699         // If we do not have to emit the truncate + sext pair, then it's always
8700         // profitable to do this xform.
8701         //
8702         // It's not safe to eliminate the trunc + sext pair if one of the
8703         // eliminated cast is a truncate. e.g.
8704         // t2 = trunc i32 t1 to i16
8705         // t3 = sext i16 t2 to i32
8706         // !=
8707         // i32 t1
8708         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8709         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8710         if (NumSignBits > (DestBitSize - SrcBitSize))
8711           return ReplaceInstUsesWith(CI, TryRes);
8712         
8713         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8714           if (TryI->use_empty())
8715             EraseInstFromFunction(*TryI);
8716       }
8717       break;
8718     }
8719     }
8720     
8721     if (DoXForm) {
8722       DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8723             " to avoid cast: " << CI);
8724       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8725                                            CI.getOpcode() == Instruction::SExt);
8726       if (JustReplace)
8727         // Just replace this cast with the result.
8728         return ReplaceInstUsesWith(CI, Res);
8729
8730       assert(Res->getType() == DestTy);
8731       switch (CI.getOpcode()) {
8732       default: llvm_unreachable("Unknown cast type!");
8733       case Instruction::Trunc:
8734         // Just replace this cast with the result.
8735         return ReplaceInstUsesWith(CI, Res);
8736       case Instruction::ZExt: {
8737         assert(SrcBitSize < DestBitSize && "Not a zext?");
8738
8739         // If the high bits are already zero, just replace this cast with the
8740         // result.
8741         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8742         if (MaskedValueIsZero(Res, Mask))
8743           return ReplaceInstUsesWith(CI, Res);
8744
8745         // We need to emit an AND to clear the high bits.
8746         Constant *C = ConstantInt::get(*Context, 
8747                                  APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8748         return BinaryOperator::CreateAnd(Res, C);
8749       }
8750       case Instruction::SExt: {
8751         // If the high bits are already filled with sign bit, just replace this
8752         // cast with the result.
8753         unsigned NumSignBits = ComputeNumSignBits(Res);
8754         if (NumSignBits > (DestBitSize - SrcBitSize))
8755           return ReplaceInstUsesWith(CI, Res);
8756
8757         // We need to emit a cast to truncate, then a cast to sext.
8758         return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
8759       }
8760       }
8761     }
8762   }
8763   
8764   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8765   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8766
8767   switch (SrcI->getOpcode()) {
8768   case Instruction::Add:
8769   case Instruction::Mul:
8770   case Instruction::And:
8771   case Instruction::Or:
8772   case Instruction::Xor:
8773     // If we are discarding information, rewrite.
8774     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8775       // Don't insert two casts unless at least one can be eliminated.
8776       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8777           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8778         Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8779         Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8780         return BinaryOperator::Create(
8781             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8782       }
8783     }
8784
8785     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8786     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8787         SrcI->getOpcode() == Instruction::Xor &&
8788         Op1 == ConstantInt::getTrue(*Context) &&
8789         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8790       Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
8791       return BinaryOperator::CreateXor(New,
8792                                       ConstantInt::get(CI.getType(), 1));
8793     }
8794     break;
8795
8796   case Instruction::Shl: {
8797     // Canonicalize trunc inside shl, if we can.
8798     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8799     if (CI && DestBitSize < SrcBitSize &&
8800         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8801       Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8802       Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8803       return BinaryOperator::CreateShl(Op0c, Op1c);
8804     }
8805     break;
8806   }
8807   }
8808   return 0;
8809 }
8810
8811 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8812   if (Instruction *Result = commonIntCastTransforms(CI))
8813     return Result;
8814   
8815   Value *Src = CI.getOperand(0);
8816   const Type *Ty = CI.getType();
8817   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8818   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8819
8820   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8821   if (DestBitWidth == 1) {
8822     Constant *One = ConstantInt::get(Src->getType(), 1);
8823     Src = Builder->CreateAnd(Src, One, "tmp");
8824     Value *Zero = Constant::getNullValue(Src->getType());
8825     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8826   }
8827
8828   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8829   ConstantInt *ShAmtV = 0;
8830   Value *ShiftOp = 0;
8831   if (Src->hasOneUse() &&
8832       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8833     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8834     
8835     // Get a mask for the bits shifting in.
8836     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8837     if (MaskedValueIsZero(ShiftOp, Mask)) {
8838       if (ShAmt >= DestBitWidth)        // All zeros.
8839         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8840       
8841       // Okay, we can shrink this.  Truncate the input, then return a new
8842       // shift.
8843       Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
8844       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8845       return BinaryOperator::CreateLShr(V1, V2);
8846     }
8847   }
8848  
8849   return 0;
8850 }
8851
8852 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8853 /// in order to eliminate the icmp.
8854 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8855                                              bool DoXform) {
8856   // If we are just checking for a icmp eq of a single bit and zext'ing it
8857   // to an integer, then shift the bit to the appropriate place and then
8858   // cast to integer to avoid the comparison.
8859   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8860     const APInt &Op1CV = Op1C->getValue();
8861       
8862     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8863     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8864     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8865         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8866       if (!DoXform) return ICI;
8867
8868       Value *In = ICI->getOperand(0);
8869       Value *Sh = ConstantInt::get(In->getType(),
8870                                    In->getType()->getScalarSizeInBits()-1);
8871       In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
8872       if (In->getType() != CI.getType())
8873         In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
8874
8875       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8876         Constant *One = ConstantInt::get(In->getType(), 1);
8877         In = Builder->CreateXor(In, One, In->getName()+".not");
8878       }
8879
8880       return ReplaceInstUsesWith(CI, In);
8881     }
8882       
8883       
8884       
8885     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8886     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8887     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8888     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8889     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8890     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8891     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8892     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8893     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8894         // This only works for EQ and NE
8895         ICI->isEquality()) {
8896       // If Op1C some other power of two, convert:
8897       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8898       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8899       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8900       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8901         
8902       APInt KnownZeroMask(~KnownZero);
8903       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8904         if (!DoXform) return ICI;
8905
8906         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8907         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8908           // (X&4) == 2 --> false
8909           // (X&4) != 2 --> true
8910           Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8911           Res = ConstantExpr::getZExt(Res, CI.getType());
8912           return ReplaceInstUsesWith(CI, Res);
8913         }
8914           
8915         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8916         Value *In = ICI->getOperand(0);
8917         if (ShiftAmt) {
8918           // Perform a logical shr by shiftamt.
8919           // Insert the shift to put the result in the low bit.
8920           In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8921                                    In->getName()+".lobit");
8922         }
8923           
8924         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8925           Constant *One = ConstantInt::get(In->getType(), 1);
8926           In = Builder->CreateXor(In, One, "tmp");
8927         }
8928           
8929         if (CI.getType() == In->getType())
8930           return ReplaceInstUsesWith(CI, In);
8931         else
8932           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8933       }
8934     }
8935   }
8936
8937   // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
8938   // It is also profitable to transform icmp eq into not(xor(A, B)) because that
8939   // may lead to additional simplifications.
8940   if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
8941     if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
8942       uint32_t BitWidth = ITy->getBitWidth();
8943       Value *LHS = ICI->getOperand(0);
8944       Value *RHS = ICI->getOperand(1);
8945
8946       APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
8947       APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
8948       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8949       ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
8950       ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
8951
8952       if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
8953         APInt KnownBits = KnownZeroLHS | KnownOneLHS;
8954         APInt UnknownBit = ~KnownBits;
8955         if (UnknownBit.countPopulation() == 1) {
8956           if (!DoXform) return ICI;
8957
8958           Value *Result = Builder->CreateXor(LHS, RHS);
8959
8960           // Mask off any bits that are set and won't be shifted away.
8961           if (KnownOneLHS.uge(UnknownBit))
8962             Result = Builder->CreateAnd(Result,
8963                                         ConstantInt::get(ITy, UnknownBit));
8964
8965           // Shift the bit we're testing down to the lsb.
8966           Result = Builder->CreateLShr(
8967                Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
8968
8969           if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8970             Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
8971           Result->takeName(ICI);
8972           return ReplaceInstUsesWith(CI, Result);
8973         }
8974       }
8975     }
8976   }
8977
8978   return 0;
8979 }
8980
8981 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8982   // If one of the common conversion will work ..
8983   if (Instruction *Result = commonIntCastTransforms(CI))
8984     return Result;
8985
8986   Value *Src = CI.getOperand(0);
8987
8988   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8989   // types and if the sizes are just right we can convert this into a logical
8990   // 'and' which will be much cheaper than the pair of casts.
8991   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8992     // Get the sizes of the types involved.  We know that the intermediate type
8993     // will be smaller than A or C, but don't know the relation between A and C.
8994     Value *A = CSrc->getOperand(0);
8995     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8996     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8997     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8998     // If we're actually extending zero bits, then if
8999     // SrcSize <  DstSize: zext(a & mask)
9000     // SrcSize == DstSize: a & mask
9001     // SrcSize  > DstSize: trunc(a) & mask
9002     if (SrcSize < DstSize) {
9003       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
9004       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
9005       Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
9006       return new ZExtInst(And, CI.getType());
9007     }
9008     
9009     if (SrcSize == DstSize) {
9010       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
9011       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
9012                                                            AndValue));
9013     }
9014     if (SrcSize > DstSize) {
9015       Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
9016       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
9017       return BinaryOperator::CreateAnd(Trunc, 
9018                                        ConstantInt::get(Trunc->getType(),
9019                                                                AndValue));
9020     }
9021   }
9022
9023   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
9024     return transformZExtICmp(ICI, CI);
9025
9026   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
9027   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
9028     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
9029     // of the (zext icmp) will be transformed.
9030     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
9031     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
9032     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
9033         (transformZExtICmp(LHS, CI, false) ||
9034          transformZExtICmp(RHS, CI, false))) {
9035       Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
9036       Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
9037       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
9038     }
9039   }
9040
9041   // zext(trunc(t) & C) -> (t & zext(C)).
9042   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
9043     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
9044       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
9045         Value *TI0 = TI->getOperand(0);
9046         if (TI0->getType() == CI.getType())
9047           return
9048             BinaryOperator::CreateAnd(TI0,
9049                                 ConstantExpr::getZExt(C, CI.getType()));
9050       }
9051
9052   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
9053   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
9054     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
9055       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
9056         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
9057             And->getOperand(1) == C)
9058           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
9059             Value *TI0 = TI->getOperand(0);
9060             if (TI0->getType() == CI.getType()) {
9061               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
9062               Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
9063               return BinaryOperator::CreateXor(NewAnd, ZC);
9064             }
9065           }
9066
9067   return 0;
9068 }
9069
9070 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
9071   if (Instruction *I = commonIntCastTransforms(CI))
9072     return I;
9073   
9074   Value *Src = CI.getOperand(0);
9075   
9076   // Canonicalize sign-extend from i1 to a select.
9077   if (Src->getType() == Type::getInt1Ty(*Context))
9078     return SelectInst::Create(Src,
9079                               Constant::getAllOnesValue(CI.getType()),
9080                               Constant::getNullValue(CI.getType()));
9081
9082   // See if the value being truncated is already sign extended.  If so, just
9083   // eliminate the trunc/sext pair.
9084   if (Operator::getOpcode(Src) == Instruction::Trunc) {
9085     Value *Op = cast<User>(Src)->getOperand(0);
9086     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
9087     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
9088     unsigned DestBits = CI.getType()->getScalarSizeInBits();
9089     unsigned NumSignBits = ComputeNumSignBits(Op);
9090
9091     if (OpBits == DestBits) {
9092       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
9093       // bits, it is already ready.
9094       if (NumSignBits > DestBits-MidBits)
9095         return ReplaceInstUsesWith(CI, Op);
9096     } else if (OpBits < DestBits) {
9097       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
9098       // bits, just sext from i32.
9099       if (NumSignBits > OpBits-MidBits)
9100         return new SExtInst(Op, CI.getType(), "tmp");
9101     } else {
9102       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
9103       // bits, just truncate to i32.
9104       if (NumSignBits > OpBits-MidBits)
9105         return new TruncInst(Op, CI.getType(), "tmp");
9106     }
9107   }
9108
9109   // If the input is a shl/ashr pair of a same constant, then this is a sign
9110   // extension from a smaller value.  If we could trust arbitrary bitwidth
9111   // integers, we could turn this into a truncate to the smaller bit and then
9112   // use a sext for the whole extension.  Since we don't, look deeper and check
9113   // for a truncate.  If the source and dest are the same type, eliminate the
9114   // trunc and extend and just do shifts.  For example, turn:
9115   //   %a = trunc i32 %i to i8
9116   //   %b = shl i8 %a, 6
9117   //   %c = ashr i8 %b, 6
9118   //   %d = sext i8 %c to i32
9119   // into:
9120   //   %a = shl i32 %i, 30
9121   //   %d = ashr i32 %a, 30
9122   Value *A = 0;
9123   ConstantInt *BA = 0, *CA = 0;
9124   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
9125                         m_ConstantInt(CA))) &&
9126       BA == CA && isa<TruncInst>(A)) {
9127     Value *I = cast<TruncInst>(A)->getOperand(0);
9128     if (I->getType() == CI.getType()) {
9129       unsigned MidSize = Src->getType()->getScalarSizeInBits();
9130       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
9131       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
9132       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
9133       I = Builder->CreateShl(I, ShAmtV, CI.getName());
9134       return BinaryOperator::CreateAShr(I, ShAmtV);
9135     }
9136   }
9137   
9138   return 0;
9139 }
9140
9141 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
9142 /// in the specified FP type without changing its value.
9143 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
9144                               LLVMContext *Context) {
9145   bool losesInfo;
9146   APFloat F = CFP->getValueAPF();
9147   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
9148   if (!losesInfo)
9149     return ConstantFP::get(*Context, F);
9150   return 0;
9151 }
9152
9153 /// LookThroughFPExtensions - If this is an fp extension instruction, look
9154 /// through it until we get the source value.
9155 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
9156   if (Instruction *I = dyn_cast<Instruction>(V))
9157     if (I->getOpcode() == Instruction::FPExt)
9158       return LookThroughFPExtensions(I->getOperand(0), Context);
9159   
9160   // If this value is a constant, return the constant in the smallest FP type
9161   // that can accurately represent it.  This allows us to turn
9162   // (float)((double)X+2.0) into x+2.0f.
9163   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
9164     if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
9165       return V;  // No constant folding of this.
9166     // See if the value can be truncated to float and then reextended.
9167     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
9168       return V;
9169     if (CFP->getType() == Type::getDoubleTy(*Context))
9170       return V;  // Won't shrink.
9171     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
9172       return V;
9173     // Don't try to shrink to various long double types.
9174   }
9175   
9176   return V;
9177 }
9178
9179 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
9180   if (Instruction *I = commonCastTransforms(CI))
9181     return I;
9182   
9183   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
9184   // smaller than the destination type, we can eliminate the truncate by doing
9185   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
9186   // many builtins (sqrt, etc).
9187   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
9188   if (OpI && OpI->hasOneUse()) {
9189     switch (OpI->getOpcode()) {
9190     default: break;
9191     case Instruction::FAdd:
9192     case Instruction::FSub:
9193     case Instruction::FMul:
9194     case Instruction::FDiv:
9195     case Instruction::FRem:
9196       const Type *SrcTy = OpI->getType();
9197       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
9198       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
9199       if (LHSTrunc->getType() != SrcTy && 
9200           RHSTrunc->getType() != SrcTy) {
9201         unsigned DstSize = CI.getType()->getScalarSizeInBits();
9202         // If the source types were both smaller than the destination type of
9203         // the cast, do this xform.
9204         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
9205             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
9206           LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
9207           RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
9208           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
9209         }
9210       }
9211       break;  
9212     }
9213   }
9214   return 0;
9215 }
9216
9217 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
9218   return commonCastTransforms(CI);
9219 }
9220
9221 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
9222   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
9223   if (OpI == 0)
9224     return commonCastTransforms(FI);
9225
9226   // fptoui(uitofp(X)) --> X
9227   // fptoui(sitofp(X)) --> X
9228   // This is safe if the intermediate type has enough bits in its mantissa to
9229   // accurately represent all values of X.  For example, do not do this with
9230   // i64->float->i64.  This is also safe for sitofp case, because any negative
9231   // 'X' value would cause an undefined result for the fptoui. 
9232   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
9233       OpI->getOperand(0)->getType() == FI.getType() &&
9234       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
9235                     OpI->getType()->getFPMantissaWidth())
9236     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
9237
9238   return commonCastTransforms(FI);
9239 }
9240
9241 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
9242   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
9243   if (OpI == 0)
9244     return commonCastTransforms(FI);
9245   
9246   // fptosi(sitofp(X)) --> X
9247   // fptosi(uitofp(X)) --> X
9248   // This is safe if the intermediate type has enough bits in its mantissa to
9249   // accurately represent all values of X.  For example, do not do this with
9250   // i64->float->i64.  This is also safe for sitofp case, because any negative
9251   // 'X' value would cause an undefined result for the fptoui. 
9252   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
9253       OpI->getOperand(0)->getType() == FI.getType() &&
9254       (int)FI.getType()->getScalarSizeInBits() <=
9255                     OpI->getType()->getFPMantissaWidth())
9256     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
9257   
9258   return commonCastTransforms(FI);
9259 }
9260
9261 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
9262   return commonCastTransforms(CI);
9263 }
9264
9265 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
9266   return commonCastTransforms(CI);
9267 }
9268
9269 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
9270   // If the destination integer type is smaller than the intptr_t type for
9271   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
9272   // trunc to be exposed to other transforms.  Don't do this for extending
9273   // ptrtoint's, because we don't know if the target sign or zero extends its
9274   // pointers.
9275   if (TD &&
9276       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
9277     Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
9278                                        TD->getIntPtrType(CI.getContext()),
9279                                        "tmp");
9280     return new TruncInst(P, CI.getType());
9281   }
9282   
9283   return commonPointerCastTransforms(CI);
9284 }
9285
9286 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
9287   // If the source integer type is larger than the intptr_t type for
9288   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
9289   // allows the trunc to be exposed to other transforms.  Don't do this for
9290   // extending inttoptr's, because we don't know if the target sign or zero
9291   // extends to pointers.
9292   if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
9293       TD->getPointerSizeInBits()) {
9294     Value *P = Builder->CreateTrunc(CI.getOperand(0),
9295                                     TD->getIntPtrType(CI.getContext()), "tmp");
9296     return new IntToPtrInst(P, CI.getType());
9297   }
9298   
9299   if (Instruction *I = commonCastTransforms(CI))
9300     return I;
9301
9302   return 0;
9303 }
9304
9305 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
9306   // If the operands are integer typed then apply the integer transforms,
9307   // otherwise just apply the common ones.
9308   Value *Src = CI.getOperand(0);
9309   const Type *SrcTy = Src->getType();
9310   const Type *DestTy = CI.getType();
9311
9312   if (isa<PointerType>(SrcTy)) {
9313     if (Instruction *I = commonPointerCastTransforms(CI))
9314       return I;
9315   } else {
9316     if (Instruction *Result = commonCastTransforms(CI))
9317       return Result;
9318   }
9319
9320
9321   // Get rid of casts from one type to the same type. These are useless and can
9322   // be replaced by the operand.
9323   if (DestTy == Src->getType())
9324     return ReplaceInstUsesWith(CI, Src);
9325
9326   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
9327     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
9328     const Type *DstElTy = DstPTy->getElementType();
9329     const Type *SrcElTy = SrcPTy->getElementType();
9330     
9331     // If the address spaces don't match, don't eliminate the bitcast, which is
9332     // required for changing types.
9333     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9334       return 0;
9335     
9336     // If we are casting a alloca to a pointer to a type of the same
9337     // size, rewrite the allocation instruction to allocate the "right" type.
9338     // There is no need to modify malloc calls because it is their bitcast that
9339     // needs to be cleaned up.
9340     if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
9341       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9342         return V;
9343     
9344     // If the source and destination are pointers, and this cast is equivalent
9345     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
9346     // This can enhance SROA and other transforms that want type-safe pointers.
9347     Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
9348     unsigned NumZeros = 0;
9349     while (SrcElTy != DstElTy && 
9350            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9351            SrcElTy->getNumContainedTypes() /* not "{}" */) {
9352       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9353       ++NumZeros;
9354     }
9355
9356     // If we found a path from the src to dest, create the getelementptr now.
9357     if (SrcElTy == DstElTy) {
9358       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
9359       return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
9360                                                ((Instruction*) NULL));
9361     }
9362   }
9363
9364   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9365     if (DestVTy->getNumElements() == 1) {
9366       if (!isa<VectorType>(SrcTy)) {
9367         Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
9368         return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
9369                             Constant::getNullValue(Type::getInt32Ty(*Context)));
9370       }
9371       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9372     }
9373   }
9374
9375   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9376     if (SrcVTy->getNumElements() == 1) {
9377       if (!isa<VectorType>(DestTy)) {
9378         Value *Elem = 
9379           Builder->CreateExtractElement(Src,
9380                             Constant::getNullValue(Type::getInt32Ty(*Context)));
9381         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9382       }
9383     }
9384   }
9385
9386   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9387     if (SVI->hasOneUse()) {
9388       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
9389       // a bitconvert to a vector with the same # elts.
9390       if (isa<VectorType>(DestTy) && 
9391           cast<VectorType>(DestTy)->getNumElements() ==
9392                 SVI->getType()->getNumElements() &&
9393           SVI->getType()->getNumElements() ==
9394             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9395         CastInst *Tmp;
9396         // If either of the operands is a cast from CI.getType(), then
9397         // evaluating the shuffle in the casted destination's type will allow
9398         // us to eliminate at least one cast.
9399         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
9400              Tmp->getOperand(0)->getType() == DestTy) ||
9401             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
9402              Tmp->getOperand(0)->getType() == DestTy)) {
9403           Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
9404           Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
9405           // Return a new shuffle vector.  Use the same element ID's, as we
9406           // know the vector types match #elts.
9407           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9408         }
9409       }
9410     }
9411   }
9412   return 0;
9413 }
9414
9415 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9416 ///   %C = or %A, %B
9417 ///   %D = select %cond, %C, %A
9418 /// into:
9419 ///   %C = select %cond, %B, 0
9420 ///   %D = or %A, %C
9421 ///
9422 /// Assuming that the specified instruction is an operand to the select, return
9423 /// a bitmask indicating which operands of this instruction are foldable if they
9424 /// equal the other incoming value of the select.
9425 ///
9426 static unsigned GetSelectFoldableOperands(Instruction *I) {
9427   switch (I->getOpcode()) {
9428   case Instruction::Add:
9429   case Instruction::Mul:
9430   case Instruction::And:
9431   case Instruction::Or:
9432   case Instruction::Xor:
9433     return 3;              // Can fold through either operand.
9434   case Instruction::Sub:   // Can only fold on the amount subtracted.
9435   case Instruction::Shl:   // Can only fold on the shift amount.
9436   case Instruction::LShr:
9437   case Instruction::AShr:
9438     return 1;
9439   default:
9440     return 0;              // Cannot fold
9441   }
9442 }
9443
9444 /// GetSelectFoldableConstant - For the same transformation as the previous
9445 /// function, return the identity constant that goes into the select.
9446 static Constant *GetSelectFoldableConstant(Instruction *I,
9447                                            LLVMContext *Context) {
9448   switch (I->getOpcode()) {
9449   default: llvm_unreachable("This cannot happen!");
9450   case Instruction::Add:
9451   case Instruction::Sub:
9452   case Instruction::Or:
9453   case Instruction::Xor:
9454   case Instruction::Shl:
9455   case Instruction::LShr:
9456   case Instruction::AShr:
9457     return Constant::getNullValue(I->getType());
9458   case Instruction::And:
9459     return Constant::getAllOnesValue(I->getType());
9460   case Instruction::Mul:
9461     return ConstantInt::get(I->getType(), 1);
9462   }
9463 }
9464
9465 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9466 /// have the same opcode and only one use each.  Try to simplify this.
9467 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9468                                           Instruction *FI) {
9469   if (TI->getNumOperands() == 1) {
9470     // If this is a non-volatile load or a cast from the same type,
9471     // merge.
9472     if (TI->isCast()) {
9473       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9474         return 0;
9475     } else {
9476       return 0;  // unknown unary op.
9477     }
9478
9479     // Fold this by inserting a select from the input values.
9480     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9481                                           FI->getOperand(0), SI.getName()+".v");
9482     InsertNewInstBefore(NewSI, SI);
9483     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9484                             TI->getType());
9485   }
9486
9487   // Only handle binary operators here.
9488   if (!isa<BinaryOperator>(TI))
9489     return 0;
9490
9491   // Figure out if the operations have any operands in common.
9492   Value *MatchOp, *OtherOpT, *OtherOpF;
9493   bool MatchIsOpZero;
9494   if (TI->getOperand(0) == FI->getOperand(0)) {
9495     MatchOp  = TI->getOperand(0);
9496     OtherOpT = TI->getOperand(1);
9497     OtherOpF = FI->getOperand(1);
9498     MatchIsOpZero = true;
9499   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9500     MatchOp  = TI->getOperand(1);
9501     OtherOpT = TI->getOperand(0);
9502     OtherOpF = FI->getOperand(0);
9503     MatchIsOpZero = false;
9504   } else if (!TI->isCommutative()) {
9505     return 0;
9506   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9507     MatchOp  = TI->getOperand(0);
9508     OtherOpT = TI->getOperand(1);
9509     OtherOpF = FI->getOperand(0);
9510     MatchIsOpZero = true;
9511   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9512     MatchOp  = TI->getOperand(1);
9513     OtherOpT = TI->getOperand(0);
9514     OtherOpF = FI->getOperand(1);
9515     MatchIsOpZero = true;
9516   } else {
9517     return 0;
9518   }
9519
9520   // If we reach here, they do have operations in common.
9521   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9522                                          OtherOpF, SI.getName()+".v");
9523   InsertNewInstBefore(NewSI, SI);
9524
9525   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9526     if (MatchIsOpZero)
9527       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9528     else
9529       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9530   }
9531   llvm_unreachable("Shouldn't get here");
9532   return 0;
9533 }
9534
9535 static bool isSelect01(Constant *C1, Constant *C2) {
9536   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9537   if (!C1I)
9538     return false;
9539   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9540   if (!C2I)
9541     return false;
9542   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9543 }
9544
9545 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9546 /// facilitate further optimization.
9547 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9548                                             Value *FalseVal) {
9549   // See the comment above GetSelectFoldableOperands for a description of the
9550   // transformation we are doing here.
9551   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9552     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9553         !isa<Constant>(FalseVal)) {
9554       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9555         unsigned OpToFold = 0;
9556         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9557           OpToFold = 1;
9558         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9559           OpToFold = 2;
9560         }
9561
9562         if (OpToFold) {
9563           Constant *C = GetSelectFoldableConstant(TVI, Context);
9564           Value *OOp = TVI->getOperand(2-OpToFold);
9565           // Avoid creating select between 2 constants unless it's selecting
9566           // between 0 and 1.
9567           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9568             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9569             InsertNewInstBefore(NewSel, SI);
9570             NewSel->takeName(TVI);
9571             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9572               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9573             llvm_unreachable("Unknown instruction!!");
9574           }
9575         }
9576       }
9577     }
9578   }
9579
9580   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9581     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9582         !isa<Constant>(TrueVal)) {
9583       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9584         unsigned OpToFold = 0;
9585         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9586           OpToFold = 1;
9587         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9588           OpToFold = 2;
9589         }
9590
9591         if (OpToFold) {
9592           Constant *C = GetSelectFoldableConstant(FVI, Context);
9593           Value *OOp = FVI->getOperand(2-OpToFold);
9594           // Avoid creating select between 2 constants unless it's selecting
9595           // between 0 and 1.
9596           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9597             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9598             InsertNewInstBefore(NewSel, SI);
9599             NewSel->takeName(FVI);
9600             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9601               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9602             llvm_unreachable("Unknown instruction!!");
9603           }
9604         }
9605       }
9606     }
9607   }
9608
9609   return 0;
9610 }
9611
9612 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9613 /// ICmpInst as its first operand.
9614 ///
9615 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9616                                                    ICmpInst *ICI) {
9617   bool Changed = false;
9618   ICmpInst::Predicate Pred = ICI->getPredicate();
9619   Value *CmpLHS = ICI->getOperand(0);
9620   Value *CmpRHS = ICI->getOperand(1);
9621   Value *TrueVal = SI.getTrueValue();
9622   Value *FalseVal = SI.getFalseValue();
9623
9624   // Check cases where the comparison is with a constant that
9625   // can be adjusted to fit the min/max idiom. We may edit ICI in
9626   // place here, so make sure the select is the only user.
9627   if (ICI->hasOneUse())
9628     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9629       switch (Pred) {
9630       default: break;
9631       case ICmpInst::ICMP_ULT:
9632       case ICmpInst::ICMP_SLT: {
9633         // X < MIN ? T : F  -->  F
9634         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9635           return ReplaceInstUsesWith(SI, FalseVal);
9636         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9637         Constant *AdjustedRHS = SubOne(CI);
9638         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9639             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9640           Pred = ICmpInst::getSwappedPredicate(Pred);
9641           CmpRHS = AdjustedRHS;
9642           std::swap(FalseVal, TrueVal);
9643           ICI->setPredicate(Pred);
9644           ICI->setOperand(1, CmpRHS);
9645           SI.setOperand(1, TrueVal);
9646           SI.setOperand(2, FalseVal);
9647           Changed = true;
9648         }
9649         break;
9650       }
9651       case ICmpInst::ICMP_UGT:
9652       case ICmpInst::ICMP_SGT: {
9653         // X > MAX ? T : F  -->  F
9654         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9655           return ReplaceInstUsesWith(SI, FalseVal);
9656         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9657         Constant *AdjustedRHS = AddOne(CI);
9658         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9659             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9660           Pred = ICmpInst::getSwappedPredicate(Pred);
9661           CmpRHS = AdjustedRHS;
9662           std::swap(FalseVal, TrueVal);
9663           ICI->setPredicate(Pred);
9664           ICI->setOperand(1, CmpRHS);
9665           SI.setOperand(1, TrueVal);
9666           SI.setOperand(2, FalseVal);
9667           Changed = true;
9668         }
9669         break;
9670       }
9671       }
9672
9673       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9674       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9675       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9676       if (match(TrueVal, m_ConstantInt<-1>()) &&
9677           match(FalseVal, m_ConstantInt<0>()))
9678         Pred = ICI->getPredicate();
9679       else if (match(TrueVal, m_ConstantInt<0>()) &&
9680                match(FalseVal, m_ConstantInt<-1>()))
9681         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9682       
9683       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9684         // If we are just checking for a icmp eq of a single bit and zext'ing it
9685         // to an integer, then shift the bit to the appropriate place and then
9686         // cast to integer to avoid the comparison.
9687         const APInt &Op1CV = CI->getValue();
9688     
9689         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9690         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9691         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9692             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9693           Value *In = ICI->getOperand(0);
9694           Value *Sh = ConstantInt::get(In->getType(),
9695                                        In->getType()->getScalarSizeInBits()-1);
9696           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9697                                                         In->getName()+".lobit"),
9698                                    *ICI);
9699           if (In->getType() != SI.getType())
9700             In = CastInst::CreateIntegerCast(In, SI.getType(),
9701                                              true/*SExt*/, "tmp", ICI);
9702     
9703           if (Pred == ICmpInst::ICMP_SGT)
9704             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9705                                        In->getName()+".not"), *ICI);
9706     
9707           return ReplaceInstUsesWith(SI, In);
9708         }
9709       }
9710     }
9711
9712   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9713     // Transform (X == Y) ? X : Y  -> Y
9714     if (Pred == ICmpInst::ICMP_EQ)
9715       return ReplaceInstUsesWith(SI, FalseVal);
9716     // Transform (X != Y) ? X : Y  -> X
9717     if (Pred == ICmpInst::ICMP_NE)
9718       return ReplaceInstUsesWith(SI, TrueVal);
9719     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9720
9721   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9722     // Transform (X == Y) ? Y : X  -> X
9723     if (Pred == ICmpInst::ICMP_EQ)
9724       return ReplaceInstUsesWith(SI, FalseVal);
9725     // Transform (X != Y) ? Y : X  -> Y
9726     if (Pred == ICmpInst::ICMP_NE)
9727       return ReplaceInstUsesWith(SI, TrueVal);
9728     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9729   }
9730   return Changed ? &SI : 0;
9731 }
9732
9733
9734 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9735 /// PHI node (but the two may be in different blocks).  See if the true/false
9736 /// values (V) are live in all of the predecessor blocks of the PHI.  For
9737 /// example, cases like this cannot be mapped:
9738 ///
9739 ///   X = phi [ C1, BB1], [C2, BB2]
9740 ///   Y = add
9741 ///   Z = select X, Y, 0
9742 ///
9743 /// because Y is not live in BB1/BB2.
9744 ///
9745 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9746                                                    const SelectInst &SI) {
9747   // If the value is a non-instruction value like a constant or argument, it
9748   // can always be mapped.
9749   const Instruction *I = dyn_cast<Instruction>(V);
9750   if (I == 0) return true;
9751   
9752   // If V is a PHI node defined in the same block as the condition PHI, we can
9753   // map the arguments.
9754   const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9755   
9756   if (const PHINode *VP = dyn_cast<PHINode>(I))
9757     if (VP->getParent() == CondPHI->getParent())
9758       return true;
9759   
9760   // Otherwise, if the PHI and select are defined in the same block and if V is
9761   // defined in a different block, then we can transform it.
9762   if (SI.getParent() == CondPHI->getParent() &&
9763       I->getParent() != CondPHI->getParent())
9764     return true;
9765   
9766   // Otherwise we have a 'hard' case and we can't tell without doing more
9767   // detailed dominator based analysis, punt.
9768   return false;
9769 }
9770
9771 /// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
9772 ///   SPF2(SPF1(A, B), C) 
9773 Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
9774                                         SelectPatternFlavor SPF1,
9775                                         Value *A, Value *B,
9776                                         Instruction &Outer,
9777                                         SelectPatternFlavor SPF2, Value *C) {
9778   if (C == A || C == B) {
9779     // MAX(MAX(A, B), B) -> MAX(A, B)
9780     // MIN(MIN(a, b), a) -> MIN(a, b)
9781     if (SPF1 == SPF2)
9782       return ReplaceInstUsesWith(Outer, Inner);
9783     
9784     // MAX(MIN(a, b), a) -> a
9785     // MIN(MAX(a, b), a) -> a
9786     if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
9787         (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
9788         (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
9789         (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
9790       return ReplaceInstUsesWith(Outer, C);
9791   }
9792   
9793   // TODO: MIN(MIN(A, 23), 97)
9794   return 0;
9795 }
9796
9797
9798
9799
9800 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9801   Value *CondVal = SI.getCondition();
9802   Value *TrueVal = SI.getTrueValue();
9803   Value *FalseVal = SI.getFalseValue();
9804
9805   // select true, X, Y  -> X
9806   // select false, X, Y -> Y
9807   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9808     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9809
9810   // select C, X, X -> X
9811   if (TrueVal == FalseVal)
9812     return ReplaceInstUsesWith(SI, TrueVal);
9813
9814   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9815     return ReplaceInstUsesWith(SI, FalseVal);
9816   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9817     return ReplaceInstUsesWith(SI, TrueVal);
9818   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9819     if (isa<Constant>(TrueVal))
9820       return ReplaceInstUsesWith(SI, TrueVal);
9821     else
9822       return ReplaceInstUsesWith(SI, FalseVal);
9823   }
9824
9825   if (SI.getType() == Type::getInt1Ty(*Context)) {
9826     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9827       if (C->getZExtValue()) {
9828         // Change: A = select B, true, C --> A = or B, C
9829         return BinaryOperator::CreateOr(CondVal, FalseVal);
9830       } else {
9831         // Change: A = select B, false, C --> A = and !B, C
9832         Value *NotCond =
9833           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9834                                              "not."+CondVal->getName()), SI);
9835         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9836       }
9837     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9838       if (C->getZExtValue() == false) {
9839         // Change: A = select B, C, false --> A = and B, C
9840         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9841       } else {
9842         // Change: A = select B, C, true --> A = or !B, C
9843         Value *NotCond =
9844           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9845                                              "not."+CondVal->getName()), SI);
9846         return BinaryOperator::CreateOr(NotCond, TrueVal);
9847       }
9848     }
9849     
9850     // select a, b, a  -> a&b
9851     // select a, a, b  -> a|b
9852     if (CondVal == TrueVal)
9853       return BinaryOperator::CreateOr(CondVal, FalseVal);
9854     else if (CondVal == FalseVal)
9855       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9856   }
9857
9858   // Selecting between two integer constants?
9859   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9860     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9861       // select C, 1, 0 -> zext C to int
9862       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9863         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9864       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9865         // select C, 0, 1 -> zext !C to int
9866         Value *NotCond =
9867           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9868                                                "not."+CondVal->getName()), SI);
9869         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9870       }
9871
9872       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9873         // If one of the constants is zero (we know they can't both be) and we
9874         // have an icmp instruction with zero, and we have an 'and' with the
9875         // non-constant value, eliminate this whole mess.  This corresponds to
9876         // cases like this: ((X & 27) ? 27 : 0)
9877         if (TrueValC->isZero() || FalseValC->isZero())
9878           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9879               cast<Constant>(IC->getOperand(1))->isNullValue())
9880             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9881               if (ICA->getOpcode() == Instruction::And &&
9882                   isa<ConstantInt>(ICA->getOperand(1)) &&
9883                   (ICA->getOperand(1) == TrueValC ||
9884                    ICA->getOperand(1) == FalseValC) &&
9885                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9886                 // Okay, now we know that everything is set up, we just don't
9887                 // know whether we have a icmp_ne or icmp_eq and whether the 
9888                 // true or false val is the zero.
9889                 bool ShouldNotVal = !TrueValC->isZero();
9890                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9891                 Value *V = ICA;
9892                 if (ShouldNotVal)
9893                   V = InsertNewInstBefore(BinaryOperator::Create(
9894                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9895                 return ReplaceInstUsesWith(SI, V);
9896               }
9897       }
9898     }
9899
9900   // See if we are selecting two values based on a comparison of the two values.
9901   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9902     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9903       // Transform (X == Y) ? X : Y  -> Y
9904       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9905         // This is not safe in general for floating point:  
9906         // consider X== -0, Y== +0.
9907         // It becomes safe if either operand is a nonzero constant.
9908         ConstantFP *CFPt, *CFPf;
9909         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9910               !CFPt->getValueAPF().isZero()) ||
9911             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9912              !CFPf->getValueAPF().isZero()))
9913         return ReplaceInstUsesWith(SI, FalseVal);
9914       }
9915       // Transform (X != Y) ? X : Y  -> X
9916       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9917         return ReplaceInstUsesWith(SI, TrueVal);
9918       // NOTE: if we wanted to, this is where to detect MIN/MAX
9919
9920     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9921       // Transform (X == Y) ? Y : X  -> X
9922       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9923         // This is not safe in general for floating point:  
9924         // consider X== -0, Y== +0.
9925         // It becomes safe if either operand is a nonzero constant.
9926         ConstantFP *CFPt, *CFPf;
9927         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9928               !CFPt->getValueAPF().isZero()) ||
9929             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9930              !CFPf->getValueAPF().isZero()))
9931           return ReplaceInstUsesWith(SI, FalseVal);
9932       }
9933       // Transform (X != Y) ? Y : X  -> Y
9934       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9935         return ReplaceInstUsesWith(SI, TrueVal);
9936       // NOTE: if we wanted to, this is where to detect MIN/MAX
9937     }
9938     // NOTE: if we wanted to, this is where to detect ABS
9939   }
9940
9941   // See if we are selecting two values based on a comparison of the two values.
9942   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9943     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9944       return Result;
9945
9946   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9947     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9948       if (TI->hasOneUse() && FI->hasOneUse()) {
9949         Instruction *AddOp = 0, *SubOp = 0;
9950
9951         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9952         if (TI->getOpcode() == FI->getOpcode())
9953           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9954             return IV;
9955
9956         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9957         // even legal for FP.
9958         if ((TI->getOpcode() == Instruction::Sub &&
9959              FI->getOpcode() == Instruction::Add) ||
9960             (TI->getOpcode() == Instruction::FSub &&
9961              FI->getOpcode() == Instruction::FAdd)) {
9962           AddOp = FI; SubOp = TI;
9963         } else if ((FI->getOpcode() == Instruction::Sub &&
9964                     TI->getOpcode() == Instruction::Add) ||
9965                    (FI->getOpcode() == Instruction::FSub &&
9966                     TI->getOpcode() == Instruction::FAdd)) {
9967           AddOp = TI; SubOp = FI;
9968         }
9969
9970         if (AddOp) {
9971           Value *OtherAddOp = 0;
9972           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9973             OtherAddOp = AddOp->getOperand(1);
9974           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9975             OtherAddOp = AddOp->getOperand(0);
9976           }
9977
9978           if (OtherAddOp) {
9979             // So at this point we know we have (Y -> OtherAddOp):
9980             //        select C, (add X, Y), (sub X, Z)
9981             Value *NegVal;  // Compute -Z
9982             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9983               NegVal = ConstantExpr::getNeg(C);
9984             } else {
9985               NegVal = InsertNewInstBefore(
9986                     BinaryOperator::CreateNeg(SubOp->getOperand(1),
9987                                               "tmp"), SI);
9988             }
9989
9990             Value *NewTrueOp = OtherAddOp;
9991             Value *NewFalseOp = NegVal;
9992             if (AddOp != TI)
9993               std::swap(NewTrueOp, NewFalseOp);
9994             Instruction *NewSel =
9995               SelectInst::Create(CondVal, NewTrueOp,
9996                                  NewFalseOp, SI.getName() + ".p");
9997
9998             NewSel = InsertNewInstBefore(NewSel, SI);
9999             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
10000           }
10001         }
10002       }
10003
10004   // See if we can fold the select into one of our operands.
10005   if (SI.getType()->isInteger()) {
10006     if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
10007       return FoldI;
10008     
10009     // MAX(MAX(a, b), a) -> MAX(a, b)
10010     // MIN(MIN(a, b), a) -> MIN(a, b)
10011     // MAX(MIN(a, b), a) -> a
10012     // MIN(MAX(a, b), a) -> a
10013     Value *LHS, *RHS, *LHS2, *RHS2;
10014     if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
10015       if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
10016         if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2, 
10017                                           SI, SPF, RHS))
10018           return R;
10019       if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
10020         if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
10021                                           SI, SPF, LHS))
10022           return R;
10023     }
10024
10025     // TODO.
10026     // ABS(-X) -> ABS(X)
10027     // ABS(ABS(X)) -> ABS(X)
10028   }
10029
10030   // See if we can fold the select into a phi node if the condition is a select.
10031   if (isa<PHINode>(SI.getCondition())) 
10032     // The true/false values have to be live in the PHI predecessor's blocks.
10033     if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
10034         CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
10035       if (Instruction *NV = FoldOpIntoPhi(SI))
10036         return NV;
10037
10038   if (BinaryOperator::isNot(CondVal)) {
10039     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
10040     SI.setOperand(1, FalseVal);
10041     SI.setOperand(2, TrueVal);
10042     return &SI;
10043   }
10044
10045   return 0;
10046 }
10047
10048 /// EnforceKnownAlignment - If the specified pointer points to an object that
10049 /// we control, modify the object's alignment to PrefAlign. This isn't
10050 /// often possible though. If alignment is important, a more reliable approach
10051 /// is to simply align all global variables and allocation instructions to
10052 /// their preferred alignment from the beginning.
10053 ///
10054 static unsigned EnforceKnownAlignment(Value *V,
10055                                       unsigned Align, unsigned PrefAlign) {
10056
10057   User *U = dyn_cast<User>(V);
10058   if (!U) return Align;
10059
10060   switch (Operator::getOpcode(U)) {
10061   default: break;
10062   case Instruction::BitCast:
10063     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
10064   case Instruction::GetElementPtr: {
10065     // If all indexes are zero, it is just the alignment of the base pointer.
10066     bool AllZeroOperands = true;
10067     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
10068       if (!isa<Constant>(*i) ||
10069           !cast<Constant>(*i)->isNullValue()) {
10070         AllZeroOperands = false;
10071         break;
10072       }
10073
10074     if (AllZeroOperands) {
10075       // Treat this like a bitcast.
10076       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
10077     }
10078     break;
10079   }
10080   }
10081
10082   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
10083     // If there is a large requested alignment and we can, bump up the alignment
10084     // of the global.
10085     if (!GV->isDeclaration()) {
10086       if (GV->getAlignment() >= PrefAlign)
10087         Align = GV->getAlignment();
10088       else {
10089         GV->setAlignment(PrefAlign);
10090         Align = PrefAlign;
10091       }
10092     }
10093   } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
10094     // If there is a requested alignment and if this is an alloca, round up.
10095     if (AI->getAlignment() >= PrefAlign)
10096       Align = AI->getAlignment();
10097     else {
10098       AI->setAlignment(PrefAlign);
10099       Align = PrefAlign;
10100     }
10101   }
10102
10103   return Align;
10104 }
10105
10106 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
10107 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
10108 /// and it is more than the alignment of the ultimate object, see if we can
10109 /// increase the alignment of the ultimate object, making this check succeed.
10110 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
10111                                                   unsigned PrefAlign) {
10112   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
10113                       sizeof(PrefAlign) * CHAR_BIT;
10114   APInt Mask = APInt::getAllOnesValue(BitWidth);
10115   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
10116   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
10117   unsigned TrailZ = KnownZero.countTrailingOnes();
10118   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
10119
10120   if (PrefAlign > Align)
10121     Align = EnforceKnownAlignment(V, Align, PrefAlign);
10122   
10123     // We don't need to make any adjustment.
10124   return Align;
10125 }
10126
10127 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
10128   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
10129   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
10130   unsigned MinAlign = std::min(DstAlign, SrcAlign);
10131   unsigned CopyAlign = MI->getAlignment();
10132
10133   if (CopyAlign < MinAlign) {
10134     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 
10135                                              MinAlign, false));
10136     return MI;
10137   }
10138   
10139   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
10140   // load/store.
10141   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
10142   if (MemOpLength == 0) return 0;
10143   
10144   // Source and destination pointer types are always "i8*" for intrinsic.  See
10145   // if the size is something we can handle with a single primitive load/store.
10146   // A single load+store correctly handles overlapping memory in the memmove
10147   // case.
10148   unsigned Size = MemOpLength->getZExtValue();
10149   if (Size == 0) return MI;  // Delete this mem transfer.
10150   
10151   if (Size > 8 || (Size&(Size-1)))
10152     return 0;  // If not 1/2/4/8 bytes, exit.
10153   
10154   // Use an integer load+store unless we can find something better.
10155   Type *NewPtrTy =
10156                 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
10157   
10158   // Memcpy forces the use of i8* for the source and destination.  That means
10159   // that if you're using memcpy to move one double around, you'll get a cast
10160   // from double* to i8*.  We'd much rather use a double load+store rather than
10161   // an i64 load+store, here because this improves the odds that the source or
10162   // dest address will be promotable.  See if we can find a better type than the
10163   // integer datatype.
10164   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
10165     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
10166     if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
10167       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
10168       // down through these levels if so.
10169       while (!SrcETy->isSingleValueType()) {
10170         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
10171           if (STy->getNumElements() == 1)
10172             SrcETy = STy->getElementType(0);
10173           else
10174             break;
10175         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
10176           if (ATy->getNumElements() == 1)
10177             SrcETy = ATy->getElementType();
10178           else
10179             break;
10180         } else
10181           break;
10182       }
10183       
10184       if (SrcETy->isSingleValueType())
10185         NewPtrTy = PointerType::getUnqual(SrcETy);
10186     }
10187   }
10188   
10189   
10190   // If the memcpy/memmove provides better alignment info than we can
10191   // infer, use it.
10192   SrcAlign = std::max(SrcAlign, CopyAlign);
10193   DstAlign = std::max(DstAlign, CopyAlign);
10194   
10195   Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
10196   Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
10197   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
10198   InsertNewInstBefore(L, *MI);
10199   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
10200
10201   // Set the size of the copy to 0, it will be deleted on the next iteration.
10202   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
10203   return MI;
10204 }
10205
10206 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
10207   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
10208   if (MI->getAlignment() < Alignment) {
10209     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
10210                                              Alignment, false));
10211     return MI;
10212   }
10213   
10214   // Extract the length and alignment and fill if they are constant.
10215   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
10216   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
10217   if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
10218     return 0;
10219   uint64_t Len = LenC->getZExtValue();
10220   Alignment = MI->getAlignment();
10221   
10222   // If the length is zero, this is a no-op
10223   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
10224   
10225   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
10226   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
10227     const Type *ITy = IntegerType::get(*Context, Len*8);  // n=1 -> i8.
10228     
10229     Value *Dest = MI->getDest();
10230     Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
10231
10232     // Alignment 0 is identity for alignment 1 for memset, but not store.
10233     if (Alignment == 0) Alignment = 1;
10234     
10235     // Extract the fill value and store.
10236     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
10237     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
10238                                       Dest, false, Alignment), *MI);
10239     
10240     // Set the size of the copy to 0, it will be deleted on the next iteration.
10241     MI->setLength(Constant::getNullValue(LenC->getType()));
10242     return MI;
10243   }
10244
10245   return 0;
10246 }
10247
10248
10249 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
10250 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
10251 /// the heavy lifting.
10252 ///
10253 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
10254   if (isFreeCall(&CI))
10255     return visitFree(CI);
10256
10257   // If the caller function is nounwind, mark the call as nounwind, even if the
10258   // callee isn't.
10259   if (CI.getParent()->getParent()->doesNotThrow() &&
10260       !CI.doesNotThrow()) {
10261     CI.setDoesNotThrow();
10262     return &CI;
10263   }
10264   
10265   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
10266   if (!II) return visitCallSite(&CI);
10267   
10268   // Intrinsics cannot occur in an invoke, so handle them here instead of in
10269   // visitCallSite.
10270   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
10271     bool Changed = false;
10272
10273     // memmove/cpy/set of zero bytes is a noop.
10274     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
10275       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
10276
10277       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
10278         if (CI->getZExtValue() == 1) {
10279           // Replace the instruction with just byte operations.  We would
10280           // transform other cases to loads/stores, but we don't know if
10281           // alignment is sufficient.
10282         }
10283     }
10284
10285     // If we have a memmove and the source operation is a constant global,
10286     // then the source and dest pointers can't alias, so we can change this
10287     // into a call to memcpy.
10288     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
10289       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
10290         if (GVSrc->isConstant()) {
10291           Module *M = CI.getParent()->getParent()->getParent();
10292           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
10293           const Type *Tys[1];
10294           Tys[0] = CI.getOperand(3)->getType();
10295           CI.setOperand(0, 
10296                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
10297           Changed = true;
10298         }
10299     }
10300
10301     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
10302       // memmove(x,x,size) -> noop.
10303       if (MTI->getSource() == MTI->getDest())
10304         return EraseInstFromFunction(CI);
10305     }
10306
10307     // If we can determine a pointer alignment that is bigger than currently
10308     // set, update the alignment.
10309     if (isa<MemTransferInst>(MI)) {
10310       if (Instruction *I = SimplifyMemTransfer(MI))
10311         return I;
10312     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
10313       if (Instruction *I = SimplifyMemSet(MSI))
10314         return I;
10315     }
10316           
10317     if (Changed) return II;
10318   }
10319   
10320   switch (II->getIntrinsicID()) {
10321   default: break;
10322   case Intrinsic::bswap:
10323     // bswap(bswap(x)) -> x
10324     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
10325       if (Operand->getIntrinsicID() == Intrinsic::bswap)
10326         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
10327       
10328     // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
10329     if (TruncInst *TI = dyn_cast<TruncInst>(II->getOperand(1))) {
10330       if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
10331         if (Operand->getIntrinsicID() == Intrinsic::bswap) {
10332           unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
10333                        TI->getType()->getPrimitiveSizeInBits();
10334           Value *CV = ConstantInt::get(Operand->getType(), C);
10335           Value *V = Builder->CreateLShr(Operand->getOperand(1), CV);
10336           return new TruncInst(V, TI->getType());
10337         }
10338     }
10339       
10340     break;
10341   case Intrinsic::powi:
10342     if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getOperand(2))) {
10343       // powi(x, 0) -> 1.0
10344       if (Power->isZero())
10345         return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
10346       // powi(x, 1) -> x
10347       if (Power->isOne())
10348         return ReplaceInstUsesWith(CI, II->getOperand(1));
10349       // powi(x, -1) -> 1/x
10350       if (Power->isAllOnesValue())
10351         return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
10352                                           II->getOperand(1));
10353     }
10354     break;
10355       
10356   case Intrinsic::uadd_with_overflow: {
10357     Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
10358     const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
10359     uint32_t BitWidth = IT->getBitWidth();
10360     APInt Mask = APInt::getSignBit(BitWidth);
10361     APInt LHSKnownZero(BitWidth, 0);
10362     APInt LHSKnownOne(BitWidth, 0);
10363     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
10364     bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
10365     bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
10366
10367     if (LHSKnownNegative || LHSKnownPositive) {
10368       APInt RHSKnownZero(BitWidth, 0);
10369       APInt RHSKnownOne(BitWidth, 0);
10370       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
10371       bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
10372       bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
10373       if (LHSKnownNegative && RHSKnownNegative) {
10374         // The sign bit is set in both cases: this MUST overflow.
10375         // Create a simple add instruction, and insert it into the struct.
10376         Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
10377         Worklist.Add(Add);
10378         Constant *V[] = {
10379           UndefValue::get(LHS->getType()), ConstantInt::getTrue(*Context)
10380         };
10381         Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10382         return InsertValueInst::Create(Struct, Add, 0);
10383       }
10384       
10385       if (LHSKnownPositive && RHSKnownPositive) {
10386         // The sign bit is clear in both cases: this CANNOT overflow.
10387         // Create a simple add instruction, and insert it into the struct.
10388         Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
10389         Worklist.Add(Add);
10390         Constant *V[] = {
10391           UndefValue::get(LHS->getType()), ConstantInt::getFalse(*Context)
10392         };
10393         Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10394         return InsertValueInst::Create(Struct, Add, 0);
10395       }
10396     }
10397   }
10398   // FALL THROUGH uadd into sadd
10399   case Intrinsic::sadd_with_overflow:
10400     // Canonicalize constants into the RHS.
10401     if (isa<Constant>(II->getOperand(1)) &&
10402         !isa<Constant>(II->getOperand(2))) {
10403       Value *LHS = II->getOperand(1);
10404       II->setOperand(1, II->getOperand(2));
10405       II->setOperand(2, LHS);
10406       return II;
10407     }
10408
10409     // X + undef -> undef
10410     if (isa<UndefValue>(II->getOperand(2)))
10411       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10412       
10413     if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10414       // X + 0 -> {X, false}
10415       if (RHS->isZero()) {
10416         Constant *V[] = {
10417           UndefValue::get(II->getOperand(0)->getType()),
10418           ConstantInt::getFalse(*Context)
10419         };
10420         Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10421         return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10422       }
10423     }
10424     break;
10425   case Intrinsic::usub_with_overflow:
10426   case Intrinsic::ssub_with_overflow:
10427     // undef - X -> undef
10428     // X - undef -> undef
10429     if (isa<UndefValue>(II->getOperand(1)) ||
10430         isa<UndefValue>(II->getOperand(2)))
10431       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10432       
10433     if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10434       // X - 0 -> {X, false}
10435       if (RHS->isZero()) {
10436         Constant *V[] = {
10437           UndefValue::get(II->getOperand(1)->getType()),
10438           ConstantInt::getFalse(*Context)
10439         };
10440         Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10441         return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10442       }
10443     }
10444     break;
10445   case Intrinsic::umul_with_overflow:
10446   case Intrinsic::smul_with_overflow:
10447     // Canonicalize constants into the RHS.
10448     if (isa<Constant>(II->getOperand(1)) &&
10449         !isa<Constant>(II->getOperand(2))) {
10450       Value *LHS = II->getOperand(1);
10451       II->setOperand(1, II->getOperand(2));
10452       II->setOperand(2, LHS);
10453       return II;
10454     }
10455
10456     // X * undef -> undef
10457     if (isa<UndefValue>(II->getOperand(2)))
10458       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10459       
10460     if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
10461       // X*0 -> {0, false}
10462       if (RHSI->isZero())
10463         return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
10464       
10465       // X * 1 -> {X, false}
10466       if (RHSI->equalsInt(1)) {
10467         Constant *V[] = {
10468           UndefValue::get(II->getOperand(1)->getType()),
10469           ConstantInt::getFalse(*Context)
10470         };
10471         Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10472         return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10473       }
10474     }
10475     break;
10476   case Intrinsic::ppc_altivec_lvx:
10477   case Intrinsic::ppc_altivec_lvxl:
10478   case Intrinsic::x86_sse_loadu_ps:
10479   case Intrinsic::x86_sse2_loadu_pd:
10480   case Intrinsic::x86_sse2_loadu_dq:
10481     // Turn PPC lvx     -> load if the pointer is known aligned.
10482     // Turn X86 loadups -> load if the pointer is known aligned.
10483     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
10484       Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
10485                                          PointerType::getUnqual(II->getType()));
10486       return new LoadInst(Ptr);
10487     }
10488     break;
10489   case Intrinsic::ppc_altivec_stvx:
10490   case Intrinsic::ppc_altivec_stvxl:
10491     // Turn stvx -> store if the pointer is known aligned.
10492     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
10493       const Type *OpPtrTy = 
10494         PointerType::getUnqual(II->getOperand(1)->getType());
10495       Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
10496       return new StoreInst(II->getOperand(1), Ptr);
10497     }
10498     break;
10499   case Intrinsic::x86_sse_storeu_ps:
10500   case Intrinsic::x86_sse2_storeu_pd:
10501   case Intrinsic::x86_sse2_storeu_dq:
10502     // Turn X86 storeu -> store if the pointer is known aligned.
10503     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
10504       const Type *OpPtrTy = 
10505         PointerType::getUnqual(II->getOperand(2)->getType());
10506       Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
10507       return new StoreInst(II->getOperand(2), Ptr);
10508     }
10509     break;
10510     
10511   case Intrinsic::x86_sse_cvttss2si: {
10512     // These intrinsics only demands the 0th element of its input vector.  If
10513     // we can simplify the input based on that, do so now.
10514     unsigned VWidth =
10515       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
10516     APInt DemandedElts(VWidth, 1);
10517     APInt UndefElts(VWidth, 0);
10518     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
10519                                               UndefElts)) {
10520       II->setOperand(1, V);
10521       return II;
10522     }
10523     break;
10524   }
10525     
10526   case Intrinsic::ppc_altivec_vperm:
10527     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
10528     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
10529       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
10530       
10531       // Check that all of the elements are integer constants or undefs.
10532       bool AllEltsOk = true;
10533       for (unsigned i = 0; i != 16; ++i) {
10534         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
10535             !isa<UndefValue>(Mask->getOperand(i))) {
10536           AllEltsOk = false;
10537           break;
10538         }
10539       }
10540       
10541       if (AllEltsOk) {
10542         // Cast the input vectors to byte vectors.
10543         Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
10544         Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
10545         Value *Result = UndefValue::get(Op0->getType());
10546         
10547         // Only extract each element once.
10548         Value *ExtractedElts[32];
10549         memset(ExtractedElts, 0, sizeof(ExtractedElts));
10550         
10551         for (unsigned i = 0; i != 16; ++i) {
10552           if (isa<UndefValue>(Mask->getOperand(i)))
10553             continue;
10554           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
10555           Idx &= 31;  // Match the hardware behavior.
10556           
10557           if (ExtractedElts[Idx] == 0) {
10558             ExtractedElts[Idx] = 
10559               Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1, 
10560                   ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
10561                                             "tmp");
10562           }
10563         
10564           // Insert this value into the result vector.
10565           Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
10566                          ConstantInt::get(Type::getInt32Ty(*Context), i, false),
10567                                                 "tmp");
10568         }
10569         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
10570       }
10571     }
10572     break;
10573
10574   case Intrinsic::stackrestore: {
10575     // If the save is right next to the restore, remove the restore.  This can
10576     // happen when variable allocas are DCE'd.
10577     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10578       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10579         BasicBlock::iterator BI = SS;
10580         if (&*++BI == II)
10581           return EraseInstFromFunction(CI);
10582       }
10583     }
10584     
10585     // Scan down this block to see if there is another stack restore in the
10586     // same block without an intervening call/alloca.
10587     BasicBlock::iterator BI = II;
10588     TerminatorInst *TI = II->getParent()->getTerminator();
10589     bool CannotRemove = false;
10590     for (++BI; &*BI != TI; ++BI) {
10591       if (isa<AllocaInst>(BI) || isMalloc(BI)) {
10592         CannotRemove = true;
10593         break;
10594       }
10595       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10596         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10597           // If there is a stackrestore below this one, remove this one.
10598           if (II->getIntrinsicID() == Intrinsic::stackrestore)
10599             return EraseInstFromFunction(CI);
10600           // Otherwise, ignore the intrinsic.
10601         } else {
10602           // If we found a non-intrinsic call, we can't remove the stack
10603           // restore.
10604           CannotRemove = true;
10605           break;
10606         }
10607       }
10608     }
10609     
10610     // If the stack restore is in a return/unwind block and if there are no
10611     // allocas or calls between the restore and the return, nuke the restore.
10612     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10613       return EraseInstFromFunction(CI);
10614     break;
10615   }
10616   }
10617
10618   return visitCallSite(II);
10619 }
10620
10621 // InvokeInst simplification
10622 //
10623 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10624   return visitCallSite(&II);
10625 }
10626
10627 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
10628 /// passed through the varargs area, we can eliminate the use of the cast.
10629 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10630                                          const CastInst * const CI,
10631                                          const TargetData * const TD,
10632                                          const int ix) {
10633   if (!CI->isLosslessCast())
10634     return false;
10635
10636   // The size of ByVal arguments is derived from the type, so we
10637   // can't change to a type with a different size.  If the size were
10638   // passed explicitly we could avoid this check.
10639   if (!CS.paramHasAttr(ix, Attribute::ByVal))
10640     return true;
10641
10642   const Type* SrcTy = 
10643             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10644   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10645   if (!SrcTy->isSized() || !DstTy->isSized())
10646     return false;
10647   if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10648     return false;
10649   return true;
10650 }
10651
10652 // visitCallSite - Improvements for call and invoke instructions.
10653 //
10654 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10655   bool Changed = false;
10656
10657   // If the callee is a constexpr cast of a function, attempt to move the cast
10658   // to the arguments of the call/invoke.
10659   if (transformConstExprCastCall(CS)) return 0;
10660
10661   Value *Callee = CS.getCalledValue();
10662
10663   if (Function *CalleeF = dyn_cast<Function>(Callee))
10664     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10665       Instruction *OldCall = CS.getInstruction();
10666       // If the call and callee calling conventions don't match, this call must
10667       // be unreachable, as the call is undefined.
10668       new StoreInst(ConstantInt::getTrue(*Context),
10669                 UndefValue::get(Type::getInt1PtrTy(*Context)), 
10670                                   OldCall);
10671       // If OldCall dues not return void then replaceAllUsesWith undef.
10672       // This allows ValueHandlers and custom metadata to adjust itself.
10673       if (!OldCall->getType()->isVoidTy())
10674         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
10675       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10676         return EraseInstFromFunction(*OldCall);
10677       return 0;
10678     }
10679
10680   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10681     // This instruction is not reachable, just remove it.  We insert a store to
10682     // undef so that we know that this code is not reachable, despite the fact
10683     // that we can't modify the CFG here.
10684     new StoreInst(ConstantInt::getTrue(*Context),
10685                UndefValue::get(Type::getInt1PtrTy(*Context)),
10686                   CS.getInstruction());
10687
10688     // If CS dues not return void then replaceAllUsesWith undef.
10689     // This allows ValueHandlers and custom metadata to adjust itself.
10690     if (!CS.getInstruction()->getType()->isVoidTy())
10691       CS.getInstruction()->
10692         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
10693
10694     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10695       // Don't break the CFG, insert a dummy cond branch.
10696       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10697                          ConstantInt::getTrue(*Context), II);
10698     }
10699     return EraseInstFromFunction(*CS.getInstruction());
10700   }
10701
10702   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10703     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10704       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10705         return transformCallThroughTrampoline(CS);
10706
10707   const PointerType *PTy = cast<PointerType>(Callee->getType());
10708   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10709   if (FTy->isVarArg()) {
10710     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10711     // See if we can optimize any arguments passed through the varargs area of
10712     // the call.
10713     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10714            E = CS.arg_end(); I != E; ++I, ++ix) {
10715       CastInst *CI = dyn_cast<CastInst>(*I);
10716       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10717         *I = CI->getOperand(0);
10718         Changed = true;
10719       }
10720     }
10721   }
10722
10723   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10724     // Inline asm calls cannot throw - mark them 'nounwind'.
10725     CS.setDoesNotThrow();
10726     Changed = true;
10727   }
10728
10729   return Changed ? CS.getInstruction() : 0;
10730 }
10731
10732 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10733 // attempt to move the cast to the arguments of the call/invoke.
10734 //
10735 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10736   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10737   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10738   if (CE->getOpcode() != Instruction::BitCast || 
10739       !isa<Function>(CE->getOperand(0)))
10740     return false;
10741   Function *Callee = cast<Function>(CE->getOperand(0));
10742   Instruction *Caller = CS.getInstruction();
10743   const AttrListPtr &CallerPAL = CS.getAttributes();
10744
10745   // Okay, this is a cast from a function to a different type.  Unless doing so
10746   // would cause a type conversion of one of our arguments, change this call to
10747   // be a direct call with arguments casted to the appropriate types.
10748   //
10749   const FunctionType *FT = Callee->getFunctionType();
10750   const Type *OldRetTy = Caller->getType();
10751   const Type *NewRetTy = FT->getReturnType();
10752
10753   if (isa<StructType>(NewRetTy))
10754     return false; // TODO: Handle multiple return values.
10755
10756   // Check to see if we are changing the return type...
10757   if (OldRetTy != NewRetTy) {
10758     if (Callee->isDeclaration() &&
10759         // Conversion is ok if changing from one pointer type to another or from
10760         // a pointer to an integer of the same size.
10761         !((isa<PointerType>(OldRetTy) || !TD ||
10762            OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
10763           (isa<PointerType>(NewRetTy) || !TD ||
10764            NewRetTy == TD->getIntPtrType(Caller->getContext()))))
10765       return false;   // Cannot transform this return value.
10766
10767     if (!Caller->use_empty() &&
10768         // void -> non-void is handled specially
10769         !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
10770       return false;   // Cannot transform this return value.
10771
10772     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10773       Attributes RAttrs = CallerPAL.getRetAttributes();
10774       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10775         return false;   // Attribute not compatible with transformed value.
10776     }
10777
10778     // If the callsite is an invoke instruction, and the return value is used by
10779     // a PHI node in a successor, we cannot change the return type of the call
10780     // because there is no place to put the cast instruction (without breaking
10781     // the critical edge).  Bail out in this case.
10782     if (!Caller->use_empty())
10783       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10784         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10785              UI != E; ++UI)
10786           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10787             if (PN->getParent() == II->getNormalDest() ||
10788                 PN->getParent() == II->getUnwindDest())
10789               return false;
10790   }
10791
10792   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10793   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10794
10795   CallSite::arg_iterator AI = CS.arg_begin();
10796   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10797     const Type *ParamTy = FT->getParamType(i);
10798     const Type *ActTy = (*AI)->getType();
10799
10800     if (!CastInst::isCastable(ActTy, ParamTy))
10801       return false;   // Cannot transform this parameter value.
10802
10803     if (CallerPAL.getParamAttributes(i + 1) 
10804         & Attribute::typeIncompatible(ParamTy))
10805       return false;   // Attribute not compatible with transformed value.
10806
10807     // Converting from one pointer type to another or between a pointer and an
10808     // integer of the same size is safe even if we do not have a body.
10809     bool isConvertible = ActTy == ParamTy ||
10810       (TD && ((isa<PointerType>(ParamTy) ||
10811       ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10812               (isa<PointerType>(ActTy) ||
10813               ActTy == TD->getIntPtrType(Caller->getContext()))));
10814     if (Callee->isDeclaration() && !isConvertible) return false;
10815   }
10816
10817   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10818       Callee->isDeclaration())
10819     return false;   // Do not delete arguments unless we have a function body.
10820
10821   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10822       !CallerPAL.isEmpty())
10823     // In this case we have more arguments than the new function type, but we
10824     // won't be dropping them.  Check that these extra arguments have attributes
10825     // that are compatible with being a vararg call argument.
10826     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10827       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10828         break;
10829       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10830       if (PAttrs & Attribute::VarArgsIncompatible)
10831         return false;
10832     }
10833
10834   // Okay, we decided that this is a safe thing to do: go ahead and start
10835   // inserting cast instructions as necessary...
10836   std::vector<Value*> Args;
10837   Args.reserve(NumActualArgs);
10838   SmallVector<AttributeWithIndex, 8> attrVec;
10839   attrVec.reserve(NumCommonArgs);
10840
10841   // Get any return attributes.
10842   Attributes RAttrs = CallerPAL.getRetAttributes();
10843
10844   // If the return value is not being used, the type may not be compatible
10845   // with the existing attributes.  Wipe out any problematic attributes.
10846   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10847
10848   // Add the new return attributes.
10849   if (RAttrs)
10850     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10851
10852   AI = CS.arg_begin();
10853   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10854     const Type *ParamTy = FT->getParamType(i);
10855     if ((*AI)->getType() == ParamTy) {
10856       Args.push_back(*AI);
10857     } else {
10858       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10859           false, ParamTy, false);
10860       Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
10861     }
10862
10863     // Add any parameter attributes.
10864     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10865       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10866   }
10867
10868   // If the function takes more arguments than the call was taking, add them
10869   // now.
10870   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10871     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10872
10873   // If we are removing arguments to the function, emit an obnoxious warning.
10874   if (FT->getNumParams() < NumActualArgs) {
10875     if (!FT->isVarArg()) {
10876       errs() << "WARNING: While resolving call to function '"
10877              << Callee->getName() << "' arguments were dropped!\n";
10878     } else {
10879       // Add all of the arguments in their promoted form to the arg list.
10880       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10881         const Type *PTy = getPromotedType((*AI)->getType());
10882         if (PTy != (*AI)->getType()) {
10883           // Must promote to pass through va_arg area!
10884           Instruction::CastOps opcode =
10885             CastInst::getCastOpcode(*AI, false, PTy, false);
10886           Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
10887         } else {
10888           Args.push_back(*AI);
10889         }
10890
10891         // Add any parameter attributes.
10892         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10893           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10894       }
10895     }
10896   }
10897
10898   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10899     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10900
10901   if (NewRetTy->isVoidTy())
10902     Caller->setName("");   // Void type should not have a name.
10903
10904   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10905                                                      attrVec.end());
10906
10907   Instruction *NC;
10908   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10909     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10910                             Args.begin(), Args.end(),
10911                             Caller->getName(), Caller);
10912     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10913     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10914   } else {
10915     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10916                           Caller->getName(), Caller);
10917     CallInst *CI = cast<CallInst>(Caller);
10918     if (CI->isTailCall())
10919       cast<CallInst>(NC)->setTailCall();
10920     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10921     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10922   }
10923
10924   // Insert a cast of the return type as necessary.
10925   Value *NV = NC;
10926   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10927     if (!NV->getType()->isVoidTy()) {
10928       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10929                                                             OldRetTy, false);
10930       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10931
10932       // If this is an invoke instruction, we should insert it after the first
10933       // non-phi, instruction in the normal successor block.
10934       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10935         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10936         InsertNewInstBefore(NC, *I);
10937       } else {
10938         // Otherwise, it's a call, just insert cast right after the call instr
10939         InsertNewInstBefore(NC, *Caller);
10940       }
10941       Worklist.AddUsersToWorkList(*Caller);
10942     } else {
10943       NV = UndefValue::get(Caller->getType());
10944     }
10945   }
10946
10947
10948   if (!Caller->use_empty())
10949     Caller->replaceAllUsesWith(NV);
10950   
10951   EraseInstFromFunction(*Caller);
10952   return true;
10953 }
10954
10955 // transformCallThroughTrampoline - Turn a call to a function created by the
10956 // init_trampoline intrinsic into a direct call to the underlying function.
10957 //
10958 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10959   Value *Callee = CS.getCalledValue();
10960   const PointerType *PTy = cast<PointerType>(Callee->getType());
10961   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10962   const AttrListPtr &Attrs = CS.getAttributes();
10963
10964   // If the call already has the 'nest' attribute somewhere then give up -
10965   // otherwise 'nest' would occur twice after splicing in the chain.
10966   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10967     return 0;
10968
10969   IntrinsicInst *Tramp =
10970     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10971
10972   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10973   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10974   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10975
10976   const AttrListPtr &NestAttrs = NestF->getAttributes();
10977   if (!NestAttrs.isEmpty()) {
10978     unsigned NestIdx = 1;
10979     const Type *NestTy = 0;
10980     Attributes NestAttr = Attribute::None;
10981
10982     // Look for a parameter marked with the 'nest' attribute.
10983     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10984          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10985       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10986         // Record the parameter type and any other attributes.
10987         NestTy = *I;
10988         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10989         break;
10990       }
10991
10992     if (NestTy) {
10993       Instruction *Caller = CS.getInstruction();
10994       std::vector<Value*> NewArgs;
10995       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10996
10997       SmallVector<AttributeWithIndex, 8> NewAttrs;
10998       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10999
11000       // Insert the nest argument into the call argument list, which may
11001       // mean appending it.  Likewise for attributes.
11002
11003       // Add any result attributes.
11004       if (Attributes Attr = Attrs.getRetAttributes())
11005         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
11006
11007       {
11008         unsigned Idx = 1;
11009         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
11010         do {
11011           if (Idx == NestIdx) {
11012             // Add the chain argument and attributes.
11013             Value *NestVal = Tramp->getOperand(3);
11014             if (NestVal->getType() != NestTy)
11015               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
11016             NewArgs.push_back(NestVal);
11017             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
11018           }
11019
11020           if (I == E)
11021             break;
11022
11023           // Add the original argument and attributes.
11024           NewArgs.push_back(*I);
11025           if (Attributes Attr = Attrs.getParamAttributes(Idx))
11026             NewAttrs.push_back
11027               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
11028
11029           ++Idx, ++I;
11030         } while (1);
11031       }
11032
11033       // Add any function attributes.
11034       if (Attributes Attr = Attrs.getFnAttributes())
11035         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
11036
11037       // The trampoline may have been bitcast to a bogus type (FTy).
11038       // Handle this by synthesizing a new function type, equal to FTy
11039       // with the chain parameter inserted.
11040
11041       std::vector<const Type*> NewTypes;
11042       NewTypes.reserve(FTy->getNumParams()+1);
11043
11044       // Insert the chain's type into the list of parameter types, which may
11045       // mean appending it.
11046       {
11047         unsigned Idx = 1;
11048         FunctionType::param_iterator I = FTy->param_begin(),
11049           E = FTy->param_end();
11050
11051         do {
11052           if (Idx == NestIdx)
11053             // Add the chain's type.
11054             NewTypes.push_back(NestTy);
11055
11056           if (I == E)
11057             break;
11058
11059           // Add the original type.
11060           NewTypes.push_back(*I);
11061
11062           ++Idx, ++I;
11063         } while (1);
11064       }
11065
11066       // Replace the trampoline call with a direct call.  Let the generic
11067       // code sort out any function type mismatches.
11068       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 
11069                                                 FTy->isVarArg());
11070       Constant *NewCallee =
11071         NestF->getType() == PointerType::getUnqual(NewFTy) ?
11072         NestF : ConstantExpr::getBitCast(NestF, 
11073                                          PointerType::getUnqual(NewFTy));
11074       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
11075                                                    NewAttrs.end());
11076
11077       Instruction *NewCaller;
11078       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
11079         NewCaller = InvokeInst::Create(NewCallee,
11080                                        II->getNormalDest(), II->getUnwindDest(),
11081                                        NewArgs.begin(), NewArgs.end(),
11082                                        Caller->getName(), Caller);
11083         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
11084         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
11085       } else {
11086         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
11087                                      Caller->getName(), Caller);
11088         if (cast<CallInst>(Caller)->isTailCall())
11089           cast<CallInst>(NewCaller)->setTailCall();
11090         cast<CallInst>(NewCaller)->
11091           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
11092         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
11093       }
11094       if (!Caller->getType()->isVoidTy())
11095         Caller->replaceAllUsesWith(NewCaller);
11096       Caller->eraseFromParent();
11097       Worklist.Remove(Caller);
11098       return 0;
11099     }
11100   }
11101
11102   // Replace the trampoline call with a direct call.  Since there is no 'nest'
11103   // parameter, there is no need to adjust the argument list.  Let the generic
11104   // code sort out any function type mismatches.
11105   Constant *NewCallee =
11106     NestF->getType() == PTy ? NestF : 
11107                               ConstantExpr::getBitCast(NestF, PTy);
11108   CS.setCalledFunction(NewCallee);
11109   return CS.getInstruction();
11110 }
11111
11112 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
11113 /// and if a/b/c and the add's all have a single use, turn this into a phi
11114 /// and a single binop.
11115 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
11116   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
11117   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
11118   unsigned Opc = FirstInst->getOpcode();
11119   Value *LHSVal = FirstInst->getOperand(0);
11120   Value *RHSVal = FirstInst->getOperand(1);
11121     
11122   const Type *LHSType = LHSVal->getType();
11123   const Type *RHSType = RHSVal->getType();
11124   
11125   // Scan to see if all operands are the same opcode, and all have one use.
11126   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
11127     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
11128     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
11129         // Verify type of the LHS matches so we don't fold cmp's of different
11130         // types or GEP's with different index types.
11131         I->getOperand(0)->getType() != LHSType ||
11132         I->getOperand(1)->getType() != RHSType)
11133       return 0;
11134
11135     // If they are CmpInst instructions, check their predicates
11136     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
11137       if (cast<CmpInst>(I)->getPredicate() !=
11138           cast<CmpInst>(FirstInst)->getPredicate())
11139         return 0;
11140     
11141     // Keep track of which operand needs a phi node.
11142     if (I->getOperand(0) != LHSVal) LHSVal = 0;
11143     if (I->getOperand(1) != RHSVal) RHSVal = 0;
11144   }
11145
11146   // If both LHS and RHS would need a PHI, don't do this transformation,
11147   // because it would increase the number of PHIs entering the block,
11148   // which leads to higher register pressure. This is especially
11149   // bad when the PHIs are in the header of a loop.
11150   if (!LHSVal && !RHSVal)
11151     return 0;
11152   
11153   // Otherwise, this is safe to transform!
11154   
11155   Value *InLHS = FirstInst->getOperand(0);
11156   Value *InRHS = FirstInst->getOperand(1);
11157   PHINode *NewLHS = 0, *NewRHS = 0;
11158   if (LHSVal == 0) {
11159     NewLHS = PHINode::Create(LHSType,
11160                              FirstInst->getOperand(0)->getName() + ".pn");
11161     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
11162     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
11163     InsertNewInstBefore(NewLHS, PN);
11164     LHSVal = NewLHS;
11165   }
11166   
11167   if (RHSVal == 0) {
11168     NewRHS = PHINode::Create(RHSType,
11169                              FirstInst->getOperand(1)->getName() + ".pn");
11170     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
11171     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
11172     InsertNewInstBefore(NewRHS, PN);
11173     RHSVal = NewRHS;
11174   }
11175   
11176   // Add all operands to the new PHIs.
11177   if (NewLHS || NewRHS) {
11178     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11179       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
11180       if (NewLHS) {
11181         Value *NewInLHS = InInst->getOperand(0);
11182         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
11183       }
11184       if (NewRHS) {
11185         Value *NewInRHS = InInst->getOperand(1);
11186         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
11187       }
11188     }
11189   }
11190     
11191   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
11192     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
11193   CmpInst *CIOp = cast<CmpInst>(FirstInst);
11194   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
11195                          LHSVal, RHSVal);
11196 }
11197
11198 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
11199   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
11200   
11201   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
11202                                         FirstInst->op_end());
11203   // This is true if all GEP bases are allocas and if all indices into them are
11204   // constants.
11205   bool AllBasePointersAreAllocas = true;
11206
11207   // We don't want to replace this phi if the replacement would require
11208   // more than one phi, which leads to higher register pressure. This is
11209   // especially bad when the PHIs are in the header of a loop.
11210   bool NeededPhi = false;
11211   
11212   // Scan to see if all operands are the same opcode, and all have one use.
11213   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
11214     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
11215     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
11216       GEP->getNumOperands() != FirstInst->getNumOperands())
11217       return 0;
11218
11219     // Keep track of whether or not all GEPs are of alloca pointers.
11220     if (AllBasePointersAreAllocas &&
11221         (!isa<AllocaInst>(GEP->getOperand(0)) ||
11222          !GEP->hasAllConstantIndices()))
11223       AllBasePointersAreAllocas = false;
11224     
11225     // Compare the operand lists.
11226     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
11227       if (FirstInst->getOperand(op) == GEP->getOperand(op))
11228         continue;
11229       
11230       // Don't merge two GEPs when two operands differ (introducing phi nodes)
11231       // if one of the PHIs has a constant for the index.  The index may be
11232       // substantially cheaper to compute for the constants, so making it a
11233       // variable index could pessimize the path.  This also handles the case
11234       // for struct indices, which must always be constant.
11235       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
11236           isa<ConstantInt>(GEP->getOperand(op)))
11237         return 0;
11238       
11239       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
11240         return 0;
11241
11242       // If we already needed a PHI for an earlier operand, and another operand
11243       // also requires a PHI, we'd be introducing more PHIs than we're
11244       // eliminating, which increases register pressure on entry to the PHI's
11245       // block.
11246       if (NeededPhi)
11247         return 0;
11248
11249       FixedOperands[op] = 0;  // Needs a PHI.
11250       NeededPhi = true;
11251     }
11252   }
11253   
11254   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
11255   // bother doing this transformation.  At best, this will just save a bit of
11256   // offset calculation, but all the predecessors will have to materialize the
11257   // stack address into a register anyway.  We'd actually rather *clone* the
11258   // load up into the predecessors so that we have a load of a gep of an alloca,
11259   // which can usually all be folded into the load.
11260   if (AllBasePointersAreAllocas)
11261     return 0;
11262   
11263   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
11264   // that is variable.
11265   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
11266   
11267   bool HasAnyPHIs = false;
11268   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
11269     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
11270     Value *FirstOp = FirstInst->getOperand(i);
11271     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
11272                                      FirstOp->getName()+".pn");
11273     InsertNewInstBefore(NewPN, PN);
11274     
11275     NewPN->reserveOperandSpace(e);
11276     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
11277     OperandPhis[i] = NewPN;
11278     FixedOperands[i] = NewPN;
11279     HasAnyPHIs = true;
11280   }
11281
11282   
11283   // Add all operands to the new PHIs.
11284   if (HasAnyPHIs) {
11285     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11286       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
11287       BasicBlock *InBB = PN.getIncomingBlock(i);
11288       
11289       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
11290         if (PHINode *OpPhi = OperandPhis[op])
11291           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
11292     }
11293   }
11294   
11295   Value *Base = FixedOperands[0];
11296   return cast<GEPOperator>(FirstInst)->isInBounds() ?
11297     GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
11298                                       FixedOperands.end()) :
11299     GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
11300                               FixedOperands.end());
11301 }
11302
11303
11304 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
11305 /// sink the load out of the block that defines it.  This means that it must be
11306 /// obvious the value of the load is not changed from the point of the load to
11307 /// the end of the block it is in.
11308 ///
11309 /// Finally, it is safe, but not profitable, to sink a load targetting a
11310 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
11311 /// to a register.
11312 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
11313   BasicBlock::iterator BBI = L, E = L->getParent()->end();
11314   
11315   for (++BBI; BBI != E; ++BBI)
11316     if (BBI->mayWriteToMemory())
11317       return false;
11318   
11319   // Check for non-address taken alloca.  If not address-taken already, it isn't
11320   // profitable to do this xform.
11321   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
11322     bool isAddressTaken = false;
11323     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
11324          UI != E; ++UI) {
11325       if (isa<LoadInst>(UI)) continue;
11326       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
11327         // If storing TO the alloca, then the address isn't taken.
11328         if (SI->getOperand(1) == AI) continue;
11329       }
11330       isAddressTaken = true;
11331       break;
11332     }
11333     
11334     if (!isAddressTaken && AI->isStaticAlloca())
11335       return false;
11336   }
11337   
11338   // If this load is a load from a GEP with a constant offset from an alloca,
11339   // then we don't want to sink it.  In its present form, it will be
11340   // load [constant stack offset].  Sinking it will cause us to have to
11341   // materialize the stack addresses in each predecessor in a register only to
11342   // do a shared load from register in the successor.
11343   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
11344     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
11345       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
11346         return false;
11347   
11348   return true;
11349 }
11350
11351 Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
11352   LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
11353   
11354   // When processing loads, we need to propagate two bits of information to the
11355   // sunk load: whether it is volatile, and what its alignment is.  We currently
11356   // don't sink loads when some have their alignment specified and some don't.
11357   // visitLoadInst will propagate an alignment onto the load when TD is around,
11358   // and if TD isn't around, we can't handle the mixed case.
11359   bool isVolatile = FirstLI->isVolatile();
11360   unsigned LoadAlignment = FirstLI->getAlignment();
11361   
11362   // We can't sink the load if the loaded value could be modified between the
11363   // load and the PHI.
11364   if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
11365       !isSafeAndProfitableToSinkLoad(FirstLI))
11366     return 0;
11367   
11368   // If the PHI is of volatile loads and the load block has multiple
11369   // successors, sinking it would remove a load of the volatile value from
11370   // the path through the other successor.
11371   if (isVolatile && 
11372       FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
11373     return 0;
11374   
11375   // Check to see if all arguments are the same operation.
11376   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11377     LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
11378     if (!LI || !LI->hasOneUse())
11379       return 0;
11380     
11381     // We can't sink the load if the loaded value could be modified between 
11382     // the load and the PHI.
11383     if (LI->isVolatile() != isVolatile ||
11384         LI->getParent() != PN.getIncomingBlock(i) ||
11385         !isSafeAndProfitableToSinkLoad(LI))
11386       return 0;
11387       
11388     // If some of the loads have an alignment specified but not all of them,
11389     // we can't do the transformation.
11390     if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
11391       return 0;
11392     
11393     LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
11394     
11395     // If the PHI is of volatile loads and the load block has multiple
11396     // successors, sinking it would remove a load of the volatile value from
11397     // the path through the other successor.
11398     if (isVolatile &&
11399         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
11400       return 0;
11401   }
11402   
11403   // Okay, they are all the same operation.  Create a new PHI node of the
11404   // correct type, and PHI together all of the LHS's of the instructions.
11405   PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
11406                                    PN.getName()+".in");
11407   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
11408   
11409   Value *InVal = FirstLI->getOperand(0);
11410   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
11411   
11412   // Add all operands to the new PHI.
11413   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11414     Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
11415     if (NewInVal != InVal)
11416       InVal = 0;
11417     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11418   }
11419   
11420   Value *PhiVal;
11421   if (InVal) {
11422     // The new PHI unions all of the same values together.  This is really
11423     // common, so we handle it intelligently here for compile-time speed.
11424     PhiVal = InVal;
11425     delete NewPN;
11426   } else {
11427     InsertNewInstBefore(NewPN, PN);
11428     PhiVal = NewPN;
11429   }
11430   
11431   // If this was a volatile load that we are merging, make sure to loop through
11432   // and mark all the input loads as non-volatile.  If we don't do this, we will
11433   // insert a new volatile load and the old ones will not be deletable.
11434   if (isVolatile)
11435     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
11436       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
11437   
11438   return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
11439 }
11440
11441
11442
11443 /// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
11444 /// operator and they all are only used by the PHI, PHI together their
11445 /// inputs, and do the operation once, to the result of the PHI.
11446 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
11447   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
11448
11449   if (isa<GetElementPtrInst>(FirstInst))
11450     return FoldPHIArgGEPIntoPHI(PN);
11451   if (isa<LoadInst>(FirstInst))
11452     return FoldPHIArgLoadIntoPHI(PN);
11453   
11454   // Scan the instruction, looking for input operations that can be folded away.
11455   // If all input operands to the phi are the same instruction (e.g. a cast from
11456   // the same type or "+42") we can pull the operation through the PHI, reducing
11457   // code size and simplifying code.
11458   Constant *ConstantOp = 0;
11459   const Type *CastSrcTy = 0;
11460   
11461   if (isa<CastInst>(FirstInst)) {
11462     CastSrcTy = FirstInst->getOperand(0)->getType();
11463
11464     // Be careful about transforming integer PHIs.  We don't want to pessimize
11465     // the code by turning an i32 into an i1293.
11466     if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
11467       if (!ShouldChangeType(PN.getType(), CastSrcTy, TD))
11468         return 0;
11469     }
11470   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
11471     // Can fold binop, compare or shift here if the RHS is a constant, 
11472     // otherwise call FoldPHIArgBinOpIntoPHI.
11473     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
11474     if (ConstantOp == 0)
11475       return FoldPHIArgBinOpIntoPHI(PN);
11476   } else {
11477     return 0;  // Cannot fold this operation.
11478   }
11479
11480   // Check to see if all arguments are the same operation.
11481   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11482     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
11483     if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
11484       return 0;
11485     if (CastSrcTy) {
11486       if (I->getOperand(0)->getType() != CastSrcTy)
11487         return 0;  // Cast operation must match.
11488     } else if (I->getOperand(1) != ConstantOp) {
11489       return 0;
11490     }
11491   }
11492
11493   // Okay, they are all the same operation.  Create a new PHI node of the
11494   // correct type, and PHI together all of the LHS's of the instructions.
11495   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
11496                                    PN.getName()+".in");
11497   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
11498
11499   Value *InVal = FirstInst->getOperand(0);
11500   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
11501
11502   // Add all operands to the new PHI.
11503   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11504     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
11505     if (NewInVal != InVal)
11506       InVal = 0;
11507     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11508   }
11509
11510   Value *PhiVal;
11511   if (InVal) {
11512     // The new PHI unions all of the same values together.  This is really
11513     // common, so we handle it intelligently here for compile-time speed.
11514     PhiVal = InVal;
11515     delete NewPN;
11516   } else {
11517     InsertNewInstBefore(NewPN, PN);
11518     PhiVal = NewPN;
11519   }
11520
11521   // Insert and return the new operation.
11522   if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
11523     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
11524   
11525   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
11526     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
11527   
11528   CmpInst *CIOp = cast<CmpInst>(FirstInst);
11529   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
11530                          PhiVal, ConstantOp);
11531 }
11532
11533 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
11534 /// that is dead.
11535 static bool DeadPHICycle(PHINode *PN,
11536                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
11537   if (PN->use_empty()) return true;
11538   if (!PN->hasOneUse()) return false;
11539
11540   // Remember this node, and if we find the cycle, return.
11541   if (!PotentiallyDeadPHIs.insert(PN))
11542     return true;
11543   
11544   // Don't scan crazily complex things.
11545   if (PotentiallyDeadPHIs.size() == 16)
11546     return false;
11547
11548   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
11549     return DeadPHICycle(PU, PotentiallyDeadPHIs);
11550
11551   return false;
11552 }
11553
11554 /// PHIsEqualValue - Return true if this phi node is always equal to
11555 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
11556 ///   z = some value; x = phi (y, z); y = phi (x, z)
11557 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
11558                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
11559   // See if we already saw this PHI node.
11560   if (!ValueEqualPHIs.insert(PN))
11561     return true;
11562   
11563   // Don't scan crazily complex things.
11564   if (ValueEqualPHIs.size() == 16)
11565     return false;
11566  
11567   // Scan the operands to see if they are either phi nodes or are equal to
11568   // the value.
11569   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11570     Value *Op = PN->getIncomingValue(i);
11571     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
11572       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
11573         return false;
11574     } else if (Op != NonPhiInVal)
11575       return false;
11576   }
11577   
11578   return true;
11579 }
11580
11581
11582 namespace {
11583 struct PHIUsageRecord {
11584   unsigned PHIId;     // The ID # of the PHI (something determinstic to sort on)
11585   unsigned Shift;     // The amount shifted.
11586   Instruction *Inst;  // The trunc instruction.
11587   
11588   PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
11589     : PHIId(pn), Shift(Sh), Inst(User) {}
11590   
11591   bool operator<(const PHIUsageRecord &RHS) const {
11592     if (PHIId < RHS.PHIId) return true;
11593     if (PHIId > RHS.PHIId) return false;
11594     if (Shift < RHS.Shift) return true;
11595     if (Shift > RHS.Shift) return false;
11596     return Inst->getType()->getPrimitiveSizeInBits() <
11597            RHS.Inst->getType()->getPrimitiveSizeInBits();
11598   }
11599 };
11600   
11601 struct LoweredPHIRecord {
11602   PHINode *PN;        // The PHI that was lowered.
11603   unsigned Shift;     // The amount shifted.
11604   unsigned Width;     // The width extracted.
11605   
11606   LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
11607     : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
11608   
11609   // Ctor form used by DenseMap.
11610   LoweredPHIRecord(PHINode *pn, unsigned Sh)
11611     : PN(pn), Shift(Sh), Width(0) {}
11612 };
11613 }
11614
11615 namespace llvm {
11616   template<>
11617   struct DenseMapInfo<LoweredPHIRecord> {
11618     static inline LoweredPHIRecord getEmptyKey() {
11619       return LoweredPHIRecord(0, 0);
11620     }
11621     static inline LoweredPHIRecord getTombstoneKey() {
11622       return LoweredPHIRecord(0, 1);
11623     }
11624     static unsigned getHashValue(const LoweredPHIRecord &Val) {
11625       return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
11626              (Val.Width>>3);
11627     }
11628     static bool isEqual(const LoweredPHIRecord &LHS,
11629                         const LoweredPHIRecord &RHS) {
11630       return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
11631              LHS.Width == RHS.Width;
11632     }
11633   };
11634   template <>
11635   struct isPodLike<LoweredPHIRecord> { static const bool value = true; };
11636 }
11637
11638
11639 /// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
11640 /// illegal type: see if it is only used by trunc or trunc(lshr) operations.  If
11641 /// so, we split the PHI into the various pieces being extracted.  This sort of
11642 /// thing is introduced when SROA promotes an aggregate to large integer values.
11643 ///
11644 /// TODO: The user of the trunc may be an bitcast to float/double/vector or an
11645 /// inttoptr.  We should produce new PHIs in the right type.
11646 ///
11647 Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
11648   // PHIUsers - Keep track of all of the truncated values extracted from a set
11649   // of PHIs, along with their offset.  These are the things we want to rewrite.
11650   SmallVector<PHIUsageRecord, 16> PHIUsers;
11651   
11652   // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
11653   // nodes which are extracted from. PHIsToSlice is a set we use to avoid
11654   // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
11655   // check the uses of (to ensure they are all extracts).
11656   SmallVector<PHINode*, 8> PHIsToSlice;
11657   SmallPtrSet<PHINode*, 8> PHIsInspected;
11658   
11659   PHIsToSlice.push_back(&FirstPhi);
11660   PHIsInspected.insert(&FirstPhi);
11661   
11662   for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
11663     PHINode *PN = PHIsToSlice[PHIId];
11664     
11665     // Scan the input list of the PHI.  If any input is an invoke, and if the
11666     // input is defined in the predecessor, then we won't be split the critical
11667     // edge which is required to insert a truncate.  Because of this, we have to
11668     // bail out.
11669     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11670       InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
11671       if (II == 0) continue;
11672       if (II->getParent() != PN->getIncomingBlock(i))
11673         continue;
11674      
11675       // If we have a phi, and if it's directly in the predecessor, then we have
11676       // a critical edge where we need to put the truncate.  Since we can't
11677       // split the edge in instcombine, we have to bail out.
11678       return 0;
11679     }
11680       
11681     
11682     for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
11683          UI != E; ++UI) {
11684       Instruction *User = cast<Instruction>(*UI);
11685       
11686       // If the user is a PHI, inspect its uses recursively.
11687       if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
11688         if (PHIsInspected.insert(UserPN))
11689           PHIsToSlice.push_back(UserPN);
11690         continue;
11691       }
11692       
11693       // Truncates are always ok.
11694       if (isa<TruncInst>(User)) {
11695         PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
11696         continue;
11697       }
11698       
11699       // Otherwise it must be a lshr which can only be used by one trunc.
11700       if (User->getOpcode() != Instruction::LShr ||
11701           !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
11702           !isa<ConstantInt>(User->getOperand(1)))
11703         return 0;
11704       
11705       unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
11706       PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
11707     }
11708   }
11709   
11710   // If we have no users, they must be all self uses, just nuke the PHI.
11711   if (PHIUsers.empty())
11712     return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
11713   
11714   // If this phi node is transformable, create new PHIs for all the pieces
11715   // extracted out of it.  First, sort the users by their offset and size.
11716   array_pod_sort(PHIUsers.begin(), PHIUsers.end());
11717   
11718   DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
11719             for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11720               errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
11721         );
11722   
11723   // PredValues - This is a temporary used when rewriting PHI nodes.  It is
11724   // hoisted out here to avoid construction/destruction thrashing.
11725   DenseMap<BasicBlock*, Value*> PredValues;
11726   
11727   // ExtractedVals - Each new PHI we introduce is saved here so we don't
11728   // introduce redundant PHIs.
11729   DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
11730   
11731   for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
11732     unsigned PHIId = PHIUsers[UserI].PHIId;
11733     PHINode *PN = PHIsToSlice[PHIId];
11734     unsigned Offset = PHIUsers[UserI].Shift;
11735     const Type *Ty = PHIUsers[UserI].Inst->getType();
11736     
11737     PHINode *EltPHI;
11738     
11739     // If we've already lowered a user like this, reuse the previously lowered
11740     // value.
11741     if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
11742       
11743       // Otherwise, Create the new PHI node for this user.
11744       EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
11745       assert(EltPHI->getType() != PN->getType() &&
11746              "Truncate didn't shrink phi?");
11747     
11748       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11749         BasicBlock *Pred = PN->getIncomingBlock(i);
11750         Value *&PredVal = PredValues[Pred];
11751         
11752         // If we already have a value for this predecessor, reuse it.
11753         if (PredVal) {
11754           EltPHI->addIncoming(PredVal, Pred);
11755           continue;
11756         }
11757
11758         // Handle the PHI self-reuse case.
11759         Value *InVal = PN->getIncomingValue(i);
11760         if (InVal == PN) {
11761           PredVal = EltPHI;
11762           EltPHI->addIncoming(PredVal, Pred);
11763           continue;
11764         }
11765         
11766         if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
11767           // If the incoming value was a PHI, and if it was one of the PHIs we
11768           // already rewrote it, just use the lowered value.
11769           if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
11770             PredVal = Res;
11771             EltPHI->addIncoming(PredVal, Pred);
11772             continue;
11773           }
11774         }
11775         
11776         // Otherwise, do an extract in the predecessor.
11777         Builder->SetInsertPoint(Pred, Pred->getTerminator());
11778         Value *Res = InVal;
11779         if (Offset)
11780           Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
11781                                                           Offset), "extract");
11782         Res = Builder->CreateTrunc(Res, Ty, "extract.t");
11783         PredVal = Res;
11784         EltPHI->addIncoming(Res, Pred);
11785         
11786         // If the incoming value was a PHI, and if it was one of the PHIs we are
11787         // rewriting, we will ultimately delete the code we inserted.  This
11788         // means we need to revisit that PHI to make sure we extract out the
11789         // needed piece.
11790         if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
11791           if (PHIsInspected.count(OldInVal)) {
11792             unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
11793                                           OldInVal)-PHIsToSlice.begin();
11794             PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset, 
11795                                               cast<Instruction>(Res)));
11796             ++UserE;
11797           }
11798       }
11799       PredValues.clear();
11800       
11801       DEBUG(errs() << "  Made element PHI for offset " << Offset << ": "
11802                    << *EltPHI << '\n');
11803       ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
11804     }
11805     
11806     // Replace the use of this piece with the PHI node.
11807     ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
11808   }
11809   
11810   // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
11811   // with undefs.
11812   Value *Undef = UndefValue::get(FirstPhi.getType());
11813   for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11814     ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
11815   return ReplaceInstUsesWith(FirstPhi, Undef);
11816 }
11817
11818 // PHINode simplification
11819 //
11820 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
11821   // If LCSSA is around, don't mess with Phi nodes
11822   if (MustPreserveLCSSA) return 0;
11823   
11824   if (Value *V = PN.hasConstantValue())
11825     return ReplaceInstUsesWith(PN, V);
11826
11827   // If all PHI operands are the same operation, pull them through the PHI,
11828   // reducing code size.
11829   if (isa<Instruction>(PN.getIncomingValue(0)) &&
11830       isa<Instruction>(PN.getIncomingValue(1)) &&
11831       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
11832       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
11833       // FIXME: The hasOneUse check will fail for PHIs that use the value more
11834       // than themselves more than once.
11835       PN.getIncomingValue(0)->hasOneUse())
11836     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
11837       return Result;
11838
11839   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
11840   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
11841   // PHI)... break the cycle.
11842   if (PN.hasOneUse()) {
11843     Instruction *PHIUser = cast<Instruction>(PN.use_back());
11844     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
11845       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
11846       PotentiallyDeadPHIs.insert(&PN);
11847       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
11848         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
11849     }
11850    
11851     // If this phi has a single use, and if that use just computes a value for
11852     // the next iteration of a loop, delete the phi.  This occurs with unused
11853     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
11854     // common case here is good because the only other things that catch this
11855     // are induction variable analysis (sometimes) and ADCE, which is only run
11856     // late.
11857     if (PHIUser->hasOneUse() &&
11858         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
11859         PHIUser->use_back() == &PN) {
11860       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
11861     }
11862   }
11863
11864   // We sometimes end up with phi cycles that non-obviously end up being the
11865   // same value, for example:
11866   //   z = some value; x = phi (y, z); y = phi (x, z)
11867   // where the phi nodes don't necessarily need to be in the same block.  Do a
11868   // quick check to see if the PHI node only contains a single non-phi value, if
11869   // so, scan to see if the phi cycle is actually equal to that value.
11870   {
11871     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
11872     // Scan for the first non-phi operand.
11873     while (InValNo != NumOperandVals && 
11874            isa<PHINode>(PN.getIncomingValue(InValNo)))
11875       ++InValNo;
11876
11877     if (InValNo != NumOperandVals) {
11878       Value *NonPhiInVal = PN.getOperand(InValNo);
11879       
11880       // Scan the rest of the operands to see if there are any conflicts, if so
11881       // there is no need to recursively scan other phis.
11882       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11883         Value *OpVal = PN.getIncomingValue(InValNo);
11884         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11885           break;
11886       }
11887       
11888       // If we scanned over all operands, then we have one unique value plus
11889       // phi values.  Scan PHI nodes to see if they all merge in each other or
11890       // the value.
11891       if (InValNo == NumOperandVals) {
11892         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11893         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11894           return ReplaceInstUsesWith(PN, NonPhiInVal);
11895       }
11896     }
11897   }
11898
11899   // If there are multiple PHIs, sort their operands so that they all list
11900   // the blocks in the same order. This will help identical PHIs be eliminated
11901   // by other passes. Other passes shouldn't depend on this for correctness
11902   // however.
11903   PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
11904   if (&PN != FirstPN)
11905     for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
11906       BasicBlock *BBA = PN.getIncomingBlock(i);
11907       BasicBlock *BBB = FirstPN->getIncomingBlock(i);
11908       if (BBA != BBB) {
11909         Value *VA = PN.getIncomingValue(i);
11910         unsigned j = PN.getBasicBlockIndex(BBB);
11911         Value *VB = PN.getIncomingValue(j);
11912         PN.setIncomingBlock(i, BBB);
11913         PN.setIncomingValue(i, VB);
11914         PN.setIncomingBlock(j, BBA);
11915         PN.setIncomingValue(j, VA);
11916         // NOTE: Instcombine normally would want us to "return &PN" if we
11917         // modified any of the operands of an instruction.  However, since we
11918         // aren't adding or removing uses (just rearranging them) we don't do
11919         // this in this case.
11920       }
11921     }
11922
11923   // If this is an integer PHI and we know that it has an illegal type, see if
11924   // it is only used by trunc or trunc(lshr) operations.  If so, we split the
11925   // PHI into the various pieces being extracted.  This sort of thing is
11926   // introduced when SROA promotes an aggregate to a single large integer type.
11927   if (isa<IntegerType>(PN.getType()) && TD &&
11928       !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
11929     if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
11930       return Res;
11931   
11932   return 0;
11933 }
11934
11935 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
11936   SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
11937
11938   if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
11939     return ReplaceInstUsesWith(GEP, V);
11940
11941   Value *PtrOp = GEP.getOperand(0);
11942
11943   if (isa<UndefValue>(GEP.getOperand(0)))
11944     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
11945
11946   // Eliminate unneeded casts for indices.
11947   if (TD) {
11948     bool MadeChange = false;
11949     unsigned PtrSize = TD->getPointerSizeInBits();
11950     
11951     gep_type_iterator GTI = gep_type_begin(GEP);
11952     for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11953          I != E; ++I, ++GTI) {
11954       if (!isa<SequentialType>(*GTI)) continue;
11955       
11956       // If we are using a wider index than needed for this platform, shrink it
11957       // to what we need.  If narrower, sign-extend it to what we need.  This
11958       // explicit cast can make subsequent optimizations more obvious.
11959       unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
11960       if (OpBits == PtrSize)
11961         continue;
11962       
11963       *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
11964       MadeChange = true;
11965     }
11966     if (MadeChange) return &GEP;
11967   }
11968
11969   // Combine Indices - If the source pointer to this getelementptr instruction
11970   // is a getelementptr instruction, combine the indices of the two
11971   // getelementptr instructions into a single instruction.
11972   //
11973   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
11974     // Note that if our source is a gep chain itself that we wait for that
11975     // chain to be resolved before we perform this transformation.  This
11976     // avoids us creating a TON of code in some cases.
11977     //
11978     if (GetElementPtrInst *SrcGEP =
11979           dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11980       if (SrcGEP->getNumOperands() == 2)
11981         return 0;   // Wait until our source is folded to completion.
11982
11983     SmallVector<Value*, 8> Indices;
11984
11985     // Find out whether the last index in the source GEP is a sequential idx.
11986     bool EndsWithSequential = false;
11987     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11988          I != E; ++I)
11989       EndsWithSequential = !isa<StructType>(*I);
11990
11991     // Can we combine the two pointer arithmetics offsets?
11992     if (EndsWithSequential) {
11993       // Replace: gep (gep %P, long B), long A, ...
11994       // With:    T = long A+B; gep %P, T, ...
11995       //
11996       Value *Sum;
11997       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11998       Value *GO1 = GEP.getOperand(1);
11999       if (SO1 == Constant::getNullValue(SO1->getType())) {
12000         Sum = GO1;
12001       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
12002         Sum = SO1;
12003       } else {
12004         // If they aren't the same type, then the input hasn't been processed
12005         // by the loop above yet (which canonicalizes sequential index types to
12006         // intptr_t).  Just avoid transforming this until the input has been
12007         // normalized.
12008         if (SO1->getType() != GO1->getType())
12009           return 0;
12010         Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
12011       }
12012
12013       // Update the GEP in place if possible.
12014       if (Src->getNumOperands() == 2) {
12015         GEP.setOperand(0, Src->getOperand(0));
12016         GEP.setOperand(1, Sum);
12017         return &GEP;
12018       }
12019       Indices.append(Src->op_begin()+1, Src->op_end()-1);
12020       Indices.push_back(Sum);
12021       Indices.append(GEP.op_begin()+2, GEP.op_end());
12022     } else if (isa<Constant>(*GEP.idx_begin()) &&
12023                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
12024                Src->getNumOperands() != 1) {
12025       // Otherwise we can do the fold if the first index of the GEP is a zero
12026       Indices.append(Src->op_begin()+1, Src->op_end());
12027       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
12028     }
12029
12030     if (!Indices.empty())
12031       return (cast<GEPOperator>(&GEP)->isInBounds() &&
12032               Src->isInBounds()) ?
12033         GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
12034                                           Indices.end(), GEP.getName()) :
12035         GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
12036                                   Indices.end(), GEP.getName());
12037   }
12038   
12039   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
12040   if (Value *X = getBitCastOperand(PtrOp)) {
12041     assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
12042
12043     // If the input bitcast is actually "bitcast(bitcast(x))", then we don't 
12044     // want to change the gep until the bitcasts are eliminated.
12045     if (getBitCastOperand(X)) {
12046       Worklist.AddValue(PtrOp);
12047       return 0;
12048     }
12049     
12050     bool HasZeroPointerIndex = false;
12051     if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
12052       HasZeroPointerIndex = C->isZero();
12053     
12054     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
12055     // into     : GEP [10 x i8]* X, i32 0, ...
12056     //
12057     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
12058     //           into     : GEP i8* X, ...
12059     // 
12060     // This occurs when the program declares an array extern like "int X[];"
12061     if (HasZeroPointerIndex) {
12062       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
12063       const PointerType *XTy = cast<PointerType>(X->getType());
12064       if (const ArrayType *CATy =
12065           dyn_cast<ArrayType>(CPTy->getElementType())) {
12066         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
12067         if (CATy->getElementType() == XTy->getElementType()) {
12068           // -> GEP i8* X, ...
12069           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
12070           return cast<GEPOperator>(&GEP)->isInBounds() ?
12071             GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
12072                                               GEP.getName()) :
12073             GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
12074                                       GEP.getName());
12075         }
12076         
12077         if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
12078           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
12079           if (CATy->getElementType() == XATy->getElementType()) {
12080             // -> GEP [10 x i8]* X, i32 0, ...
12081             // At this point, we know that the cast source type is a pointer
12082             // to an array of the same type as the destination pointer
12083             // array.  Because the array type is never stepped over (there
12084             // is a leading zero) we can fold the cast into this GEP.
12085             GEP.setOperand(0, X);
12086             return &GEP;
12087           }
12088         }
12089       }
12090     } else if (GEP.getNumOperands() == 2) {
12091       // Transform things like:
12092       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
12093       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
12094       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
12095       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
12096       if (TD && isa<ArrayType>(SrcElTy) &&
12097           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
12098           TD->getTypeAllocSize(ResElTy)) {
12099         Value *Idx[2];
12100         Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
12101         Idx[1] = GEP.getOperand(1);
12102         Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
12103           Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
12104           Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
12105         // V and GEP are both pointer types --> BitCast
12106         return new BitCastInst(NewGEP, GEP.getType());
12107       }
12108       
12109       // Transform things like:
12110       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
12111       //   (where tmp = 8*tmp2) into:
12112       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
12113       
12114       if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
12115         uint64_t ArrayEltSize =
12116             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
12117         
12118         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
12119         // allow either a mul, shift, or constant here.
12120         Value *NewIdx = 0;
12121         ConstantInt *Scale = 0;
12122         if (ArrayEltSize == 1) {
12123           NewIdx = GEP.getOperand(1);
12124           Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
12125         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
12126           NewIdx = ConstantInt::get(CI->getType(), 1);
12127           Scale = CI;
12128         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
12129           if (Inst->getOpcode() == Instruction::Shl &&
12130               isa<ConstantInt>(Inst->getOperand(1))) {
12131             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
12132             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
12133             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
12134                                      1ULL << ShAmtVal);
12135             NewIdx = Inst->getOperand(0);
12136           } else if (Inst->getOpcode() == Instruction::Mul &&
12137                      isa<ConstantInt>(Inst->getOperand(1))) {
12138             Scale = cast<ConstantInt>(Inst->getOperand(1));
12139             NewIdx = Inst->getOperand(0);
12140           }
12141         }
12142         
12143         // If the index will be to exactly the right offset with the scale taken
12144         // out, perform the transformation. Note, we don't know whether Scale is
12145         // signed or not. We'll use unsigned version of division/modulo
12146         // operation after making sure Scale doesn't have the sign bit set.
12147         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
12148             Scale->getZExtValue() % ArrayEltSize == 0) {
12149           Scale = ConstantInt::get(Scale->getType(),
12150                                    Scale->getZExtValue() / ArrayEltSize);
12151           if (Scale->getZExtValue() != 1) {
12152             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
12153                                                        false /*ZExt*/);
12154             NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
12155           }
12156
12157           // Insert the new GEP instruction.
12158           Value *Idx[2];
12159           Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
12160           Idx[1] = NewIdx;
12161           Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
12162             Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
12163             Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
12164           // The NewGEP must be pointer typed, so must the old one -> BitCast
12165           return new BitCastInst(NewGEP, GEP.getType());
12166         }
12167       }
12168     }
12169   }
12170   
12171   /// See if we can simplify:
12172   ///   X = bitcast A* to B*
12173   ///   Y = gep X, <...constant indices...>
12174   /// into a gep of the original struct.  This is important for SROA and alias
12175   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
12176   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
12177     if (TD &&
12178         !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
12179       // Determine how much the GEP moves the pointer.  We are guaranteed to get
12180       // a constant back from EmitGEPOffset.
12181       ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, *this));
12182       int64_t Offset = OffsetV->getSExtValue();
12183       
12184       // If this GEP instruction doesn't move the pointer, just replace the GEP
12185       // with a bitcast of the real input to the dest type.
12186       if (Offset == 0) {
12187         // If the bitcast is of an allocation, and the allocation will be
12188         // converted to match the type of the cast, don't touch this.
12189         if (isa<AllocaInst>(BCI->getOperand(0)) ||
12190             isMalloc(BCI->getOperand(0))) {
12191           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
12192           if (Instruction *I = visitBitCast(*BCI)) {
12193             if (I != BCI) {
12194               I->takeName(BCI);
12195               BCI->getParent()->getInstList().insert(BCI, I);
12196               ReplaceInstUsesWith(*BCI, I);
12197             }
12198             return &GEP;
12199           }
12200         }
12201         return new BitCastInst(BCI->getOperand(0), GEP.getType());
12202       }
12203       
12204       // Otherwise, if the offset is non-zero, we need to find out if there is a
12205       // field at Offset in 'A's type.  If so, we can pull the cast through the
12206       // GEP.
12207       SmallVector<Value*, 8> NewIndices;
12208       const Type *InTy =
12209         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
12210       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
12211         Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
12212           Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
12213                                      NewIndices.end()) :
12214           Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
12215                              NewIndices.end());
12216         
12217         if (NGEP->getType() == GEP.getType())
12218           return ReplaceInstUsesWith(GEP, NGEP);
12219         NGEP->takeName(&GEP);
12220         return new BitCastInst(NGEP, GEP.getType());
12221       }
12222     }
12223   }    
12224     
12225   return 0;
12226 }
12227
12228 Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
12229   // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
12230   if (AI.isArrayAllocation()) {  // Check C != 1
12231     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
12232       const Type *NewTy = 
12233         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
12234       assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
12235       AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
12236       New->setAlignment(AI.getAlignment());
12237
12238       // Scan to the end of the allocation instructions, to skip over a block of
12239       // allocas if possible...also skip interleaved debug info
12240       //
12241       BasicBlock::iterator It = New;
12242       while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
12243
12244       // Now that I is pointing to the first non-allocation-inst in the block,
12245       // insert our getelementptr instruction...
12246       //
12247       Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
12248       Value *Idx[2];
12249       Idx[0] = NullIdx;
12250       Idx[1] = NullIdx;
12251       Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
12252                                                    New->getName()+".sub", It);
12253
12254       // Now make everything use the getelementptr instead of the original
12255       // allocation.
12256       return ReplaceInstUsesWith(AI, V);
12257     } else if (isa<UndefValue>(AI.getArraySize())) {
12258       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
12259     }
12260   }
12261
12262   if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
12263     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
12264     // Note that we only do this for alloca's, because malloc should allocate
12265     // and return a unique pointer, even for a zero byte allocation.
12266     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
12267       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
12268
12269     // If the alignment is 0 (unspecified), assign it the preferred alignment.
12270     if (AI.getAlignment() == 0)
12271       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
12272   }
12273
12274   return 0;
12275 }
12276
12277 Instruction *InstCombiner::visitFree(Instruction &FI) {
12278   Value *Op = FI.getOperand(1);
12279
12280   // free undef -> unreachable.
12281   if (isa<UndefValue>(Op)) {
12282     // Insert a new store to null because we cannot modify the CFG here.
12283     new StoreInst(ConstantInt::getTrue(*Context),
12284            UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
12285     return EraseInstFromFunction(FI);
12286   }
12287   
12288   // If we have 'free null' delete the instruction.  This can happen in stl code
12289   // when lots of inlining happens.
12290   if (isa<ConstantPointerNull>(Op))
12291     return EraseInstFromFunction(FI);
12292
12293   // If we have a malloc call whose only use is a free call, delete both.
12294   if (isMalloc(Op)) {
12295     if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
12296       if (Op->hasOneUse() && CI->hasOneUse()) {
12297         EraseInstFromFunction(FI);
12298         EraseInstFromFunction(*CI);
12299         return EraseInstFromFunction(*cast<Instruction>(Op));
12300       }
12301     } else {
12302       // Op is a call to malloc
12303       if (Op->hasOneUse()) {
12304         EraseInstFromFunction(FI);
12305         return EraseInstFromFunction(*cast<Instruction>(Op));
12306       }
12307     }
12308   }
12309
12310   return 0;
12311 }
12312
12313 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
12314 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
12315                                         const TargetData *TD) {
12316   User *CI = cast<User>(LI.getOperand(0));
12317   Value *CastOp = CI->getOperand(0);
12318   LLVMContext *Context = IC.getContext();
12319
12320   const PointerType *DestTy = cast<PointerType>(CI->getType());
12321   const Type *DestPTy = DestTy->getElementType();
12322   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
12323
12324     // If the address spaces don't match, don't eliminate the cast.
12325     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
12326       return 0;
12327
12328     const Type *SrcPTy = SrcTy->getElementType();
12329
12330     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
12331          isa<VectorType>(DestPTy)) {
12332       // If the source is an array, the code below will not succeed.  Check to
12333       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
12334       // constants.
12335       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
12336         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
12337           if (ASrcTy->getNumElements() != 0) {
12338             Value *Idxs[2];
12339             Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
12340             Idxs[1] = Idxs[0];
12341             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
12342             SrcTy = cast<PointerType>(CastOp->getType());
12343             SrcPTy = SrcTy->getElementType();
12344           }
12345
12346       if (IC.getTargetData() &&
12347           (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
12348             isa<VectorType>(SrcPTy)) &&
12349           // Do not allow turning this into a load of an integer, which is then
12350           // casted to a pointer, this pessimizes pointer analysis a lot.
12351           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
12352           IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
12353                IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
12354
12355         // Okay, we are casting from one integer or pointer type to another of
12356         // the same size.  Instead of casting the pointer before the load, cast
12357         // the result of the loaded value.
12358         Value *NewLoad = 
12359           IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
12360         // Now cast the result of the load.
12361         return new BitCastInst(NewLoad, LI.getType());
12362       }
12363     }
12364   }
12365   return 0;
12366 }
12367
12368 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
12369   Value *Op = LI.getOperand(0);
12370
12371   // Attempt to improve the alignment.
12372   if (TD) {
12373     unsigned KnownAlign =
12374       GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
12375     if (KnownAlign >
12376         (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
12377                                   LI.getAlignment()))
12378       LI.setAlignment(KnownAlign);
12379   }
12380
12381   // load (cast X) --> cast (load X) iff safe.
12382   if (isa<CastInst>(Op))
12383     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
12384       return Res;
12385
12386   // None of the following transforms are legal for volatile loads.
12387   if (LI.isVolatile()) return 0;
12388   
12389   // Do really simple store-to-load forwarding and load CSE, to catch cases
12390   // where there are several consequtive memory accesses to the same location,
12391   // separated by a few arithmetic operations.
12392   BasicBlock::iterator BBI = &LI;
12393   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
12394     return ReplaceInstUsesWith(LI, AvailableVal);
12395
12396   // load(gep null, ...) -> unreachable
12397   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
12398     const Value *GEPI0 = GEPI->getOperand(0);
12399     // TODO: Consider a target hook for valid address spaces for this xform.
12400     if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
12401       // Insert a new store to null instruction before the load to indicate
12402       // that this code is not reachable.  We do this instead of inserting
12403       // an unreachable instruction directly because we cannot modify the
12404       // CFG.
12405       new StoreInst(UndefValue::get(LI.getType()),
12406                     Constant::getNullValue(Op->getType()), &LI);
12407       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
12408     }
12409   } 
12410
12411   // load null/undef -> unreachable
12412   // TODO: Consider a target hook for valid address spaces for this xform.
12413   if (isa<UndefValue>(Op) ||
12414       (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
12415     // Insert a new store to null instruction before the load to indicate that
12416     // this code is not reachable.  We do this instead of inserting an
12417     // unreachable instruction directly because we cannot modify the CFG.
12418     new StoreInst(UndefValue::get(LI.getType()),
12419                   Constant::getNullValue(Op->getType()), &LI);
12420     return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
12421   }
12422
12423   // Instcombine load (constantexpr_cast global) -> cast (load global)
12424   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
12425     if (CE->isCast())
12426       if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
12427         return Res;
12428   
12429   if (Op->hasOneUse()) {
12430     // Change select and PHI nodes to select values instead of addresses: this
12431     // helps alias analysis out a lot, allows many others simplifications, and
12432     // exposes redundancy in the code.
12433     //
12434     // Note that we cannot do the transformation unless we know that the
12435     // introduced loads cannot trap!  Something like this is valid as long as
12436     // the condition is always false: load (select bool %C, int* null, int* %G),
12437     // but it would not be valid if we transformed it to load from null
12438     // unconditionally.
12439     //
12440     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
12441       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
12442       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
12443           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
12444         Value *V1 = Builder->CreateLoad(SI->getOperand(1),
12445                                         SI->getOperand(1)->getName()+".val");
12446         Value *V2 = Builder->CreateLoad(SI->getOperand(2),
12447                                         SI->getOperand(2)->getName()+".val");
12448         return SelectInst::Create(SI->getCondition(), V1, V2);
12449       }
12450
12451       // load (select (cond, null, P)) -> load P
12452       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
12453         if (C->isNullValue()) {
12454           LI.setOperand(0, SI->getOperand(2));
12455           return &LI;
12456         }
12457
12458       // load (select (cond, P, null)) -> load P
12459       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
12460         if (C->isNullValue()) {
12461           LI.setOperand(0, SI->getOperand(1));
12462           return &LI;
12463         }
12464     }
12465   }
12466   return 0;
12467 }
12468
12469 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
12470 /// when possible.  This makes it generally easy to do alias analysis and/or
12471 /// SROA/mem2reg of the memory object.
12472 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
12473   User *CI = cast<User>(SI.getOperand(1));
12474   Value *CastOp = CI->getOperand(0);
12475
12476   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
12477   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
12478   if (SrcTy == 0) return 0;
12479   
12480   const Type *SrcPTy = SrcTy->getElementType();
12481
12482   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
12483     return 0;
12484   
12485   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
12486   /// to its first element.  This allows us to handle things like:
12487   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
12488   /// on 32-bit hosts.
12489   SmallVector<Value*, 4> NewGEPIndices;
12490   
12491   // If the source is an array, the code below will not succeed.  Check to
12492   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
12493   // constants.
12494   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
12495     // Index through pointer.
12496     Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
12497     NewGEPIndices.push_back(Zero);
12498     
12499     while (1) {
12500       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
12501         if (!STy->getNumElements()) /* Struct can be empty {} */
12502           break;
12503         NewGEPIndices.push_back(Zero);
12504         SrcPTy = STy->getElementType(0);
12505       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
12506         NewGEPIndices.push_back(Zero);
12507         SrcPTy = ATy->getElementType();
12508       } else {
12509         break;
12510       }
12511     }
12512     
12513     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
12514   }
12515
12516   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
12517     return 0;
12518   
12519   // If the pointers point into different address spaces or if they point to
12520   // values with different sizes, we can't do the transformation.
12521   if (!IC.getTargetData() ||
12522       SrcTy->getAddressSpace() != 
12523         cast<PointerType>(CI->getType())->getAddressSpace() ||
12524       IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
12525       IC.getTargetData()->getTypeSizeInBits(DestPTy))
12526     return 0;
12527
12528   // Okay, we are casting from one integer or pointer type to another of
12529   // the same size.  Instead of casting the pointer before 
12530   // the store, cast the value to be stored.
12531   Value *NewCast;
12532   Value *SIOp0 = SI.getOperand(0);
12533   Instruction::CastOps opcode = Instruction::BitCast;
12534   const Type* CastSrcTy = SIOp0->getType();
12535   const Type* CastDstTy = SrcPTy;
12536   if (isa<PointerType>(CastDstTy)) {
12537     if (CastSrcTy->isInteger())
12538       opcode = Instruction::IntToPtr;
12539   } else if (isa<IntegerType>(CastDstTy)) {
12540     if (isa<PointerType>(SIOp0->getType()))
12541       opcode = Instruction::PtrToInt;
12542   }
12543   
12544   // SIOp0 is a pointer to aggregate and this is a store to the first field,
12545   // emit a GEP to index into its first field.
12546   if (!NewGEPIndices.empty())
12547     CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
12548                                            NewGEPIndices.end());
12549   
12550   NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
12551                                    SIOp0->getName()+".c");
12552   return new StoreInst(NewCast, CastOp);
12553 }
12554
12555 /// equivalentAddressValues - Test if A and B will obviously have the same
12556 /// value. This includes recognizing that %t0 and %t1 will have the same
12557 /// value in code like this:
12558 ///   %t0 = getelementptr \@a, 0, 3
12559 ///   store i32 0, i32* %t0
12560 ///   %t1 = getelementptr \@a, 0, 3
12561 ///   %t2 = load i32* %t1
12562 ///
12563 static bool equivalentAddressValues(Value *A, Value *B) {
12564   // Test if the values are trivially equivalent.
12565   if (A == B) return true;
12566   
12567   // Test if the values come form identical arithmetic instructions.
12568   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
12569   // its only used to compare two uses within the same basic block, which
12570   // means that they'll always either have the same value or one of them
12571   // will have an undefined value.
12572   if (isa<BinaryOperator>(A) ||
12573       isa<CastInst>(A) ||
12574       isa<PHINode>(A) ||
12575       isa<GetElementPtrInst>(A))
12576     if (Instruction *BI = dyn_cast<Instruction>(B))
12577       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
12578         return true;
12579   
12580   // Otherwise they may not be equivalent.
12581   return false;
12582 }
12583
12584 // If this instruction has two uses, one of which is a llvm.dbg.declare,
12585 // return the llvm.dbg.declare.
12586 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
12587   if (!V->hasNUses(2))
12588     return 0;
12589   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
12590        UI != E; ++UI) {
12591     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
12592       return DI;
12593     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
12594       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
12595         return DI;
12596       }
12597   }
12598   return 0;
12599 }
12600
12601 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
12602   Value *Val = SI.getOperand(0);
12603   Value *Ptr = SI.getOperand(1);
12604
12605   // If the RHS is an alloca with a single use, zapify the store, making the
12606   // alloca dead.
12607   // If the RHS is an alloca with a two uses, the other one being a 
12608   // llvm.dbg.declare, zapify the store and the declare, making the
12609   // alloca dead.  We must do this to prevent declare's from affecting
12610   // codegen.
12611   if (!SI.isVolatile()) {
12612     if (Ptr->hasOneUse()) {
12613       if (isa<AllocaInst>(Ptr)) {
12614         EraseInstFromFunction(SI);
12615         ++NumCombined;
12616         return 0;
12617       }
12618       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
12619         if (isa<AllocaInst>(GEP->getOperand(0))) {
12620           if (GEP->getOperand(0)->hasOneUse()) {
12621             EraseInstFromFunction(SI);
12622             ++NumCombined;
12623             return 0;
12624           }
12625           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
12626             EraseInstFromFunction(*DI);
12627             EraseInstFromFunction(SI);
12628             ++NumCombined;
12629             return 0;
12630           }
12631         }
12632       }
12633     }
12634     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
12635       EraseInstFromFunction(*DI);
12636       EraseInstFromFunction(SI);
12637       ++NumCombined;
12638       return 0;
12639     }
12640   }
12641
12642   // Attempt to improve the alignment.
12643   if (TD) {
12644     unsigned KnownAlign =
12645       GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
12646     if (KnownAlign >
12647         (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
12648                                   SI.getAlignment()))
12649       SI.setAlignment(KnownAlign);
12650   }
12651
12652   // Do really simple DSE, to catch cases where there are several consecutive
12653   // stores to the same location, separated by a few arithmetic operations. This
12654   // situation often occurs with bitfield accesses.
12655   BasicBlock::iterator BBI = &SI;
12656   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
12657        --ScanInsts) {
12658     --BBI;
12659     // Don't count debug info directives, lest they affect codegen,
12660     // and we skip pointer-to-pointer bitcasts, which are NOPs.
12661     // It is necessary for correctness to skip those that feed into a
12662     // llvm.dbg.declare, as these are not present when debugging is off.
12663     if (isa<DbgInfoIntrinsic>(BBI) ||
12664         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12665       ScanInsts++;
12666       continue;
12667     }    
12668     
12669     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
12670       // Prev store isn't volatile, and stores to the same location?
12671       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
12672                                                           SI.getOperand(1))) {
12673         ++NumDeadStore;
12674         ++BBI;
12675         EraseInstFromFunction(*PrevSI);
12676         continue;
12677       }
12678       break;
12679     }
12680     
12681     // If this is a load, we have to stop.  However, if the loaded value is from
12682     // the pointer we're loading and is producing the pointer we're storing,
12683     // then *this* store is dead (X = load P; store X -> P).
12684     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
12685       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
12686           !SI.isVolatile()) {
12687         EraseInstFromFunction(SI);
12688         ++NumCombined;
12689         return 0;
12690       }
12691       // Otherwise, this is a load from some other location.  Stores before it
12692       // may not be dead.
12693       break;
12694     }
12695     
12696     // Don't skip over loads or things that can modify memory.
12697     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
12698       break;
12699   }
12700   
12701   
12702   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
12703
12704   // store X, null    -> turns into 'unreachable' in SimplifyCFG
12705   if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
12706     if (!isa<UndefValue>(Val)) {
12707       SI.setOperand(0, UndefValue::get(Val->getType()));
12708       if (Instruction *U = dyn_cast<Instruction>(Val))
12709         Worklist.Add(U);  // Dropped a use.
12710       ++NumCombined;
12711     }
12712     return 0;  // Do not modify these!
12713   }
12714
12715   // store undef, Ptr -> noop
12716   if (isa<UndefValue>(Val)) {
12717     EraseInstFromFunction(SI);
12718     ++NumCombined;
12719     return 0;
12720   }
12721
12722   // If the pointer destination is a cast, see if we can fold the cast into the
12723   // source instead.
12724   if (isa<CastInst>(Ptr))
12725     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12726       return Res;
12727   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
12728     if (CE->isCast())
12729       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12730         return Res;
12731
12732   
12733   // If this store is the last instruction in the basic block (possibly
12734   // excepting debug info instructions and the pointer bitcasts that feed
12735   // into them), and if the block ends with an unconditional branch, try
12736   // to move it to the successor block.
12737   BBI = &SI; 
12738   do {
12739     ++BBI;
12740   } while (isa<DbgInfoIntrinsic>(BBI) ||
12741            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
12742   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
12743     if (BI->isUnconditional())
12744       if (SimplifyStoreAtEndOfBlock(SI))
12745         return 0;  // xform done!
12746   
12747   return 0;
12748 }
12749
12750 /// SimplifyStoreAtEndOfBlock - Turn things like:
12751 ///   if () { *P = v1; } else { *P = v2 }
12752 /// into a phi node with a store in the successor.
12753 ///
12754 /// Simplify things like:
12755 ///   *P = v1; if () { *P = v2; }
12756 /// into a phi node with a store in the successor.
12757 ///
12758 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12759   BasicBlock *StoreBB = SI.getParent();
12760   
12761   // Check to see if the successor block has exactly two incoming edges.  If
12762   // so, see if the other predecessor contains a store to the same location.
12763   // if so, insert a PHI node (if needed) and move the stores down.
12764   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
12765   
12766   // Determine whether Dest has exactly two predecessors and, if so, compute
12767   // the other predecessor.
12768   pred_iterator PI = pred_begin(DestBB);
12769   BasicBlock *OtherBB = 0;
12770   if (*PI != StoreBB)
12771     OtherBB = *PI;
12772   ++PI;
12773   if (PI == pred_end(DestBB))
12774     return false;
12775   
12776   if (*PI != StoreBB) {
12777     if (OtherBB)
12778       return false;
12779     OtherBB = *PI;
12780   }
12781   if (++PI != pred_end(DestBB))
12782     return false;
12783
12784   // Bail out if all the relevant blocks aren't distinct (this can happen,
12785   // for example, if SI is in an infinite loop)
12786   if (StoreBB == DestBB || OtherBB == DestBB)
12787     return false;
12788
12789   // Verify that the other block ends in a branch and is not otherwise empty.
12790   BasicBlock::iterator BBI = OtherBB->getTerminator();
12791   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12792   if (!OtherBr || BBI == OtherBB->begin())
12793     return false;
12794   
12795   // If the other block ends in an unconditional branch, check for the 'if then
12796   // else' case.  there is an instruction before the branch.
12797   StoreInst *OtherStore = 0;
12798   if (OtherBr->isUnconditional()) {
12799     --BBI;
12800     // Skip over debugging info.
12801     while (isa<DbgInfoIntrinsic>(BBI) ||
12802            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12803       if (BBI==OtherBB->begin())
12804         return false;
12805       --BBI;
12806     }
12807     // If this isn't a store, isn't a store to the same location, or if the
12808     // alignments differ, bail out.
12809     OtherStore = dyn_cast<StoreInst>(BBI);
12810     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
12811         OtherStore->getAlignment() != SI.getAlignment())
12812       return false;
12813   } else {
12814     // Otherwise, the other block ended with a conditional branch. If one of the
12815     // destinations is StoreBB, then we have the if/then case.
12816     if (OtherBr->getSuccessor(0) != StoreBB && 
12817         OtherBr->getSuccessor(1) != StoreBB)
12818       return false;
12819     
12820     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12821     // if/then triangle.  See if there is a store to the same ptr as SI that
12822     // lives in OtherBB.
12823     for (;; --BBI) {
12824       // Check to see if we find the matching store.
12825       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12826         if (OtherStore->getOperand(1) != SI.getOperand(1) ||
12827             OtherStore->getAlignment() != SI.getAlignment())
12828           return false;
12829         break;
12830       }
12831       // If we find something that may be using or overwriting the stored
12832       // value, or if we run out of instructions, we can't do the xform.
12833       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12834           BBI == OtherBB->begin())
12835         return false;
12836     }
12837     
12838     // In order to eliminate the store in OtherBr, we have to
12839     // make sure nothing reads or overwrites the stored value in
12840     // StoreBB.
12841     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12842       // FIXME: This should really be AA driven.
12843       if (I->mayReadFromMemory() || I->mayWriteToMemory())
12844         return false;
12845     }
12846   }
12847   
12848   // Insert a PHI node now if we need it.
12849   Value *MergedVal = OtherStore->getOperand(0);
12850   if (MergedVal != SI.getOperand(0)) {
12851     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12852     PN->reserveOperandSpace(2);
12853     PN->addIncoming(SI.getOperand(0), SI.getParent());
12854     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12855     MergedVal = InsertNewInstBefore(PN, DestBB->front());
12856   }
12857   
12858   // Advance to a place where it is safe to insert the new store and
12859   // insert it.
12860   BBI = DestBB->getFirstNonPHI();
12861   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12862                                     OtherStore->isVolatile(),
12863                                     SI.getAlignment()), *BBI);
12864   
12865   // Nuke the old stores.
12866   EraseInstFromFunction(SI);
12867   EraseInstFromFunction(*OtherStore);
12868   ++NumCombined;
12869   return true;
12870 }
12871
12872
12873 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12874   // Change br (not X), label True, label False to: br X, label False, True
12875   Value *X = 0;
12876   BasicBlock *TrueDest;
12877   BasicBlock *FalseDest;
12878   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
12879       !isa<Constant>(X)) {
12880     // Swap Destinations and condition...
12881     BI.setCondition(X);
12882     BI.setSuccessor(0, FalseDest);
12883     BI.setSuccessor(1, TrueDest);
12884     return &BI;
12885   }
12886
12887   // Cannonicalize fcmp_one -> fcmp_oeq
12888   FCmpInst::Predicate FPred; Value *Y;
12889   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12890                              TrueDest, FalseDest)) &&
12891       BI.getCondition()->hasOneUse())
12892     if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12893         FPred == FCmpInst::FCMP_OGE) {
12894       FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12895       Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12896       
12897       // Swap Destinations and condition.
12898       BI.setSuccessor(0, FalseDest);
12899       BI.setSuccessor(1, TrueDest);
12900       Worklist.Add(Cond);
12901       return &BI;
12902     }
12903
12904   // Cannonicalize icmp_ne -> icmp_eq
12905   ICmpInst::Predicate IPred;
12906   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12907                       TrueDest, FalseDest)) &&
12908       BI.getCondition()->hasOneUse())
12909     if (IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12910         IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12911         IPred == ICmpInst::ICMP_SGE) {
12912       ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12913       Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12914       // Swap Destinations and condition.
12915       BI.setSuccessor(0, FalseDest);
12916       BI.setSuccessor(1, TrueDest);
12917       Worklist.Add(Cond);
12918       return &BI;
12919     }
12920
12921   return 0;
12922 }
12923
12924 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12925   Value *Cond = SI.getCondition();
12926   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12927     if (I->getOpcode() == Instruction::Add)
12928       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12929         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12930         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12931           SI.setOperand(i,
12932                    ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
12933                                                 AddRHS));
12934         SI.setOperand(0, I->getOperand(0));
12935         Worklist.Add(I);
12936         return &SI;
12937       }
12938   }
12939   return 0;
12940 }
12941
12942 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12943   Value *Agg = EV.getAggregateOperand();
12944
12945   if (!EV.hasIndices())
12946     return ReplaceInstUsesWith(EV, Agg);
12947
12948   if (Constant *C = dyn_cast<Constant>(Agg)) {
12949     if (isa<UndefValue>(C))
12950       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12951       
12952     if (isa<ConstantAggregateZero>(C))
12953       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12954
12955     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12956       // Extract the element indexed by the first index out of the constant
12957       Value *V = C->getOperand(*EV.idx_begin());
12958       if (EV.getNumIndices() > 1)
12959         // Extract the remaining indices out of the constant indexed by the
12960         // first index
12961         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12962       else
12963         return ReplaceInstUsesWith(EV, V);
12964     }
12965     return 0; // Can't handle other constants
12966   } 
12967   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12968     // We're extracting from an insertvalue instruction, compare the indices
12969     const unsigned *exti, *exte, *insi, *inse;
12970     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12971          exte = EV.idx_end(), inse = IV->idx_end();
12972          exti != exte && insi != inse;
12973          ++exti, ++insi) {
12974       if (*insi != *exti)
12975         // The insert and extract both reference distinctly different elements.
12976         // This means the extract is not influenced by the insert, and we can
12977         // replace the aggregate operand of the extract with the aggregate
12978         // operand of the insert. i.e., replace
12979         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12980         // %E = extractvalue { i32, { i32 } } %I, 0
12981         // with
12982         // %E = extractvalue { i32, { i32 } } %A, 0
12983         return ExtractValueInst::Create(IV->getAggregateOperand(),
12984                                         EV.idx_begin(), EV.idx_end());
12985     }
12986     if (exti == exte && insi == inse)
12987       // Both iterators are at the end: Index lists are identical. Replace
12988       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12989       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12990       // with "i32 42"
12991       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12992     if (exti == exte) {
12993       // The extract list is a prefix of the insert list. i.e. replace
12994       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12995       // %E = extractvalue { i32, { i32 } } %I, 1
12996       // with
12997       // %X = extractvalue { i32, { i32 } } %A, 1
12998       // %E = insertvalue { i32 } %X, i32 42, 0
12999       // by switching the order of the insert and extract (though the
13000       // insertvalue should be left in, since it may have other uses).
13001       Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
13002                                                  EV.idx_begin(), EV.idx_end());
13003       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
13004                                      insi, inse);
13005     }
13006     if (insi == inse)
13007       // The insert list is a prefix of the extract list
13008       // We can simply remove the common indices from the extract and make it
13009       // operate on the inserted value instead of the insertvalue result.
13010       // i.e., replace
13011       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
13012       // %E = extractvalue { i32, { i32 } } %I, 1, 0
13013       // with
13014       // %E extractvalue { i32 } { i32 42 }, 0
13015       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
13016                                       exti, exte);
13017   }
13018   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
13019     // We're extracting from an intrinsic, see if we're the only user, which
13020     // allows us to simplify multiple result intrinsics to simpler things that
13021     // just get one value..
13022     if (II->hasOneUse()) {
13023       // Check if we're grabbing the overflow bit or the result of a 'with
13024       // overflow' intrinsic.  If it's the latter we can remove the intrinsic
13025       // and replace it with a traditional binary instruction.
13026       switch (II->getIntrinsicID()) {
13027       case Intrinsic::uadd_with_overflow:
13028       case Intrinsic::sadd_with_overflow:
13029         if (*EV.idx_begin() == 0) {  // Normal result.
13030           Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
13031           II->replaceAllUsesWith(UndefValue::get(II->getType()));
13032           EraseInstFromFunction(*II);
13033           return BinaryOperator::CreateAdd(LHS, RHS);
13034         }
13035         break;
13036       case Intrinsic::usub_with_overflow:
13037       case Intrinsic::ssub_with_overflow:
13038         if (*EV.idx_begin() == 0) {  // Normal result.
13039           Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
13040           II->replaceAllUsesWith(UndefValue::get(II->getType()));
13041           EraseInstFromFunction(*II);
13042           return BinaryOperator::CreateSub(LHS, RHS);
13043         }
13044         break;
13045       case Intrinsic::umul_with_overflow:
13046       case Intrinsic::smul_with_overflow:
13047         if (*EV.idx_begin() == 0) {  // Normal result.
13048           Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
13049           II->replaceAllUsesWith(UndefValue::get(II->getType()));
13050           EraseInstFromFunction(*II);
13051           return BinaryOperator::CreateMul(LHS, RHS);
13052         }
13053         break;
13054       default:
13055         break;
13056       }
13057     }
13058   }
13059   // Can't simplify extracts from other values. Note that nested extracts are
13060   // already simplified implicitely by the above (extract ( extract (insert) )
13061   // will be translated into extract ( insert ( extract ) ) first and then just
13062   // the value inserted, if appropriate).
13063   return 0;
13064 }
13065
13066 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
13067 /// is to leave as a vector operation.
13068 static bool CheapToScalarize(Value *V, bool isConstant) {
13069   if (isa<ConstantAggregateZero>(V)) 
13070     return true;
13071   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
13072     if (isConstant) return true;
13073     // If all elts are the same, we can extract.
13074     Constant *Op0 = C->getOperand(0);
13075     for (unsigned i = 1; i < C->getNumOperands(); ++i)
13076       if (C->getOperand(i) != Op0)
13077         return false;
13078     return true;
13079   }
13080   Instruction *I = dyn_cast<Instruction>(V);
13081   if (!I) return false;
13082   
13083   // Insert element gets simplified to the inserted element or is deleted if
13084   // this is constant idx extract element and its a constant idx insertelt.
13085   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
13086       isa<ConstantInt>(I->getOperand(2)))
13087     return true;
13088   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
13089     return true;
13090   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
13091     if (BO->hasOneUse() &&
13092         (CheapToScalarize(BO->getOperand(0), isConstant) ||
13093          CheapToScalarize(BO->getOperand(1), isConstant)))
13094       return true;
13095   if (CmpInst *CI = dyn_cast<CmpInst>(I))
13096     if (CI->hasOneUse() &&
13097         (CheapToScalarize(CI->getOperand(0), isConstant) ||
13098          CheapToScalarize(CI->getOperand(1), isConstant)))
13099       return true;
13100   
13101   return false;
13102 }
13103
13104 /// Read and decode a shufflevector mask.
13105 ///
13106 /// It turns undef elements into values that are larger than the number of
13107 /// elements in the input.
13108 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
13109   unsigned NElts = SVI->getType()->getNumElements();
13110   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
13111     return std::vector<unsigned>(NElts, 0);
13112   if (isa<UndefValue>(SVI->getOperand(2)))
13113     return std::vector<unsigned>(NElts, 2*NElts);
13114
13115   std::vector<unsigned> Result;
13116   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
13117   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
13118     if (isa<UndefValue>(*i))
13119       Result.push_back(NElts*2);  // undef -> 8
13120     else
13121       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
13122   return Result;
13123 }
13124
13125 /// FindScalarElement - Given a vector and an element number, see if the scalar
13126 /// value is already around as a register, for example if it were inserted then
13127 /// extracted from the vector.
13128 static Value *FindScalarElement(Value *V, unsigned EltNo,
13129                                 LLVMContext *Context) {
13130   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
13131   const VectorType *PTy = cast<VectorType>(V->getType());
13132   unsigned Width = PTy->getNumElements();
13133   if (EltNo >= Width)  // Out of range access.
13134     return UndefValue::get(PTy->getElementType());
13135   
13136   if (isa<UndefValue>(V))
13137     return UndefValue::get(PTy->getElementType());
13138   else if (isa<ConstantAggregateZero>(V))
13139     return Constant::getNullValue(PTy->getElementType());
13140   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
13141     return CP->getOperand(EltNo);
13142   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
13143     // If this is an insert to a variable element, we don't know what it is.
13144     if (!isa<ConstantInt>(III->getOperand(2))) 
13145       return 0;
13146     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
13147     
13148     // If this is an insert to the element we are looking for, return the
13149     // inserted value.
13150     if (EltNo == IIElt) 
13151       return III->getOperand(1);
13152     
13153     // Otherwise, the insertelement doesn't modify the value, recurse on its
13154     // vector input.
13155     return FindScalarElement(III->getOperand(0), EltNo, Context);
13156   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
13157     unsigned LHSWidth =
13158       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
13159     unsigned InEl = getShuffleMask(SVI)[EltNo];
13160     if (InEl < LHSWidth)
13161       return FindScalarElement(SVI->getOperand(0), InEl, Context);
13162     else if (InEl < LHSWidth*2)
13163       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
13164     else
13165       return UndefValue::get(PTy->getElementType());
13166   }
13167   
13168   // Otherwise, we don't know.
13169   return 0;
13170 }
13171
13172 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
13173   // If vector val is undef, replace extract with scalar undef.
13174   if (isa<UndefValue>(EI.getOperand(0)))
13175     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
13176
13177   // If vector val is constant 0, replace extract with scalar 0.
13178   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
13179     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
13180   
13181   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
13182     // If vector val is constant with all elements the same, replace EI with
13183     // that element. When the elements are not identical, we cannot replace yet
13184     // (we do that below, but only when the index is constant).
13185     Constant *op0 = C->getOperand(0);
13186     for (unsigned i = 1; i != C->getNumOperands(); ++i)
13187       if (C->getOperand(i) != op0) {
13188         op0 = 0; 
13189         break;
13190       }
13191     if (op0)
13192       return ReplaceInstUsesWith(EI, op0);
13193   }
13194   
13195   // If extracting a specified index from the vector, see if we can recursively
13196   // find a previously computed scalar that was inserted into the vector.
13197   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
13198     unsigned IndexVal = IdxC->getZExtValue();
13199     unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
13200       
13201     // If this is extracting an invalid index, turn this into undef, to avoid
13202     // crashing the code below.
13203     if (IndexVal >= VectorWidth)
13204       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
13205     
13206     // This instruction only demands the single element from the input vector.
13207     // If the input vector has a single use, simplify it based on this use
13208     // property.
13209     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
13210       APInt UndefElts(VectorWidth, 0);
13211       APInt DemandedMask(VectorWidth, 1 << IndexVal);
13212       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
13213                                                 DemandedMask, UndefElts)) {
13214         EI.setOperand(0, V);
13215         return &EI;
13216       }
13217     }
13218     
13219     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
13220       return ReplaceInstUsesWith(EI, Elt);
13221     
13222     // If the this extractelement is directly using a bitcast from a vector of
13223     // the same number of elements, see if we can find the source element from
13224     // it.  In this case, we will end up needing to bitcast the scalars.
13225     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
13226       if (const VectorType *VT = 
13227               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
13228         if (VT->getNumElements() == VectorWidth)
13229           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
13230                                              IndexVal, Context))
13231             return new BitCastInst(Elt, EI.getType());
13232     }
13233   }
13234   
13235   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
13236     // Push extractelement into predecessor operation if legal and
13237     // profitable to do so
13238     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
13239       if (I->hasOneUse() &&
13240           CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
13241         Value *newEI0 =
13242           Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
13243                                         EI.getName()+".lhs");
13244         Value *newEI1 =
13245           Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
13246                                         EI.getName()+".rhs");
13247         return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
13248       }
13249     } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
13250       // Extracting the inserted element?
13251       if (IE->getOperand(2) == EI.getOperand(1))
13252         return ReplaceInstUsesWith(EI, IE->getOperand(1));
13253       // If the inserted and extracted elements are constants, they must not
13254       // be the same value, extract from the pre-inserted value instead.
13255       if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
13256         Worklist.AddValue(EI.getOperand(0));
13257         EI.setOperand(0, IE->getOperand(0));
13258         return &EI;
13259       }
13260     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
13261       // If this is extracting an element from a shufflevector, figure out where
13262       // it came from and extract from the appropriate input element instead.
13263       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
13264         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
13265         Value *Src;
13266         unsigned LHSWidth =
13267           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
13268
13269         if (SrcIdx < LHSWidth)
13270           Src = SVI->getOperand(0);
13271         else if (SrcIdx < LHSWidth*2) {
13272           SrcIdx -= LHSWidth;
13273           Src = SVI->getOperand(1);
13274         } else {
13275           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
13276         }
13277         return ExtractElementInst::Create(Src,
13278                          ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
13279                                           false));
13280       }
13281     }
13282     // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
13283   }
13284   return 0;
13285 }
13286
13287 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
13288 /// elements from either LHS or RHS, return the shuffle mask and true. 
13289 /// Otherwise, return false.
13290 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
13291                                          std::vector<Constant*> &Mask,
13292                                          LLVMContext *Context) {
13293   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
13294          "Invalid CollectSingleShuffleElements");
13295   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
13296
13297   if (isa<UndefValue>(V)) {
13298     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
13299     return true;
13300   } else if (V == LHS) {
13301     for (unsigned i = 0; i != NumElts; ++i)
13302       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
13303     return true;
13304   } else if (V == RHS) {
13305     for (unsigned i = 0; i != NumElts; ++i)
13306       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
13307     return true;
13308   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
13309     // If this is an insert of an extract from some other vector, include it.
13310     Value *VecOp    = IEI->getOperand(0);
13311     Value *ScalarOp = IEI->getOperand(1);
13312     Value *IdxOp    = IEI->getOperand(2);
13313     
13314     if (!isa<ConstantInt>(IdxOp))
13315       return false;
13316     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
13317     
13318     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
13319       // Okay, we can handle this if the vector we are insertinting into is
13320       // transitively ok.
13321       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
13322         // If so, update the mask to reflect the inserted undef.
13323         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
13324         return true;
13325       }      
13326     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
13327       if (isa<ConstantInt>(EI->getOperand(1)) &&
13328           EI->getOperand(0)->getType() == V->getType()) {
13329         unsigned ExtractedIdx =
13330           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13331         
13332         // This must be extracting from either LHS or RHS.
13333         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
13334           // Okay, we can handle this if the vector we are insertinting into is
13335           // transitively ok.
13336           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
13337             // If so, update the mask to reflect the inserted value.
13338             if (EI->getOperand(0) == LHS) {
13339               Mask[InsertedIdx % NumElts] = 
13340                  ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
13341             } else {
13342               assert(EI->getOperand(0) == RHS);
13343               Mask[InsertedIdx % NumElts] = 
13344                 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
13345               
13346             }
13347             return true;
13348           }
13349         }
13350       }
13351     }
13352   }
13353   // TODO: Handle shufflevector here!
13354   
13355   return false;
13356 }
13357
13358 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
13359 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
13360 /// that computes V and the LHS value of the shuffle.
13361 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
13362                                      Value *&RHS, LLVMContext *Context) {
13363   assert(isa<VectorType>(V->getType()) && 
13364          (RHS == 0 || V->getType() == RHS->getType()) &&
13365          "Invalid shuffle!");
13366   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
13367
13368   if (isa<UndefValue>(V)) {
13369     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
13370     return V;
13371   } else if (isa<ConstantAggregateZero>(V)) {
13372     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
13373     return V;
13374   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
13375     // If this is an insert of an extract from some other vector, include it.
13376     Value *VecOp    = IEI->getOperand(0);
13377     Value *ScalarOp = IEI->getOperand(1);
13378     Value *IdxOp    = IEI->getOperand(2);
13379     
13380     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13381       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13382           EI->getOperand(0)->getType() == V->getType()) {
13383         unsigned ExtractedIdx =
13384           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13385         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
13386         
13387         // Either the extracted from or inserted into vector must be RHSVec,
13388         // otherwise we'd end up with a shuffle of three inputs.
13389         if (EI->getOperand(0) == RHS || RHS == 0) {
13390           RHS = EI->getOperand(0);
13391           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
13392           Mask[InsertedIdx % NumElts] = 
13393             ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
13394           return V;
13395         }
13396         
13397         if (VecOp == RHS) {
13398           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
13399                                             RHS, Context);
13400           // Everything but the extracted element is replaced with the RHS.
13401           for (unsigned i = 0; i != NumElts; ++i) {
13402             if (i != InsertedIdx)
13403               Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
13404           }
13405           return V;
13406         }
13407         
13408         // If this insertelement is a chain that comes from exactly these two
13409         // vectors, return the vector and the effective shuffle.
13410         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
13411                                          Context))
13412           return EI->getOperand(0);
13413         
13414       }
13415     }
13416   }
13417   // TODO: Handle shufflevector here!
13418   
13419   // Otherwise, can't do anything fancy.  Return an identity vector.
13420   for (unsigned i = 0; i != NumElts; ++i)
13421     Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
13422   return V;
13423 }
13424
13425 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
13426   Value *VecOp    = IE.getOperand(0);
13427   Value *ScalarOp = IE.getOperand(1);
13428   Value *IdxOp    = IE.getOperand(2);
13429   
13430   // Inserting an undef or into an undefined place, remove this.
13431   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
13432     ReplaceInstUsesWith(IE, VecOp);
13433   
13434   // If the inserted element was extracted from some other vector, and if the 
13435   // indexes are constant, try to turn this into a shufflevector operation.
13436   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13437     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13438         EI->getOperand(0)->getType() == IE.getType()) {
13439       unsigned NumVectorElts = IE.getType()->getNumElements();
13440       unsigned ExtractedIdx =
13441         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13442       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
13443       
13444       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
13445         return ReplaceInstUsesWith(IE, VecOp);
13446       
13447       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
13448         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
13449       
13450       // If we are extracting a value from a vector, then inserting it right
13451       // back into the same place, just use the input vector.
13452       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
13453         return ReplaceInstUsesWith(IE, VecOp);      
13454       
13455       // If this insertelement isn't used by some other insertelement, turn it
13456       // (and any insertelements it points to), into one big shuffle.
13457       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
13458         std::vector<Constant*> Mask;
13459         Value *RHS = 0;
13460         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
13461         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
13462         // We now have a shuffle of LHS, RHS, Mask.
13463         return new ShuffleVectorInst(LHS, RHS,
13464                                      ConstantVector::get(Mask));
13465       }
13466     }
13467   }
13468
13469   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
13470   APInt UndefElts(VWidth, 0);
13471   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13472   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
13473     return &IE;
13474
13475   return 0;
13476 }
13477
13478
13479 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
13480   Value *LHS = SVI.getOperand(0);
13481   Value *RHS = SVI.getOperand(1);
13482   std::vector<unsigned> Mask = getShuffleMask(&SVI);
13483
13484   bool MadeChange = false;
13485
13486   // Undefined shuffle mask -> undefined value.
13487   if (isa<UndefValue>(SVI.getOperand(2)))
13488     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
13489
13490   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
13491
13492   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
13493     return 0;
13494
13495   APInt UndefElts(VWidth, 0);
13496   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13497   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
13498     LHS = SVI.getOperand(0);
13499     RHS = SVI.getOperand(1);
13500     MadeChange = true;
13501   }
13502   
13503   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
13504   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
13505   if (LHS == RHS || isa<UndefValue>(LHS)) {
13506     if (isa<UndefValue>(LHS) && LHS == RHS) {
13507       // shuffle(undef,undef,mask) -> undef.
13508       return ReplaceInstUsesWith(SVI, LHS);
13509     }
13510     
13511     // Remap any references to RHS to use LHS.
13512     std::vector<Constant*> Elts;
13513     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13514       if (Mask[i] >= 2*e)
13515         Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13516       else {
13517         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
13518             (Mask[i] <  e && isa<UndefValue>(LHS))) {
13519           Mask[i] = 2*e;     // Turn into undef.
13520           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13521         } else {
13522           Mask[i] = Mask[i] % e;  // Force to LHS.
13523           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
13524         }
13525       }
13526     }
13527     SVI.setOperand(0, SVI.getOperand(1));
13528     SVI.setOperand(1, UndefValue::get(RHS->getType()));
13529     SVI.setOperand(2, ConstantVector::get(Elts));
13530     LHS = SVI.getOperand(0);
13531     RHS = SVI.getOperand(1);
13532     MadeChange = true;
13533   }
13534   
13535   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
13536   bool isLHSID = true, isRHSID = true;
13537     
13538   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13539     if (Mask[i] >= e*2) continue;  // Ignore undef values.
13540     // Is this an identity shuffle of the LHS value?
13541     isLHSID &= (Mask[i] == i);
13542       
13543     // Is this an identity shuffle of the RHS value?
13544     isRHSID &= (Mask[i]-e == i);
13545   }
13546
13547   // Eliminate identity shuffles.
13548   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
13549   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
13550   
13551   // If the LHS is a shufflevector itself, see if we can combine it with this
13552   // one without producing an unusual shuffle.  Here we are really conservative:
13553   // we are absolutely afraid of producing a shuffle mask not in the input
13554   // program, because the code gen may not be smart enough to turn a merged
13555   // shuffle into two specific shuffles: it may produce worse code.  As such,
13556   // we only merge two shuffles if the result is one of the two input shuffle
13557   // masks.  In this case, merging the shuffles just removes one instruction,
13558   // which we know is safe.  This is good for things like turning:
13559   // (splat(splat)) -> splat.
13560   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
13561     if (isa<UndefValue>(RHS)) {
13562       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
13563
13564       if (LHSMask.size() == Mask.size()) {
13565         std::vector<unsigned> NewMask;
13566         for (unsigned i = 0, e = Mask.size(); i != e; ++i)
13567           if (Mask[i] >= e)
13568             NewMask.push_back(2*e);
13569           else
13570             NewMask.push_back(LHSMask[Mask[i]]);
13571       
13572         // If the result mask is equal to the src shuffle or this
13573         // shuffle mask, do the replacement.
13574         if (NewMask == LHSMask || NewMask == Mask) {
13575           unsigned LHSInNElts =
13576             cast<VectorType>(LHSSVI->getOperand(0)->getType())->
13577             getNumElements();
13578           std::vector<Constant*> Elts;
13579           for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
13580             if (NewMask[i] >= LHSInNElts*2) {
13581               Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13582             } else {
13583               Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
13584                                               NewMask[i]));
13585             }
13586           }
13587           return new ShuffleVectorInst(LHSSVI->getOperand(0),
13588                                        LHSSVI->getOperand(1),
13589                                        ConstantVector::get(Elts));
13590         }
13591       }
13592     }
13593   }
13594
13595   return MadeChange ? &SVI : 0;
13596 }
13597
13598
13599
13600
13601 /// TryToSinkInstruction - Try to move the specified instruction from its
13602 /// current block into the beginning of DestBlock, which can only happen if it's
13603 /// safe to move the instruction past all of the instructions between it and the
13604 /// end of its block.
13605 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
13606   assert(I->hasOneUse() && "Invariants didn't hold!");
13607
13608   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
13609   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
13610     return false;
13611
13612   // Do not sink alloca instructions out of the entry block.
13613   if (isa<AllocaInst>(I) && I->getParent() ==
13614         &DestBlock->getParent()->getEntryBlock())
13615     return false;
13616
13617   // We can only sink load instructions if there is nothing between the load and
13618   // the end of block that could change the value.
13619   if (I->mayReadFromMemory()) {
13620     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
13621          Scan != E; ++Scan)
13622       if (Scan->mayWriteToMemory())
13623         return false;
13624   }
13625
13626   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
13627
13628   CopyPrecedingStopPoint(I, InsertPos);
13629   I->moveBefore(InsertPos);
13630   ++NumSunkInst;
13631   return true;
13632 }
13633
13634
13635 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
13636 /// all reachable code to the worklist.
13637 ///
13638 /// This has a couple of tricks to make the code faster and more powerful.  In
13639 /// particular, we constant fold and DCE instructions as we go, to avoid adding
13640 /// them to the worklist (this significantly speeds up instcombine on code where
13641 /// many instructions are dead or constant).  Additionally, if we find a branch
13642 /// whose condition is a known constant, we only visit the reachable successors.
13643 ///
13644 static bool AddReachableCodeToWorklist(BasicBlock *BB, 
13645                                        SmallPtrSet<BasicBlock*, 64> &Visited,
13646                                        InstCombiner &IC,
13647                                        const TargetData *TD) {
13648   bool MadeIRChange = false;
13649   SmallVector<BasicBlock*, 256> Worklist;
13650   Worklist.push_back(BB);
13651   
13652   std::vector<Instruction*> InstrsForInstCombineWorklist;
13653   InstrsForInstCombineWorklist.reserve(128);
13654
13655   SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
13656   
13657   while (!Worklist.empty()) {
13658     BB = Worklist.back();
13659     Worklist.pop_back();
13660     
13661     // We have now visited this block!  If we've already been here, ignore it.
13662     if (!Visited.insert(BB)) continue;
13663
13664     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
13665       Instruction *Inst = BBI++;
13666       
13667       // DCE instruction if trivially dead.
13668       if (isInstructionTriviallyDead(Inst)) {
13669         ++NumDeadInst;
13670         DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
13671         Inst->eraseFromParent();
13672         continue;
13673       }
13674       
13675       // ConstantProp instruction if trivially constant.
13676       if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
13677         if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
13678           DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
13679                        << *Inst << '\n');
13680           Inst->replaceAllUsesWith(C);
13681           ++NumConstProp;
13682           Inst->eraseFromParent();
13683           continue;
13684         }
13685       
13686       
13687       
13688       if (TD) {
13689         // See if we can constant fold its operands.
13690         for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
13691              i != e; ++i) {
13692           ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
13693           if (CE == 0) continue;
13694           
13695           // If we already folded this constant, don't try again.
13696           if (!FoldedConstants.insert(CE))
13697             continue;
13698           
13699           Constant *NewC = ConstantFoldConstantExpression(CE, TD);
13700           if (NewC && NewC != CE) {
13701             *i = NewC;
13702             MadeIRChange = true;
13703           }
13704         }
13705       }
13706       
13707
13708       InstrsForInstCombineWorklist.push_back(Inst);
13709     }
13710
13711     // Recursively visit successors.  If this is a branch or switch on a
13712     // constant, only visit the reachable successor.
13713     TerminatorInst *TI = BB->getTerminator();
13714     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
13715       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
13716         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
13717         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
13718         Worklist.push_back(ReachableBB);
13719         continue;
13720       }
13721     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
13722       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
13723         // See if this is an explicit destination.
13724         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
13725           if (SI->getCaseValue(i) == Cond) {
13726             BasicBlock *ReachableBB = SI->getSuccessor(i);
13727             Worklist.push_back(ReachableBB);
13728             continue;
13729           }
13730         
13731         // Otherwise it is the default destination.
13732         Worklist.push_back(SI->getSuccessor(0));
13733         continue;
13734       }
13735     }
13736     
13737     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
13738       Worklist.push_back(TI->getSuccessor(i));
13739   }
13740   
13741   // Once we've found all of the instructions to add to instcombine's worklist,
13742   // add them in reverse order.  This way instcombine will visit from the top
13743   // of the function down.  This jives well with the way that it adds all uses
13744   // of instructions to the worklist after doing a transformation, thus avoiding
13745   // some N^2 behavior in pathological cases.
13746   IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
13747                               InstrsForInstCombineWorklist.size());
13748   
13749   return MadeIRChange;
13750 }
13751
13752 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
13753   MadeIRChange = false;
13754   
13755   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
13756         << F.getNameStr() << "\n");
13757
13758   {
13759     // Do a depth-first traversal of the function, populate the worklist with
13760     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
13761     // track of which blocks we visit.
13762     SmallPtrSet<BasicBlock*, 64> Visited;
13763     MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
13764
13765     // Do a quick scan over the function.  If we find any blocks that are
13766     // unreachable, remove any instructions inside of them.  This prevents
13767     // the instcombine code from having to deal with some bad special cases.
13768     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
13769       if (!Visited.count(BB)) {
13770         Instruction *Term = BB->getTerminator();
13771         while (Term != BB->begin()) {   // Remove instrs bottom-up
13772           BasicBlock::iterator I = Term; --I;
13773
13774           DEBUG(errs() << "IC: DCE: " << *I << '\n');
13775           // A debug intrinsic shouldn't force another iteration if we weren't
13776           // going to do one without it.
13777           if (!isa<DbgInfoIntrinsic>(I)) {
13778             ++NumDeadInst;
13779             MadeIRChange = true;
13780           }
13781
13782           // If I is not void type then replaceAllUsesWith undef.
13783           // This allows ValueHandlers and custom metadata to adjust itself.
13784           if (!I->getType()->isVoidTy())
13785             I->replaceAllUsesWith(UndefValue::get(I->getType()));
13786           I->eraseFromParent();
13787         }
13788       }
13789   }
13790
13791   while (!Worklist.isEmpty()) {
13792     Instruction *I = Worklist.RemoveOne();
13793     if (I == 0) continue;  // skip null values.
13794
13795     // Check to see if we can DCE the instruction.
13796     if (isInstructionTriviallyDead(I)) {
13797       DEBUG(errs() << "IC: DCE: " << *I << '\n');
13798       EraseInstFromFunction(*I);
13799       ++NumDeadInst;
13800       MadeIRChange = true;
13801       continue;
13802     }
13803
13804     // Instruction isn't dead, see if we can constant propagate it.
13805     if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
13806       if (Constant *C = ConstantFoldInstruction(I, TD)) {
13807         DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
13808
13809         // Add operands to the worklist.
13810         ReplaceInstUsesWith(*I, C);
13811         ++NumConstProp;
13812         EraseInstFromFunction(*I);
13813         MadeIRChange = true;
13814         continue;
13815       }
13816
13817     // See if we can trivially sink this instruction to a successor basic block.
13818     if (I->hasOneUse()) {
13819       BasicBlock *BB = I->getParent();
13820       Instruction *UserInst = cast<Instruction>(I->use_back());
13821       BasicBlock *UserParent;
13822       
13823       // Get the block the use occurs in.
13824       if (PHINode *PN = dyn_cast<PHINode>(UserInst))
13825         UserParent = PN->getIncomingBlock(I->use_begin().getUse());
13826       else
13827         UserParent = UserInst->getParent();
13828       
13829       if (UserParent != BB) {
13830         bool UserIsSuccessor = false;
13831         // See if the user is one of our successors.
13832         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13833           if (*SI == UserParent) {
13834             UserIsSuccessor = true;
13835             break;
13836           }
13837
13838         // If the user is one of our immediate successors, and if that successor
13839         // only has us as a predecessors (we'd have to split the critical edge
13840         // otherwise), we can keep going.
13841         if (UserIsSuccessor && UserParent->getSinglePredecessor())
13842           // Okay, the CFG is simple enough, try to sink this instruction.
13843           MadeIRChange |= TryToSinkInstruction(I, UserParent);
13844       }
13845     }
13846
13847     // Now that we have an instruction, try combining it to simplify it.
13848     Builder->SetInsertPoint(I->getParent(), I);
13849     
13850 #ifndef NDEBUG
13851     std::string OrigI;
13852 #endif
13853     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
13854     DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
13855
13856     if (Instruction *Result = visit(*I)) {
13857       ++NumCombined;
13858       // Should we replace the old instruction with a new one?
13859       if (Result != I) {
13860         DEBUG(errs() << "IC: Old = " << *I << '\n'
13861                      << "    New = " << *Result << '\n');
13862
13863         // Everything uses the new instruction now.
13864         I->replaceAllUsesWith(Result);
13865
13866         // Push the new instruction and any users onto the worklist.
13867         Worklist.Add(Result);
13868         Worklist.AddUsersToWorkList(*Result);
13869
13870         // Move the name to the new instruction first.
13871         Result->takeName(I);
13872
13873         // Insert the new instruction into the basic block...
13874         BasicBlock *InstParent = I->getParent();
13875         BasicBlock::iterator InsertPos = I;
13876
13877         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
13878           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13879             ++InsertPos;
13880
13881         InstParent->getInstList().insert(InsertPos, Result);
13882
13883         EraseInstFromFunction(*I);
13884       } else {
13885 #ifndef NDEBUG
13886         DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13887                      << "    New = " << *I << '\n');
13888 #endif
13889
13890         // If the instruction was modified, it's possible that it is now dead.
13891         // if so, remove it.
13892         if (isInstructionTriviallyDead(I)) {
13893           EraseInstFromFunction(*I);
13894         } else {
13895           Worklist.Add(I);
13896           Worklist.AddUsersToWorkList(*I);
13897         }
13898       }
13899       MadeIRChange = true;
13900     }
13901   }
13902
13903   Worklist.Zap();
13904   return MadeIRChange;
13905 }
13906
13907
13908 bool InstCombiner::runOnFunction(Function &F) {
13909   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13910   Context = &F.getContext();
13911   TD = getAnalysisIfAvailable<TargetData>();
13912
13913   
13914   /// Builder - This is an IRBuilder that automatically inserts new
13915   /// instructions into the worklist when they are created.
13916   IRBuilder<true, TargetFolder, InstCombineIRInserter> 
13917     TheBuilder(F.getContext(), TargetFolder(TD),
13918                InstCombineIRInserter(Worklist));
13919   Builder = &TheBuilder;
13920   
13921   bool EverMadeChange = false;
13922
13923   // Iterate while there is work to do.
13924   unsigned Iteration = 0;
13925   while (DoOneIteration(F, Iteration++))
13926     EverMadeChange = true;
13927   
13928   Builder = 0;
13929   return EverMadeChange;
13930 }
13931
13932 FunctionPass *llvm::createInstructionCombiningPass() {
13933   return new InstCombiner();
13934 }