fix PR5262.
[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/MallocHelper.h"
46 #include "llvm/Analysis/ValueTracking.h"
47 #include "llvm/Target/TargetData.h"
48 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
49 #include "llvm/Transforms/Utils/Local.h"
50 #include "llvm/Support/CallSite.h"
51 #include "llvm/Support/ConstantRange.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include "llvm/Support/GetElementPtrTypeIterator.h"
55 #include "llvm/Support/InstVisitor.h"
56 #include "llvm/Support/IRBuilder.h"
57 #include "llvm/Support/MathExtras.h"
58 #include "llvm/Support/PatternMatch.h"
59 #include "llvm/Support/TargetFolder.h"
60 #include "llvm/Support/raw_ostream.h"
61 #include "llvm/ADT/DenseMap.h"
62 #include "llvm/ADT/SmallVector.h"
63 #include "llvm/ADT/SmallPtrSet.h"
64 #include "llvm/ADT/Statistic.h"
65 #include "llvm/ADT/STLExtras.h"
66 #include <algorithm>
67 #include <climits>
68 using namespace llvm;
69 using namespace llvm::PatternMatch;
70
71 STATISTIC(NumCombined , "Number of insts combined");
72 STATISTIC(NumConstProp, "Number of constant folds");
73 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
74 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
75 STATISTIC(NumSunkInst , "Number of instructions sunk");
76
77 namespace {
78   /// InstCombineWorklist - This is the worklist management logic for
79   /// InstCombine.
80   class InstCombineWorklist {
81     SmallVector<Instruction*, 256> Worklist;
82     DenseMap<Instruction*, unsigned> WorklistMap;
83     
84     void operator=(const InstCombineWorklist&RHS);   // DO NOT IMPLEMENT
85     InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
86   public:
87     InstCombineWorklist() {}
88     
89     bool isEmpty() const { return Worklist.empty(); }
90     
91     /// Add - Add the specified instruction to the worklist if it isn't already
92     /// in it.
93     void Add(Instruction *I) {
94       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {
95         DEBUG(errs() << "IC: ADD: " << *I << '\n');
96         Worklist.push_back(I);
97       }
98     }
99     
100     void AddValue(Value *V) {
101       if (Instruction *I = dyn_cast<Instruction>(V))
102         Add(I);
103     }
104     
105     /// AddInitialGroup - Add the specified batch of stuff in reverse order.
106     /// which should only be done when the worklist is empty and when the group
107     /// has no duplicates.
108     void AddInitialGroup(Instruction *const *List, unsigned NumEntries) {
109       assert(Worklist.empty() && "Worklist must be empty to add initial group");
110       Worklist.reserve(NumEntries+16);
111       DEBUG(errs() << "IC: ADDING: " << NumEntries << " instrs to worklist\n");
112       for (; NumEntries; --NumEntries) {
113         Instruction *I = List[NumEntries-1];
114         WorklistMap.insert(std::make_pair(I, Worklist.size()));
115         Worklist.push_back(I);
116       }
117     }
118     
119     // Remove - remove I from the worklist if it exists.
120     void Remove(Instruction *I) {
121       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
122       if (It == WorklistMap.end()) return; // Not in worklist.
123       
124       // Don't bother moving everything down, just null out the slot.
125       Worklist[It->second] = 0;
126       
127       WorklistMap.erase(It);
128     }
129     
130     Instruction *RemoveOne() {
131       Instruction *I = Worklist.back();
132       Worklist.pop_back();
133       WorklistMap.erase(I);
134       return I;
135     }
136
137     /// AddUsersToWorkList - When an instruction is simplified, add all users of
138     /// the instruction to the work lists because they might get more simplified
139     /// now.
140     ///
141     void AddUsersToWorkList(Instruction &I) {
142       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
143            UI != UE; ++UI)
144         Add(cast<Instruction>(*UI));
145     }
146     
147     
148     /// Zap - check that the worklist is empty and nuke the backing store for
149     /// the map if it is large.
150     void Zap() {
151       assert(WorklistMap.empty() && "Worklist empty, but map not?");
152       
153       // Do an explicit clear, this shrinks the map if needed.
154       WorklistMap.clear();
155     }
156   };
157 } // end anonymous namespace.
158
159
160 namespace {
161   /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
162   /// just like the normal insertion helper, but also adds any new instructions
163   /// to the instcombine worklist.
164   class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
165     InstCombineWorklist &Worklist;
166   public:
167     InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
168     
169     void InsertHelper(Instruction *I, const Twine &Name,
170                       BasicBlock *BB, BasicBlock::iterator InsertPt) const {
171       IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
172       Worklist.Add(I);
173     }
174   };
175 } // end anonymous namespace
176
177
178 namespace {
179   class InstCombiner : public FunctionPass,
180                        public InstVisitor<InstCombiner, Instruction*> {
181     TargetData *TD;
182     bool MustPreserveLCSSA;
183     bool MadeIRChange;
184   public:
185     /// Worklist - All of the instructions that need to be simplified.
186     InstCombineWorklist Worklist;
187
188     /// Builder - This is an IRBuilder that automatically inserts new
189     /// instructions into the worklist when they are created.
190     typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
191     BuilderTy *Builder;
192         
193     static char ID; // Pass identification, replacement for typeid
194     InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
195
196     LLVMContext *Context;
197     LLVMContext *getContext() const { return Context; }
198
199   public:
200     virtual bool runOnFunction(Function &F);
201     
202     bool DoOneIteration(Function &F, unsigned ItNum);
203
204     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
205       AU.addPreservedID(LCSSAID);
206       AU.setPreservesCFG();
207     }
208
209     TargetData *getTargetData() const { return TD; }
210
211     // Visitation implementation - Implement instruction combining for different
212     // instruction types.  The semantics are as follows:
213     // Return Value:
214     //    null        - No change was made
215     //     I          - Change was made, I is still valid, I may be dead though
216     //   otherwise    - Change was made, replace I with returned instruction
217     //
218     Instruction *visitAdd(BinaryOperator &I);
219     Instruction *visitFAdd(BinaryOperator &I);
220     Instruction *visitSub(BinaryOperator &I);
221     Instruction *visitFSub(BinaryOperator &I);
222     Instruction *visitMul(BinaryOperator &I);
223     Instruction *visitFMul(BinaryOperator &I);
224     Instruction *visitURem(BinaryOperator &I);
225     Instruction *visitSRem(BinaryOperator &I);
226     Instruction *visitFRem(BinaryOperator &I);
227     bool SimplifyDivRemOfSelect(BinaryOperator &I);
228     Instruction *commonRemTransforms(BinaryOperator &I);
229     Instruction *commonIRemTransforms(BinaryOperator &I);
230     Instruction *commonDivTransforms(BinaryOperator &I);
231     Instruction *commonIDivTransforms(BinaryOperator &I);
232     Instruction *visitUDiv(BinaryOperator &I);
233     Instruction *visitSDiv(BinaryOperator &I);
234     Instruction *visitFDiv(BinaryOperator &I);
235     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
236     Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
237     Instruction *visitAnd(BinaryOperator &I);
238     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
239     Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
240     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
241                                      Value *A, Value *B, Value *C);
242     Instruction *visitOr (BinaryOperator &I);
243     Instruction *visitXor(BinaryOperator &I);
244     Instruction *visitShl(BinaryOperator &I);
245     Instruction *visitAShr(BinaryOperator &I);
246     Instruction *visitLShr(BinaryOperator &I);
247     Instruction *commonShiftTransforms(BinaryOperator &I);
248     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
249                                       Constant *RHSC);
250     Instruction *visitFCmpInst(FCmpInst &I);
251     Instruction *visitICmpInst(ICmpInst &I);
252     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
253     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
254                                                 Instruction *LHS,
255                                                 ConstantInt *RHS);
256     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
257                                 ConstantInt *DivRHS);
258
259     Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
260                              ICmpInst::Predicate Cond, Instruction &I);
261     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
262                                      BinaryOperator &I);
263     Instruction *commonCastTransforms(CastInst &CI);
264     Instruction *commonIntCastTransforms(CastInst &CI);
265     Instruction *commonPointerCastTransforms(CastInst &CI);
266     Instruction *visitTrunc(TruncInst &CI);
267     Instruction *visitZExt(ZExtInst &CI);
268     Instruction *visitSExt(SExtInst &CI);
269     Instruction *visitFPTrunc(FPTruncInst &CI);
270     Instruction *visitFPExt(CastInst &CI);
271     Instruction *visitFPToUI(FPToUIInst &FI);
272     Instruction *visitFPToSI(FPToSIInst &FI);
273     Instruction *visitUIToFP(CastInst &CI);
274     Instruction *visitSIToFP(CastInst &CI);
275     Instruction *visitPtrToInt(PtrToIntInst &CI);
276     Instruction *visitIntToPtr(IntToPtrInst &CI);
277     Instruction *visitBitCast(BitCastInst &CI);
278     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
279                                 Instruction *FI);
280     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
281     Instruction *visitSelectInst(SelectInst &SI);
282     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
283     Instruction *visitCallInst(CallInst &CI);
284     Instruction *visitInvokeInst(InvokeInst &II);
285     Instruction *visitPHINode(PHINode &PN);
286     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
287     Instruction *visitAllocationInst(AllocationInst &AI);
288     Instruction *visitFreeInst(FreeInst &FI);
289     Instruction *visitLoadInst(LoadInst &LI);
290     Instruction *visitStoreInst(StoreInst &SI);
291     Instruction *visitBranchInst(BranchInst &BI);
292     Instruction *visitSwitchInst(SwitchInst &SI);
293     Instruction *visitInsertElementInst(InsertElementInst &IE);
294     Instruction *visitExtractElementInst(ExtractElementInst &EI);
295     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
296     Instruction *visitExtractValueInst(ExtractValueInst &EV);
297
298     // visitInstruction - Specify what to return for unhandled instructions...
299     Instruction *visitInstruction(Instruction &I) { return 0; }
300
301   private:
302     Instruction *visitCallSite(CallSite CS);
303     bool transformConstExprCastCall(CallSite CS);
304     Instruction *transformCallThroughTrampoline(CallSite CS);
305     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
306                                    bool DoXform = true);
307     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
308     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
309
310
311   public:
312     // InsertNewInstBefore - insert an instruction New before instruction Old
313     // in the program.  Add the new instruction to the worklist.
314     //
315     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
316       assert(New && New->getParent() == 0 &&
317              "New instruction already inserted into a basic block!");
318       BasicBlock *BB = Old.getParent();
319       BB->getInstList().insert(&Old, New);  // Insert inst
320       Worklist.Add(New);
321       return New;
322     }
323         
324     // ReplaceInstUsesWith - This method is to be used when an instruction is
325     // found to be dead, replacable with another preexisting expression.  Here
326     // we add all uses of I to the worklist, replace all uses of I with the new
327     // value, then return I, so that the inst combiner will know that I was
328     // modified.
329     //
330     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
331       Worklist.AddUsersToWorkList(I);   // Add all modified instrs to worklist.
332       
333       // If we are replacing the instruction with itself, this must be in a
334       // segment of unreachable code, so just clobber the instruction.
335       if (&I == V) 
336         V = UndefValue::get(I.getType());
337         
338       I.replaceAllUsesWith(V);
339       return &I;
340     }
341
342     // EraseInstFromFunction - When dealing with an instruction that has side
343     // effects or produces a void value, we can't rely on DCE to delete the
344     // instruction.  Instead, visit methods should return the value returned by
345     // this function.
346     Instruction *EraseInstFromFunction(Instruction &I) {
347       DEBUG(errs() << "IC: ERASE " << I << '\n');
348
349       assert(I.use_empty() && "Cannot erase instruction that is used!");
350       // Make sure that we reprocess all operands now that we reduced their
351       // use counts.
352       if (I.getNumOperands() < 8) {
353         for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
354           if (Instruction *Op = dyn_cast<Instruction>(*i))
355             Worklist.Add(Op);
356       }
357       Worklist.Remove(&I);
358       I.eraseFromParent();
359       MadeIRChange = true;
360       return 0;  // Don't do anything with FI
361     }
362         
363     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
364                            APInt &KnownOne, unsigned Depth = 0) const {
365       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
366     }
367     
368     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
369                            unsigned Depth = 0) const {
370       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
371     }
372     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
373       return llvm::ComputeNumSignBits(Op, TD, Depth);
374     }
375
376   private:
377
378     /// SimplifyCommutative - This performs a few simplifications for 
379     /// commutative operators.
380     bool SimplifyCommutative(BinaryOperator &I);
381
382     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
383     /// most-complex to least-complex order.
384     bool SimplifyCompare(CmpInst &I);
385
386     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
387     /// based on the demanded bits.
388     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
389                                    APInt& KnownZero, APInt& KnownOne,
390                                    unsigned Depth);
391     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
392                               APInt& KnownZero, APInt& KnownOne,
393                               unsigned Depth=0);
394         
395     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
396     /// SimplifyDemandedBits knows about.  See if the instruction has any
397     /// properties that allow us to simplify its operands.
398     bool SimplifyDemandedInstructionBits(Instruction &Inst);
399         
400     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
401                                       APInt& UndefElts, unsigned Depth = 0);
402       
403     // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
404     // which has a PHI node as operand #0, see if we can fold the instruction
405     // into the PHI (which is only possible if all operands to the PHI are
406     // constants).
407     //
408     // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
409     // that would normally be unprofitable because they strongly encourage jump
410     // threading.
411     Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
412
413     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
414     // operator and they all are only used by the PHI, PHI together their
415     // inputs, and do the operation once, to the result of the PHI.
416     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
417     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
418     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
419
420     
421     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
422                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
423     
424     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
425                               bool isSub, Instruction &I);
426     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
427                                  bool isSigned, bool Inside, Instruction &IB);
428     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
429     Instruction *MatchBSwap(BinaryOperator &I);
430     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
431     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
432     Instruction *SimplifyMemSet(MemSetInst *MI);
433
434
435     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
436
437     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
438                                     unsigned CastOpc, int &NumCastsRemoved);
439     unsigned GetOrEnforceKnownAlignment(Value *V,
440                                         unsigned PrefAlign = 0);
441
442   };
443 } // end anonymous namespace
444
445 char InstCombiner::ID = 0;
446 static RegisterPass<InstCombiner>
447 X("instcombine", "Combine redundant instructions");
448
449 // getComplexity:  Assign a complexity or rank value to LLVM Values...
450 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
451 static unsigned getComplexity(Value *V) {
452   if (isa<Instruction>(V)) {
453     if (BinaryOperator::isNeg(V) ||
454         BinaryOperator::isFNeg(V) ||
455         BinaryOperator::isNot(V))
456       return 3;
457     return 4;
458   }
459   if (isa<Argument>(V)) return 3;
460   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
461 }
462
463 // isOnlyUse - Return true if this instruction will be deleted if we stop using
464 // it.
465 static bool isOnlyUse(Value *V) {
466   return V->hasOneUse() || isa<Constant>(V);
467 }
468
469 // getPromotedType - Return the specified type promoted as it would be to pass
470 // though a va_arg area...
471 static const Type *getPromotedType(const Type *Ty) {
472   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
473     if (ITy->getBitWidth() < 32)
474       return Type::getInt32Ty(Ty->getContext());
475   }
476   return Ty;
477 }
478
479 /// getBitCastOperand - If the specified operand is a CastInst, a constant
480 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
481 /// operand value, otherwise return null.
482 static Value *getBitCastOperand(Value *V) {
483   if (Operator *O = dyn_cast<Operator>(V)) {
484     if (O->getOpcode() == Instruction::BitCast)
485       return O->getOperand(0);
486     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
487       if (GEP->hasAllZeroIndices())
488         return GEP->getPointerOperand();
489   }
490   return 0;
491 }
492
493 /// This function is a wrapper around CastInst::isEliminableCastPair. It
494 /// simply extracts arguments and returns what that function returns.
495 static Instruction::CastOps 
496 isEliminableCastPair(
497   const CastInst *CI, ///< The first cast instruction
498   unsigned opcode,       ///< The opcode of the second cast instruction
499   const Type *DstTy,     ///< The target type for the second cast instruction
500   TargetData *TD         ///< The target data for pointer size
501 ) {
502
503   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
504   const Type *MidTy = CI->getType();                  // B from above
505
506   // Get the opcodes of the two Cast instructions
507   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
508   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
509
510   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
511                                                 DstTy,
512                                   TD ? TD->getIntPtrType(CI->getContext()) : 0);
513   
514   // We don't want to form an inttoptr or ptrtoint that converts to an integer
515   // type that differs from the pointer size.
516   if ((Res == Instruction::IntToPtr &&
517           (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
518       (Res == Instruction::PtrToInt &&
519           (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
520     Res = 0;
521   
522   return Instruction::CastOps(Res);
523 }
524
525 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
526 /// in any code being generated.  It does not require codegen if V is simple
527 /// enough or if the cast can be folded into other casts.
528 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
529                               const Type *Ty, TargetData *TD) {
530   if (V->getType() == Ty || isa<Constant>(V)) return false;
531   
532   // If this is another cast that can be eliminated, it isn't codegen either.
533   if (const CastInst *CI = dyn_cast<CastInst>(V))
534     if (isEliminableCastPair(CI, opcode, Ty, TD))
535       return false;
536   return true;
537 }
538
539 // SimplifyCommutative - This performs a few simplifications for commutative
540 // operators:
541 //
542 //  1. Order operands such that they are listed from right (least complex) to
543 //     left (most complex).  This puts constants before unary operators before
544 //     binary operators.
545 //
546 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
547 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
548 //
549 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
550   bool Changed = false;
551   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
552     Changed = !I.swapOperands();
553
554   if (!I.isAssociative()) return Changed;
555   Instruction::BinaryOps Opcode = I.getOpcode();
556   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
557     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
558       if (isa<Constant>(I.getOperand(1))) {
559         Constant *Folded = ConstantExpr::get(I.getOpcode(),
560                                              cast<Constant>(I.getOperand(1)),
561                                              cast<Constant>(Op->getOperand(1)));
562         I.setOperand(0, Op->getOperand(0));
563         I.setOperand(1, Folded);
564         return true;
565       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
566         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
567             isOnlyUse(Op) && isOnlyUse(Op1)) {
568           Constant *C1 = cast<Constant>(Op->getOperand(1));
569           Constant *C2 = cast<Constant>(Op1->getOperand(1));
570
571           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
572           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
573           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
574                                                     Op1->getOperand(0),
575                                                     Op1->getName(), &I);
576           Worklist.Add(New);
577           I.setOperand(0, New);
578           I.setOperand(1, Folded);
579           return true;
580         }
581     }
582   return Changed;
583 }
584
585 /// SimplifyCompare - For a CmpInst this function just orders the operands
586 /// so that theyare listed from right (least complex) to left (most complex).
587 /// This puts constants before unary operators before binary operators.
588 bool InstCombiner::SimplifyCompare(CmpInst &I) {
589   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
590     return false;
591   I.swapOperands();
592   // Compare instructions are not associative so there's nothing else we can do.
593   return true;
594 }
595
596 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
597 // if the LHS is a constant zero (which is the 'negate' form).
598 //
599 static inline Value *dyn_castNegVal(Value *V) {
600   if (BinaryOperator::isNeg(V))
601     return BinaryOperator::getNegArgument(V);
602
603   // Constants can be considered to be negated values if they can be folded.
604   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
605     return ConstantExpr::getNeg(C);
606
607   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
608     if (C->getType()->getElementType()->isInteger())
609       return ConstantExpr::getNeg(C);
610
611   return 0;
612 }
613
614 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
615 // instruction if the LHS is a constant negative zero (which is the 'negate'
616 // form).
617 //
618 static inline Value *dyn_castFNegVal(Value *V) {
619   if (BinaryOperator::isFNeg(V))
620     return BinaryOperator::getFNegArgument(V);
621
622   // Constants can be considered to be negated values if they can be folded.
623   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
624     return ConstantExpr::getFNeg(C);
625
626   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
627     if (C->getType()->getElementType()->isFloatingPoint())
628       return ConstantExpr::getFNeg(C);
629
630   return 0;
631 }
632
633 static inline Value *dyn_castNotVal(Value *V) {
634   if (BinaryOperator::isNot(V))
635     return BinaryOperator::getNotArgument(V);
636
637   // Constants can be considered to be not'ed values...
638   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
639     return ConstantInt::get(C->getType(), ~C->getValue());
640   return 0;
641 }
642
643 // dyn_castFoldableMul - If this value is a multiply that can be folded into
644 // other computations (because it has a constant operand), return the
645 // non-constant operand of the multiply, and set CST to point to the multiplier.
646 // Otherwise, return null.
647 //
648 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
649   if (V->hasOneUse() && V->getType()->isInteger())
650     if (Instruction *I = dyn_cast<Instruction>(V)) {
651       if (I->getOpcode() == Instruction::Mul)
652         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
653           return I->getOperand(0);
654       if (I->getOpcode() == Instruction::Shl)
655         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
656           // The multiplier is really 1 << CST.
657           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
658           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
659           CST = ConstantInt::get(V->getType()->getContext(),
660                                  APInt(BitWidth, 1).shl(CSTVal));
661           return I->getOperand(0);
662         }
663     }
664   return 0;
665 }
666
667 /// AddOne - Add one to a ConstantInt
668 static Constant *AddOne(Constant *C) {
669   return ConstantExpr::getAdd(C, 
670     ConstantInt::get(C->getType(), 1));
671 }
672 /// SubOne - Subtract one from a ConstantInt
673 static Constant *SubOne(ConstantInt *C) {
674   return ConstantExpr::getSub(C, 
675     ConstantInt::get(C->getType(), 1));
676 }
677 /// MultiplyOverflows - True if the multiply can not be expressed in an int
678 /// this size.
679 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
680   uint32_t W = C1->getBitWidth();
681   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
682   if (sign) {
683     LHSExt.sext(W * 2);
684     RHSExt.sext(W * 2);
685   } else {
686     LHSExt.zext(W * 2);
687     RHSExt.zext(W * 2);
688   }
689
690   APInt MulExt = LHSExt * RHSExt;
691
692   if (sign) {
693     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
694     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
695     return MulExt.slt(Min) || MulExt.sgt(Max);
696   } else 
697     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
698 }
699
700
701 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
702 /// specified instruction is a constant integer.  If so, check to see if there
703 /// are any bits set in the constant that are not demanded.  If so, shrink the
704 /// constant and return true.
705 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
706                                    APInt Demanded) {
707   assert(I && "No instruction?");
708   assert(OpNo < I->getNumOperands() && "Operand index too large");
709
710   // If the operand is not a constant integer, nothing to do.
711   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
712   if (!OpC) return false;
713
714   // If there are no bits set that aren't demanded, nothing to do.
715   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
716   if ((~Demanded & OpC->getValue()) == 0)
717     return false;
718
719   // This instruction is producing bits that are not demanded. Shrink the RHS.
720   Demanded &= OpC->getValue();
721   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
722   return true;
723 }
724
725 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
726 // set of known zero and one bits, compute the maximum and minimum values that
727 // could have the specified known zero and known one bits, returning them in
728 // min/max.
729 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
730                                                    const APInt& KnownOne,
731                                                    APInt& Min, APInt& Max) {
732   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
733          KnownZero.getBitWidth() == Min.getBitWidth() &&
734          KnownZero.getBitWidth() == Max.getBitWidth() &&
735          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
736   APInt UnknownBits = ~(KnownZero|KnownOne);
737
738   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
739   // bit if it is unknown.
740   Min = KnownOne;
741   Max = KnownOne|UnknownBits;
742   
743   if (UnknownBits.isNegative()) { // Sign bit is unknown
744     Min.set(Min.getBitWidth()-1);
745     Max.clear(Max.getBitWidth()-1);
746   }
747 }
748
749 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
750 // a set of known zero and one bits, compute the maximum and minimum values that
751 // could have the specified known zero and known one bits, returning them in
752 // min/max.
753 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
754                                                      const APInt &KnownOne,
755                                                      APInt &Min, APInt &Max) {
756   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
757          KnownZero.getBitWidth() == Min.getBitWidth() &&
758          KnownZero.getBitWidth() == Max.getBitWidth() &&
759          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
760   APInt UnknownBits = ~(KnownZero|KnownOne);
761   
762   // The minimum value is when the unknown bits are all zeros.
763   Min = KnownOne;
764   // The maximum value is when the unknown bits are all ones.
765   Max = KnownOne|UnknownBits;
766 }
767
768 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
769 /// SimplifyDemandedBits knows about.  See if the instruction has any
770 /// properties that allow us to simplify its operands.
771 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
772   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
773   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
774   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
775   
776   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
777                                      KnownZero, KnownOne, 0);
778   if (V == 0) return false;
779   if (V == &Inst) return true;
780   ReplaceInstUsesWith(Inst, V);
781   return true;
782 }
783
784 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
785 /// specified instruction operand if possible, updating it in place.  It returns
786 /// true if it made any change and false otherwise.
787 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
788                                         APInt &KnownZero, APInt &KnownOne,
789                                         unsigned Depth) {
790   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
791                                           KnownZero, KnownOne, Depth);
792   if (NewVal == 0) return false;
793   U = NewVal;
794   return true;
795 }
796
797
798 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
799 /// value based on the demanded bits.  When this function is called, it is known
800 /// that only the bits set in DemandedMask of the result of V are ever used
801 /// downstream. Consequently, depending on the mask and V, it may be possible
802 /// to replace V with a constant or one of its operands. In such cases, this
803 /// function does the replacement and returns true. In all other cases, it
804 /// returns false after analyzing the expression and setting KnownOne and known
805 /// to be one in the expression.  KnownZero contains all the bits that are known
806 /// to be zero in the expression. These are provided to potentially allow the
807 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
808 /// the expression. KnownOne and KnownZero always follow the invariant that 
809 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
810 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
811 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
812 /// and KnownOne must all be the same.
813 ///
814 /// This returns null if it did not change anything and it permits no
815 /// simplification.  This returns V itself if it did some simplification of V's
816 /// operands based on the information about what bits are demanded. This returns
817 /// some other non-null value if it found out that V is equal to another value
818 /// in the context where the specified bits are demanded, but not for all users.
819 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
820                                              APInt &KnownZero, APInt &KnownOne,
821                                              unsigned Depth) {
822   assert(V != 0 && "Null pointer of Value???");
823   assert(Depth <= 6 && "Limit Search Depth");
824   uint32_t BitWidth = DemandedMask.getBitWidth();
825   const Type *VTy = V->getType();
826   assert((TD || !isa<PointerType>(VTy)) &&
827          "SimplifyDemandedBits needs to know bit widths!");
828   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
829          (!VTy->isIntOrIntVector() ||
830           VTy->getScalarSizeInBits() == BitWidth) &&
831          KnownZero.getBitWidth() == BitWidth &&
832          KnownOne.getBitWidth() == BitWidth &&
833          "Value *V, DemandedMask, KnownZero and KnownOne "
834          "must have same BitWidth");
835   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
836     // We know all of the bits for a constant!
837     KnownOne = CI->getValue() & DemandedMask;
838     KnownZero = ~KnownOne & DemandedMask;
839     return 0;
840   }
841   if (isa<ConstantPointerNull>(V)) {
842     // We know all of the bits for a constant!
843     KnownOne.clear();
844     KnownZero = DemandedMask;
845     return 0;
846   }
847
848   KnownZero.clear();
849   KnownOne.clear();
850   if (DemandedMask == 0) {   // Not demanding any bits from V.
851     if (isa<UndefValue>(V))
852       return 0;
853     return UndefValue::get(VTy);
854   }
855   
856   if (Depth == 6)        // Limit search depth.
857     return 0;
858   
859   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
860   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
861
862   Instruction *I = dyn_cast<Instruction>(V);
863   if (!I) {
864     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
865     return 0;        // Only analyze instructions.
866   }
867
868   // If there are multiple uses of this value and we aren't at the root, then
869   // we can't do any simplifications of the operands, because DemandedMask
870   // only reflects the bits demanded by *one* of the users.
871   if (Depth != 0 && !I->hasOneUse()) {
872     // Despite the fact that we can't simplify this instruction in all User's
873     // context, we can at least compute the knownzero/knownone bits, and we can
874     // do simplifications that apply to *just* the one user if we know that
875     // this instruction has a simpler value in that context.
876     if (I->getOpcode() == Instruction::And) {
877       // If either the LHS or the RHS are Zero, the result is zero.
878       ComputeMaskedBits(I->getOperand(1), DemandedMask,
879                         RHSKnownZero, RHSKnownOne, Depth+1);
880       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
881                         LHSKnownZero, LHSKnownOne, Depth+1);
882       
883       // If all of the demanded bits are known 1 on one side, return the other.
884       // These bits cannot contribute to the result of the 'and' in this
885       // context.
886       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
887           (DemandedMask & ~LHSKnownZero))
888         return I->getOperand(0);
889       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
890           (DemandedMask & ~RHSKnownZero))
891         return I->getOperand(1);
892       
893       // If all of the demanded bits in the inputs are known zeros, return zero.
894       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
895         return Constant::getNullValue(VTy);
896       
897     } else if (I->getOpcode() == Instruction::Or) {
898       // We can simplify (X|Y) -> X or Y in the user's context if we know that
899       // only bits from X or Y are demanded.
900       
901       // If either the LHS or the RHS are One, the result is One.
902       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
903                         RHSKnownZero, RHSKnownOne, Depth+1);
904       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
905                         LHSKnownZero, LHSKnownOne, Depth+1);
906       
907       // If all of the demanded bits are known zero on one side, return the
908       // other.  These bits cannot contribute to the result of the 'or' in this
909       // context.
910       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
911           (DemandedMask & ~LHSKnownOne))
912         return I->getOperand(0);
913       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
914           (DemandedMask & ~RHSKnownOne))
915         return I->getOperand(1);
916       
917       // If all of the potentially set bits on one side are known to be set on
918       // the other side, just use the 'other' side.
919       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
920           (DemandedMask & (~RHSKnownZero)))
921         return I->getOperand(0);
922       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
923           (DemandedMask & (~LHSKnownZero)))
924         return I->getOperand(1);
925     }
926     
927     // Compute the KnownZero/KnownOne bits to simplify things downstream.
928     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
929     return 0;
930   }
931   
932   // If this is the root being simplified, allow it to have multiple uses,
933   // just set the DemandedMask to all bits so that we can try to simplify the
934   // operands.  This allows visitTruncInst (for example) to simplify the
935   // operand of a trunc without duplicating all the logic below.
936   if (Depth == 0 && !V->hasOneUse())
937     DemandedMask = APInt::getAllOnesValue(BitWidth);
938   
939   switch (I->getOpcode()) {
940   default:
941     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
942     break;
943   case Instruction::And:
944     // If either the LHS or the RHS are Zero, the result is zero.
945     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
946                              RHSKnownZero, RHSKnownOne, Depth+1) ||
947         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
948                              LHSKnownZero, LHSKnownOne, Depth+1))
949       return I;
950     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
951     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
952
953     // If all of the demanded bits are known 1 on one side, return the other.
954     // These bits cannot contribute to the result of the 'and'.
955     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
956         (DemandedMask & ~LHSKnownZero))
957       return I->getOperand(0);
958     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
959         (DemandedMask & ~RHSKnownZero))
960       return I->getOperand(1);
961     
962     // If all of the demanded bits in the inputs are known zeros, return zero.
963     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
964       return Constant::getNullValue(VTy);
965       
966     // If the RHS is a constant, see if we can simplify it.
967     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
968       return I;
969       
970     // Output known-1 bits are only known if set in both the LHS & RHS.
971     RHSKnownOne &= LHSKnownOne;
972     // Output known-0 are known to be clear if zero in either the LHS | RHS.
973     RHSKnownZero |= LHSKnownZero;
974     break;
975   case Instruction::Or:
976     // If either the LHS or the RHS are One, the result is One.
977     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
978                              RHSKnownZero, RHSKnownOne, Depth+1) ||
979         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
980                              LHSKnownZero, LHSKnownOne, Depth+1))
981       return I;
982     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
983     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
984     
985     // If all of the demanded bits are known zero on one side, return the other.
986     // These bits cannot contribute to the result of the 'or'.
987     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
988         (DemandedMask & ~LHSKnownOne))
989       return I->getOperand(0);
990     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
991         (DemandedMask & ~RHSKnownOne))
992       return I->getOperand(1);
993
994     // If all of the potentially set bits on one side are known to be set on
995     // the other side, just use the 'other' side.
996     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
997         (DemandedMask & (~RHSKnownZero)))
998       return I->getOperand(0);
999     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1000         (DemandedMask & (~LHSKnownZero)))
1001       return I->getOperand(1);
1002         
1003     // If the RHS is a constant, see if we can simplify it.
1004     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1005       return I;
1006           
1007     // Output known-0 bits are only known if clear in both the LHS & RHS.
1008     RHSKnownZero &= LHSKnownZero;
1009     // Output known-1 are known to be set if set in either the LHS | RHS.
1010     RHSKnownOne |= LHSKnownOne;
1011     break;
1012   case Instruction::Xor: {
1013     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1014                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1015         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1016                              LHSKnownZero, LHSKnownOne, Depth+1))
1017       return I;
1018     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1019     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1020     
1021     // If all of the demanded bits are known zero on one side, return the other.
1022     // These bits cannot contribute to the result of the 'xor'.
1023     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1024       return I->getOperand(0);
1025     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1026       return I->getOperand(1);
1027     
1028     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1029     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1030                          (RHSKnownOne & LHSKnownOne);
1031     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1032     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1033                         (RHSKnownOne & LHSKnownZero);
1034     
1035     // If all of the demanded bits are known to be zero on one side or the
1036     // other, turn this into an *inclusive* or.
1037     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1038     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1039       Instruction *Or = 
1040         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1041                                  I->getName());
1042       return InsertNewInstBefore(Or, *I);
1043     }
1044     
1045     // If all of the demanded bits on one side are known, and all of the set
1046     // bits on that side are also known to be set on the other side, turn this
1047     // into an AND, as we know the bits will be cleared.
1048     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1049     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1050       // all known
1051       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1052         Constant *AndC = Constant::getIntegerValue(VTy,
1053                                                    ~RHSKnownOne & DemandedMask);
1054         Instruction *And = 
1055           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1056         return InsertNewInstBefore(And, *I);
1057       }
1058     }
1059     
1060     // If the RHS is a constant, see if we can simplify it.
1061     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1062     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1063       return I;
1064     
1065     // If our LHS is an 'and' and if it has one use, and if any of the bits we
1066     // are flipping are known to be set, then the xor is just resetting those
1067     // bits to zero.  We can just knock out bits from the 'and' and the 'xor',
1068     // simplifying both of them.
1069     if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1070       if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1071           isa<ConstantInt>(I->getOperand(1)) &&
1072           isa<ConstantInt>(LHSInst->getOperand(1)) &&
1073           (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1074         ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1075         ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1076         APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1077         
1078         Constant *AndC =
1079           ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1080         Instruction *NewAnd = 
1081           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1082         InsertNewInstBefore(NewAnd, *I);
1083         
1084         Constant *XorC =
1085           ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1086         Instruction *NewXor =
1087           BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1088         return InsertNewInstBefore(NewXor, *I);
1089       }
1090           
1091           
1092     RHSKnownZero = KnownZeroOut;
1093     RHSKnownOne  = KnownOneOut;
1094     break;
1095   }
1096   case Instruction::Select:
1097     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1098                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1099         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1100                              LHSKnownZero, LHSKnownOne, Depth+1))
1101       return I;
1102     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1103     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1104     
1105     // If the operands are constants, see if we can simplify them.
1106     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1107         ShrinkDemandedConstant(I, 2, DemandedMask))
1108       return I;
1109     
1110     // Only known if known in both the LHS and RHS.
1111     RHSKnownOne &= LHSKnownOne;
1112     RHSKnownZero &= LHSKnownZero;
1113     break;
1114   case Instruction::Trunc: {
1115     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1116     DemandedMask.zext(truncBf);
1117     RHSKnownZero.zext(truncBf);
1118     RHSKnownOne.zext(truncBf);
1119     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1120                              RHSKnownZero, RHSKnownOne, Depth+1))
1121       return I;
1122     DemandedMask.trunc(BitWidth);
1123     RHSKnownZero.trunc(BitWidth);
1124     RHSKnownOne.trunc(BitWidth);
1125     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1126     break;
1127   }
1128   case Instruction::BitCast:
1129     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1130       return false;  // vector->int or fp->int?
1131
1132     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1133       if (const VectorType *SrcVTy =
1134             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1135         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1136           // Don't touch a bitcast between vectors of different element counts.
1137           return false;
1138       } else
1139         // Don't touch a scalar-to-vector bitcast.
1140         return false;
1141     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1142       // Don't touch a vector-to-scalar bitcast.
1143       return false;
1144
1145     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1146                              RHSKnownZero, RHSKnownOne, Depth+1))
1147       return I;
1148     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1149     break;
1150   case Instruction::ZExt: {
1151     // Compute the bits in the result that are not present in the input.
1152     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1153     
1154     DemandedMask.trunc(SrcBitWidth);
1155     RHSKnownZero.trunc(SrcBitWidth);
1156     RHSKnownOne.trunc(SrcBitWidth);
1157     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1158                              RHSKnownZero, RHSKnownOne, Depth+1))
1159       return I;
1160     DemandedMask.zext(BitWidth);
1161     RHSKnownZero.zext(BitWidth);
1162     RHSKnownOne.zext(BitWidth);
1163     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1164     // The top bits are known to be zero.
1165     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1166     break;
1167   }
1168   case Instruction::SExt: {
1169     // Compute the bits in the result that are not present in the input.
1170     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1171     
1172     APInt InputDemandedBits = DemandedMask & 
1173                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1174
1175     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1176     // If any of the sign extended bits are demanded, we know that the sign
1177     // bit is demanded.
1178     if ((NewBits & DemandedMask) != 0)
1179       InputDemandedBits.set(SrcBitWidth-1);
1180       
1181     InputDemandedBits.trunc(SrcBitWidth);
1182     RHSKnownZero.trunc(SrcBitWidth);
1183     RHSKnownOne.trunc(SrcBitWidth);
1184     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1185                              RHSKnownZero, RHSKnownOne, Depth+1))
1186       return I;
1187     InputDemandedBits.zext(BitWidth);
1188     RHSKnownZero.zext(BitWidth);
1189     RHSKnownOne.zext(BitWidth);
1190     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1191       
1192     // If the sign bit of the input is known set or clear, then we know the
1193     // top bits of the result.
1194
1195     // If the input sign bit is known zero, or if the NewBits are not demanded
1196     // convert this into a zero extension.
1197     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1198       // Convert to ZExt cast
1199       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1200       return InsertNewInstBefore(NewCast, *I);
1201     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1202       RHSKnownOne |= NewBits;
1203     }
1204     break;
1205   }
1206   case Instruction::Add: {
1207     // Figure out what the input bits are.  If the top bits of the and result
1208     // are not demanded, then the add doesn't demand them from its input
1209     // either.
1210     unsigned NLZ = DemandedMask.countLeadingZeros();
1211       
1212     // If there is a constant on the RHS, there are a variety of xformations
1213     // we can do.
1214     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1215       // If null, this should be simplified elsewhere.  Some of the xforms here
1216       // won't work if the RHS is zero.
1217       if (RHS->isZero())
1218         break;
1219       
1220       // If the top bit of the output is demanded, demand everything from the
1221       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1222       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1223
1224       // Find information about known zero/one bits in the input.
1225       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1226                                LHSKnownZero, LHSKnownOne, Depth+1))
1227         return I;
1228
1229       // If the RHS of the add has bits set that can't affect the input, reduce
1230       // the constant.
1231       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1232         return I;
1233       
1234       // Avoid excess work.
1235       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1236         break;
1237       
1238       // Turn it into OR if input bits are zero.
1239       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1240         Instruction *Or =
1241           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1242                                    I->getName());
1243         return InsertNewInstBefore(Or, *I);
1244       }
1245       
1246       // We can say something about the output known-zero and known-one bits,
1247       // depending on potential carries from the input constant and the
1248       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1249       // bits set and the RHS constant is 0x01001, then we know we have a known
1250       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1251       
1252       // To compute this, we first compute the potential carry bits.  These are
1253       // the bits which may be modified.  I'm not aware of a better way to do
1254       // this scan.
1255       const APInt &RHSVal = RHS->getValue();
1256       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1257       
1258       // Now that we know which bits have carries, compute the known-1/0 sets.
1259       
1260       // Bits are known one if they are known zero in one operand and one in the
1261       // other, and there is no input carry.
1262       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1263                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1264       
1265       // Bits are known zero if they are known zero in both operands and there
1266       // is no input carry.
1267       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1268     } else {
1269       // If the high-bits of this ADD are not demanded, then it does not demand
1270       // the high bits of its LHS or RHS.
1271       if (DemandedMask[BitWidth-1] == 0) {
1272         // Right fill the mask of bits for this ADD to demand the most
1273         // significant bit and all those below it.
1274         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1275         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1276                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1277             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1278                                  LHSKnownZero, LHSKnownOne, Depth+1))
1279           return I;
1280       }
1281     }
1282     break;
1283   }
1284   case Instruction::Sub:
1285     // If the high-bits of this SUB are not demanded, then it does not demand
1286     // the high bits of its LHS or RHS.
1287     if (DemandedMask[BitWidth-1] == 0) {
1288       // Right fill the mask of bits for this SUB to demand the most
1289       // significant bit and all those below it.
1290       uint32_t NLZ = DemandedMask.countLeadingZeros();
1291       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1292       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1293                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1294           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1295                                LHSKnownZero, LHSKnownOne, Depth+1))
1296         return I;
1297     }
1298     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1299     // the known zeros and ones.
1300     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1301     break;
1302   case Instruction::Shl:
1303     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1304       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1305       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1306       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1307                                RHSKnownZero, RHSKnownOne, Depth+1))
1308         return I;
1309       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1310       RHSKnownZero <<= ShiftAmt;
1311       RHSKnownOne  <<= ShiftAmt;
1312       // low bits known zero.
1313       if (ShiftAmt)
1314         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1315     }
1316     break;
1317   case Instruction::LShr:
1318     // For a logical shift right
1319     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1320       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1321       
1322       // Unsigned shift right.
1323       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1324       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1325                                RHSKnownZero, RHSKnownOne, Depth+1))
1326         return I;
1327       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1328       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1329       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1330       if (ShiftAmt) {
1331         // Compute the new bits that are at the top now.
1332         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1333         RHSKnownZero |= HighBits;  // high bits known zero.
1334       }
1335     }
1336     break;
1337   case Instruction::AShr:
1338     // If this is an arithmetic shift right and only the low-bit is set, we can
1339     // always convert this into a logical shr, even if the shift amount is
1340     // variable.  The low bit of the shift cannot be an input sign bit unless
1341     // the shift amount is >= the size of the datatype, which is undefined.
1342     if (DemandedMask == 1) {
1343       // Perform the logical shift right.
1344       Instruction *NewVal = BinaryOperator::CreateLShr(
1345                         I->getOperand(0), I->getOperand(1), I->getName());
1346       return InsertNewInstBefore(NewVal, *I);
1347     }    
1348
1349     // If the sign bit is the only bit demanded by this ashr, then there is no
1350     // need to do it, the shift doesn't change the high bit.
1351     if (DemandedMask.isSignBit())
1352       return I->getOperand(0);
1353     
1354     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1355       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1356       
1357       // Signed shift right.
1358       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1359       // If any of the "high bits" are demanded, we should set the sign bit as
1360       // demanded.
1361       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1362         DemandedMaskIn.set(BitWidth-1);
1363       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1364                                RHSKnownZero, RHSKnownOne, Depth+1))
1365         return I;
1366       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1367       // Compute the new bits that are at the top now.
1368       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1369       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1370       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1371         
1372       // Handle the sign bits.
1373       APInt SignBit(APInt::getSignBit(BitWidth));
1374       // Adjust to where it is now in the mask.
1375       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1376         
1377       // If the input sign bit is known to be zero, or if none of the top bits
1378       // are demanded, turn this into an unsigned shift right.
1379       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1380           (HighBits & ~DemandedMask) == HighBits) {
1381         // Perform the logical shift right.
1382         Instruction *NewVal = BinaryOperator::CreateLShr(
1383                           I->getOperand(0), SA, I->getName());
1384         return InsertNewInstBefore(NewVal, *I);
1385       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1386         RHSKnownOne |= HighBits;
1387       }
1388     }
1389     break;
1390   case Instruction::SRem:
1391     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1392       APInt RA = Rem->getValue().abs();
1393       if (RA.isPowerOf2()) {
1394         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1395           return I->getOperand(0);
1396
1397         APInt LowBits = RA - 1;
1398         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1399         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1400                                  LHSKnownZero, LHSKnownOne, Depth+1))
1401           return I;
1402
1403         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1404           LHSKnownZero |= ~LowBits;
1405
1406         KnownZero |= LHSKnownZero & DemandedMask;
1407
1408         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1409       }
1410     }
1411     break;
1412   case Instruction::URem: {
1413     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1414     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1415     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1416                              KnownZero2, KnownOne2, Depth+1) ||
1417         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1418                              KnownZero2, KnownOne2, Depth+1))
1419       return I;
1420
1421     unsigned Leaders = KnownZero2.countLeadingOnes();
1422     Leaders = std::max(Leaders,
1423                        KnownZero2.countLeadingOnes());
1424     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1425     break;
1426   }
1427   case Instruction::Call:
1428     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1429       switch (II->getIntrinsicID()) {
1430       default: break;
1431       case Intrinsic::bswap: {
1432         // If the only bits demanded come from one byte of the bswap result,
1433         // just shift the input byte into position to eliminate the bswap.
1434         unsigned NLZ = DemandedMask.countLeadingZeros();
1435         unsigned NTZ = DemandedMask.countTrailingZeros();
1436           
1437         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1438         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1439         // have 14 leading zeros, round to 8.
1440         NLZ &= ~7;
1441         NTZ &= ~7;
1442         // If we need exactly one byte, we can do this transformation.
1443         if (BitWidth-NLZ-NTZ == 8) {
1444           unsigned ResultBit = NTZ;
1445           unsigned InputBit = BitWidth-NTZ-8;
1446           
1447           // Replace this with either a left or right shift to get the byte into
1448           // the right place.
1449           Instruction *NewVal;
1450           if (InputBit > ResultBit)
1451             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1452                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1453           else
1454             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1455                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1456           NewVal->takeName(I);
1457           return InsertNewInstBefore(NewVal, *I);
1458         }
1459           
1460         // TODO: Could compute known zero/one bits based on the input.
1461         break;
1462       }
1463       }
1464     }
1465     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1466     break;
1467   }
1468   
1469   // If the client is only demanding bits that we know, return the known
1470   // constant.
1471   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1472     return Constant::getIntegerValue(VTy, RHSKnownOne);
1473   return false;
1474 }
1475
1476
1477 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1478 /// any number of elements. DemandedElts contains the set of elements that are
1479 /// actually used by the caller.  This method analyzes which elements of the
1480 /// operand are undef and returns that information in UndefElts.
1481 ///
1482 /// If the information about demanded elements can be used to simplify the
1483 /// operation, the operation is simplified, then the resultant value is
1484 /// returned.  This returns null if no change was made.
1485 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1486                                                 APInt& UndefElts,
1487                                                 unsigned Depth) {
1488   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1489   APInt EltMask(APInt::getAllOnesValue(VWidth));
1490   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1491
1492   if (isa<UndefValue>(V)) {
1493     // If the entire vector is undefined, just return this info.
1494     UndefElts = EltMask;
1495     return 0;
1496   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1497     UndefElts = EltMask;
1498     return UndefValue::get(V->getType());
1499   }
1500
1501   UndefElts = 0;
1502   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1503     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1504     Constant *Undef = UndefValue::get(EltTy);
1505
1506     std::vector<Constant*> Elts;
1507     for (unsigned i = 0; i != VWidth; ++i)
1508       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1509         Elts.push_back(Undef);
1510         UndefElts.set(i);
1511       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1512         Elts.push_back(Undef);
1513         UndefElts.set(i);
1514       } else {                               // Otherwise, defined.
1515         Elts.push_back(CP->getOperand(i));
1516       }
1517
1518     // If we changed the constant, return it.
1519     Constant *NewCP = ConstantVector::get(Elts);
1520     return NewCP != CP ? NewCP : 0;
1521   } else if (isa<ConstantAggregateZero>(V)) {
1522     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1523     // set to undef.
1524     
1525     // Check if this is identity. If so, return 0 since we are not simplifying
1526     // anything.
1527     if (DemandedElts == ((1ULL << VWidth) -1))
1528       return 0;
1529     
1530     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1531     Constant *Zero = Constant::getNullValue(EltTy);
1532     Constant *Undef = UndefValue::get(EltTy);
1533     std::vector<Constant*> Elts;
1534     for (unsigned i = 0; i != VWidth; ++i) {
1535       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1536       Elts.push_back(Elt);
1537     }
1538     UndefElts = DemandedElts ^ EltMask;
1539     return ConstantVector::get(Elts);
1540   }
1541   
1542   // Limit search depth.
1543   if (Depth == 10)
1544     return 0;
1545
1546   // If multiple users are using the root value, procede with
1547   // simplification conservatively assuming that all elements
1548   // are needed.
1549   if (!V->hasOneUse()) {
1550     // Quit if we find multiple users of a non-root value though.
1551     // They'll be handled when it's their turn to be visited by
1552     // the main instcombine process.
1553     if (Depth != 0)
1554       // TODO: Just compute the UndefElts information recursively.
1555       return 0;
1556
1557     // Conservatively assume that all elements are needed.
1558     DemandedElts = EltMask;
1559   }
1560   
1561   Instruction *I = dyn_cast<Instruction>(V);
1562   if (!I) return 0;        // Only analyze instructions.
1563   
1564   bool MadeChange = false;
1565   APInt UndefElts2(VWidth, 0);
1566   Value *TmpV;
1567   switch (I->getOpcode()) {
1568   default: break;
1569     
1570   case Instruction::InsertElement: {
1571     // If this is a variable index, we don't know which element it overwrites.
1572     // demand exactly the same input as we produce.
1573     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1574     if (Idx == 0) {
1575       // Note that we can't propagate undef elt info, because we don't know
1576       // which elt is getting updated.
1577       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1578                                         UndefElts2, Depth+1);
1579       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1580       break;
1581     }
1582     
1583     // If this is inserting an element that isn't demanded, remove this
1584     // insertelement.
1585     unsigned IdxNo = Idx->getZExtValue();
1586     if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1587       Worklist.Add(I);
1588       return I->getOperand(0);
1589     }
1590     
1591     // Otherwise, the element inserted overwrites whatever was there, so the
1592     // input demanded set is simpler than the output set.
1593     APInt DemandedElts2 = DemandedElts;
1594     DemandedElts2.clear(IdxNo);
1595     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1596                                       UndefElts, Depth+1);
1597     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1598
1599     // The inserted element is defined.
1600     UndefElts.clear(IdxNo);
1601     break;
1602   }
1603   case Instruction::ShuffleVector: {
1604     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1605     uint64_t LHSVWidth =
1606       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1607     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1608     for (unsigned i = 0; i < VWidth; i++) {
1609       if (DemandedElts[i]) {
1610         unsigned MaskVal = Shuffle->getMaskValue(i);
1611         if (MaskVal != -1u) {
1612           assert(MaskVal < LHSVWidth * 2 &&
1613                  "shufflevector mask index out of range!");
1614           if (MaskVal < LHSVWidth)
1615             LeftDemanded.set(MaskVal);
1616           else
1617             RightDemanded.set(MaskVal - LHSVWidth);
1618         }
1619       }
1620     }
1621
1622     APInt UndefElts4(LHSVWidth, 0);
1623     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1624                                       UndefElts4, Depth+1);
1625     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1626
1627     APInt UndefElts3(LHSVWidth, 0);
1628     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1629                                       UndefElts3, Depth+1);
1630     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1631
1632     bool NewUndefElts = false;
1633     for (unsigned i = 0; i < VWidth; i++) {
1634       unsigned MaskVal = Shuffle->getMaskValue(i);
1635       if (MaskVal == -1u) {
1636         UndefElts.set(i);
1637       } else if (MaskVal < LHSVWidth) {
1638         if (UndefElts4[MaskVal]) {
1639           NewUndefElts = true;
1640           UndefElts.set(i);
1641         }
1642       } else {
1643         if (UndefElts3[MaskVal - LHSVWidth]) {
1644           NewUndefElts = true;
1645           UndefElts.set(i);
1646         }
1647       }
1648     }
1649
1650     if (NewUndefElts) {
1651       // Add additional discovered undefs.
1652       std::vector<Constant*> Elts;
1653       for (unsigned i = 0; i < VWidth; ++i) {
1654         if (UndefElts[i])
1655           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
1656         else
1657           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
1658                                           Shuffle->getMaskValue(i)));
1659       }
1660       I->setOperand(2, ConstantVector::get(Elts));
1661       MadeChange = true;
1662     }
1663     break;
1664   }
1665   case Instruction::BitCast: {
1666     // Vector->vector casts only.
1667     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1668     if (!VTy) break;
1669     unsigned InVWidth = VTy->getNumElements();
1670     APInt InputDemandedElts(InVWidth, 0);
1671     unsigned Ratio;
1672
1673     if (VWidth == InVWidth) {
1674       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1675       // elements as are demanded of us.
1676       Ratio = 1;
1677       InputDemandedElts = DemandedElts;
1678     } else if (VWidth > InVWidth) {
1679       // Untested so far.
1680       break;
1681       
1682       // If there are more elements in the result than there are in the source,
1683       // then an input element is live if any of the corresponding output
1684       // elements are live.
1685       Ratio = VWidth/InVWidth;
1686       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1687         if (DemandedElts[OutIdx])
1688           InputDemandedElts.set(OutIdx/Ratio);
1689       }
1690     } else {
1691       // Untested so far.
1692       break;
1693       
1694       // If there are more elements in the source than there are in the result,
1695       // then an input element is live if the corresponding output element is
1696       // live.
1697       Ratio = InVWidth/VWidth;
1698       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1699         if (DemandedElts[InIdx/Ratio])
1700           InputDemandedElts.set(InIdx);
1701     }
1702     
1703     // div/rem demand all inputs, because they don't want divide by zero.
1704     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1705                                       UndefElts2, Depth+1);
1706     if (TmpV) {
1707       I->setOperand(0, TmpV);
1708       MadeChange = true;
1709     }
1710     
1711     UndefElts = UndefElts2;
1712     if (VWidth > InVWidth) {
1713       llvm_unreachable("Unimp");
1714       // If there are more elements in the result than there are in the source,
1715       // then an output element is undef if the corresponding input element is
1716       // undef.
1717       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1718         if (UndefElts2[OutIdx/Ratio])
1719           UndefElts.set(OutIdx);
1720     } else if (VWidth < InVWidth) {
1721       llvm_unreachable("Unimp");
1722       // If there are more elements in the source than there are in the result,
1723       // then a result element is undef if all of the corresponding input
1724       // elements are undef.
1725       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1726       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1727         if (!UndefElts2[InIdx])            // Not undef?
1728           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1729     }
1730     break;
1731   }
1732   case Instruction::And:
1733   case Instruction::Or:
1734   case Instruction::Xor:
1735   case Instruction::Add:
1736   case Instruction::Sub:
1737   case Instruction::Mul:
1738     // div/rem demand all inputs, because they don't want divide by zero.
1739     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1740                                       UndefElts, Depth+1);
1741     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1742     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1743                                       UndefElts2, Depth+1);
1744     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1745       
1746     // Output elements are undefined if both are undefined.  Consider things
1747     // like undef&0.  The result is known zero, not undef.
1748     UndefElts &= UndefElts2;
1749     break;
1750     
1751   case Instruction::Call: {
1752     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1753     if (!II) break;
1754     switch (II->getIntrinsicID()) {
1755     default: break;
1756       
1757     // Binary vector operations that work column-wise.  A dest element is a
1758     // function of the corresponding input elements from the two inputs.
1759     case Intrinsic::x86_sse_sub_ss:
1760     case Intrinsic::x86_sse_mul_ss:
1761     case Intrinsic::x86_sse_min_ss:
1762     case Intrinsic::x86_sse_max_ss:
1763     case Intrinsic::x86_sse2_sub_sd:
1764     case Intrinsic::x86_sse2_mul_sd:
1765     case Intrinsic::x86_sse2_min_sd:
1766     case Intrinsic::x86_sse2_max_sd:
1767       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1768                                         UndefElts, Depth+1);
1769       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1770       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1771                                         UndefElts2, Depth+1);
1772       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1773
1774       // If only the low elt is demanded and this is a scalarizable intrinsic,
1775       // scalarize it now.
1776       if (DemandedElts == 1) {
1777         switch (II->getIntrinsicID()) {
1778         default: break;
1779         case Intrinsic::x86_sse_sub_ss:
1780         case Intrinsic::x86_sse_mul_ss:
1781         case Intrinsic::x86_sse2_sub_sd:
1782         case Intrinsic::x86_sse2_mul_sd:
1783           // TODO: Lower MIN/MAX/ABS/etc
1784           Value *LHS = II->getOperand(1);
1785           Value *RHS = II->getOperand(2);
1786           // Extract the element as scalars.
1787           LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS, 
1788             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1789           RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1790             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1791           
1792           switch (II->getIntrinsicID()) {
1793           default: llvm_unreachable("Case stmts out of sync!");
1794           case Intrinsic::x86_sse_sub_ss:
1795           case Intrinsic::x86_sse2_sub_sd:
1796             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1797                                                         II->getName()), *II);
1798             break;
1799           case Intrinsic::x86_sse_mul_ss:
1800           case Intrinsic::x86_sse2_mul_sd:
1801             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1802                                                          II->getName()), *II);
1803             break;
1804           }
1805           
1806           Instruction *New =
1807             InsertElementInst::Create(
1808               UndefValue::get(II->getType()), TmpV,
1809               ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
1810           InsertNewInstBefore(New, *II);
1811           return New;
1812         }            
1813       }
1814         
1815       // Output elements are undefined if both are undefined.  Consider things
1816       // like undef&0.  The result is known zero, not undef.
1817       UndefElts &= UndefElts2;
1818       break;
1819     }
1820     break;
1821   }
1822   }
1823   return MadeChange ? I : 0;
1824 }
1825
1826
1827 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1828 /// function is designed to check a chain of associative operators for a
1829 /// potential to apply a certain optimization.  Since the optimization may be
1830 /// applicable if the expression was reassociated, this checks the chain, then
1831 /// reassociates the expression as necessary to expose the optimization
1832 /// opportunity.  This makes use of a special Functor, which must define
1833 /// 'shouldApply' and 'apply' methods.
1834 ///
1835 template<typename Functor>
1836 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1837   unsigned Opcode = Root.getOpcode();
1838   Value *LHS = Root.getOperand(0);
1839
1840   // Quick check, see if the immediate LHS matches...
1841   if (F.shouldApply(LHS))
1842     return F.apply(Root);
1843
1844   // Otherwise, if the LHS is not of the same opcode as the root, return.
1845   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1846   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1847     // Should we apply this transform to the RHS?
1848     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1849
1850     // If not to the RHS, check to see if we should apply to the LHS...
1851     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1852       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1853       ShouldApply = true;
1854     }
1855
1856     // If the functor wants to apply the optimization to the RHS of LHSI,
1857     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1858     if (ShouldApply) {
1859       // Now all of the instructions are in the current basic block, go ahead
1860       // and perform the reassociation.
1861       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1862
1863       // First move the selected RHS to the LHS of the root...
1864       Root.setOperand(0, LHSI->getOperand(1));
1865
1866       // Make what used to be the LHS of the root be the user of the root...
1867       Value *ExtraOperand = TmpLHSI->getOperand(1);
1868       if (&Root == TmpLHSI) {
1869         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1870         return 0;
1871       }
1872       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1873       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1874       BasicBlock::iterator ARI = &Root; ++ARI;
1875       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1876       ARI = Root;
1877
1878       // Now propagate the ExtraOperand down the chain of instructions until we
1879       // get to LHSI.
1880       while (TmpLHSI != LHSI) {
1881         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1882         // Move the instruction to immediately before the chain we are
1883         // constructing to avoid breaking dominance properties.
1884         NextLHSI->moveBefore(ARI);
1885         ARI = NextLHSI;
1886
1887         Value *NextOp = NextLHSI->getOperand(1);
1888         NextLHSI->setOperand(1, ExtraOperand);
1889         TmpLHSI = NextLHSI;
1890         ExtraOperand = NextOp;
1891       }
1892
1893       // Now that the instructions are reassociated, have the functor perform
1894       // the transformation...
1895       return F.apply(Root);
1896     }
1897
1898     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1899   }
1900   return 0;
1901 }
1902
1903 namespace {
1904
1905 // AddRHS - Implements: X + X --> X << 1
1906 struct AddRHS {
1907   Value *RHS;
1908   explicit AddRHS(Value *rhs) : RHS(rhs) {}
1909   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1910   Instruction *apply(BinaryOperator &Add) const {
1911     return BinaryOperator::CreateShl(Add.getOperand(0),
1912                                      ConstantInt::get(Add.getType(), 1));
1913   }
1914 };
1915
1916 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1917 //                 iff C1&C2 == 0
1918 struct AddMaskingAnd {
1919   Constant *C2;
1920   explicit AddMaskingAnd(Constant *c) : C2(c) {}
1921   bool shouldApply(Value *LHS) const {
1922     ConstantInt *C1;
1923     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1924            ConstantExpr::getAnd(C1, C2)->isNullValue();
1925   }
1926   Instruction *apply(BinaryOperator &Add) const {
1927     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1928   }
1929 };
1930
1931 }
1932
1933 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1934                                              InstCombiner *IC) {
1935   if (CastInst *CI = dyn_cast<CastInst>(&I))
1936     return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
1937
1938   // Figure out if the constant is the left or the right argument.
1939   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1940   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1941
1942   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1943     if (ConstIsRHS)
1944       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1945     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1946   }
1947
1948   Value *Op0 = SO, *Op1 = ConstOperand;
1949   if (!ConstIsRHS)
1950     std::swap(Op0, Op1);
1951   
1952   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1953     return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1954                                     SO->getName()+".op");
1955   if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1956     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1957                                    SO->getName()+".cmp");
1958   if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1959     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1960                                    SO->getName()+".cmp");
1961   llvm_unreachable("Unknown binary instruction type!");
1962 }
1963
1964 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1965 // constant as the other operand, try to fold the binary operator into the
1966 // select arguments.  This also works for Cast instructions, which obviously do
1967 // not have a second operand.
1968 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1969                                      InstCombiner *IC) {
1970   // Don't modify shared select instructions
1971   if (!SI->hasOneUse()) return 0;
1972   Value *TV = SI->getOperand(1);
1973   Value *FV = SI->getOperand(2);
1974
1975   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1976     // Bool selects with constant operands can be folded to logical ops.
1977     if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
1978
1979     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1980     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1981
1982     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1983                               SelectFalseVal);
1984   }
1985   return 0;
1986 }
1987
1988
1989 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
1990 /// has a PHI node as operand #0, see if we can fold the instruction into the
1991 /// PHI (which is only possible if all operands to the PHI are constants).
1992 ///
1993 /// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
1994 /// that would normally be unprofitable because they strongly encourage jump
1995 /// threading.
1996 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
1997                                          bool AllowAggressive) {
1998   AllowAggressive = false;
1999   PHINode *PN = cast<PHINode>(I.getOperand(0));
2000   unsigned NumPHIValues = PN->getNumIncomingValues();
2001   if (NumPHIValues == 0 ||
2002       // We normally only transform phis with a single use, unless we're trying
2003       // hard to make jump threading happen.
2004       (!PN->hasOneUse() && !AllowAggressive))
2005     return 0;
2006   
2007   
2008   // Check to see if all of the operands of the PHI are simple constants
2009   // (constantint/constantfp/undef).  If there is one non-constant value,
2010   // remember the BB it is in.  If there is more than one or if *it* is a PHI,
2011   // bail out.  We don't do arbitrary constant expressions here because moving
2012   // their computation can be expensive without a cost model.
2013   BasicBlock *NonConstBB = 0;
2014   for (unsigned i = 0; i != NumPHIValues; ++i)
2015     if (!isa<Constant>(PN->getIncomingValue(i)) ||
2016         isa<ConstantExpr>(PN->getIncomingValue(i))) {
2017       if (NonConstBB) return 0;  // More than one non-const value.
2018       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
2019       NonConstBB = PN->getIncomingBlock(i);
2020       
2021       // If the incoming non-constant value is in I's block, we have an infinite
2022       // loop.
2023       if (NonConstBB == I.getParent())
2024         return 0;
2025     }
2026   
2027   // If there is exactly one non-constant value, we can insert a copy of the
2028   // operation in that block.  However, if this is a critical edge, we would be
2029   // inserting the computation one some other paths (e.g. inside a loop).  Only
2030   // do this if the pred block is unconditionally branching into the phi block.
2031   if (NonConstBB != 0 && !AllowAggressive) {
2032     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2033     if (!BI || !BI->isUnconditional()) return 0;
2034   }
2035
2036   // Okay, we can do the transformation: create the new PHI node.
2037   PHINode *NewPN = PHINode::Create(I.getType(), "");
2038   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2039   InsertNewInstBefore(NewPN, *PN);
2040   NewPN->takeName(PN);
2041
2042   // Next, add all of the operands to the PHI.
2043   if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2044     // We only currently try to fold the condition of a select when it is a phi,
2045     // not the true/false values.
2046     Value *TrueV = SI->getTrueValue();
2047     Value *FalseV = SI->getFalseValue();
2048     BasicBlock *PhiTransBB = PN->getParent();
2049     for (unsigned i = 0; i != NumPHIValues; ++i) {
2050       BasicBlock *ThisBB = PN->getIncomingBlock(i);
2051       Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2052       Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
2053       Value *InV = 0;
2054       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2055         InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
2056       } else {
2057         assert(PN->getIncomingBlock(i) == NonConstBB);
2058         InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2059                                  FalseVInPred,
2060                                  "phitmp", NonConstBB->getTerminator());
2061         Worklist.Add(cast<Instruction>(InV));
2062       }
2063       NewPN->addIncoming(InV, ThisBB);
2064     }
2065   } else if (I.getNumOperands() == 2) {
2066     Constant *C = cast<Constant>(I.getOperand(1));
2067     for (unsigned i = 0; i != NumPHIValues; ++i) {
2068       Value *InV = 0;
2069       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2070         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2071           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2072         else
2073           InV = ConstantExpr::get(I.getOpcode(), InC, C);
2074       } else {
2075         assert(PN->getIncomingBlock(i) == NonConstBB);
2076         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2077           InV = BinaryOperator::Create(BO->getOpcode(),
2078                                        PN->getIncomingValue(i), C, "phitmp",
2079                                        NonConstBB->getTerminator());
2080         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2081           InV = CmpInst::Create(CI->getOpcode(),
2082                                 CI->getPredicate(),
2083                                 PN->getIncomingValue(i), C, "phitmp",
2084                                 NonConstBB->getTerminator());
2085         else
2086           llvm_unreachable("Unknown binop!");
2087         
2088         Worklist.Add(cast<Instruction>(InV));
2089       }
2090       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2091     }
2092   } else { 
2093     CastInst *CI = cast<CastInst>(&I);
2094     const Type *RetTy = CI->getType();
2095     for (unsigned i = 0; i != NumPHIValues; ++i) {
2096       Value *InV;
2097       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2098         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2099       } else {
2100         assert(PN->getIncomingBlock(i) == NonConstBB);
2101         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2102                                I.getType(), "phitmp", 
2103                                NonConstBB->getTerminator());
2104         Worklist.Add(cast<Instruction>(InV));
2105       }
2106       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2107     }
2108   }
2109   return ReplaceInstUsesWith(I, NewPN);
2110 }
2111
2112
2113 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2114 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2115 /// This basically requires proving that the add in the original type would not
2116 /// overflow to change the sign bit or have a carry out.
2117 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2118   // There are different heuristics we can use for this.  Here are some simple
2119   // ones.
2120   
2121   // Add has the property that adding any two 2's complement numbers can only 
2122   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2123   // have at least two sign bits, we know that the addition of the two values will
2124   // sign extend fine.
2125   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2126     return true;
2127   
2128   
2129   // If one of the operands only has one non-zero bit, and if the other operand
2130   // has a known-zero bit in a more significant place than it (not including the
2131   // sign bit) the ripple may go up to and fill the zero, but won't change the
2132   // sign.  For example, (X & ~4) + 1.
2133   
2134   // TODO: Implement.
2135   
2136   return false;
2137 }
2138
2139
2140 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2141   bool Changed = SimplifyCommutative(I);
2142   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2143
2144   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2145     // X + undef -> undef
2146     if (isa<UndefValue>(RHS))
2147       return ReplaceInstUsesWith(I, RHS);
2148
2149     // X + 0 --> X
2150     if (RHSC->isNullValue())
2151       return ReplaceInstUsesWith(I, LHS);
2152
2153     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2154       // X + (signbit) --> X ^ signbit
2155       const APInt& Val = CI->getValue();
2156       uint32_t BitWidth = Val.getBitWidth();
2157       if (Val == APInt::getSignBit(BitWidth))
2158         return BinaryOperator::CreateXor(LHS, RHS);
2159       
2160       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2161       // (X & 254)+1 -> (X&254)|1
2162       if (SimplifyDemandedInstructionBits(I))
2163         return &I;
2164
2165       // zext(bool) + C -> bool ? C + 1 : C
2166       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2167         if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2168           return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2169     }
2170
2171     if (isa<PHINode>(LHS))
2172       if (Instruction *NV = FoldOpIntoPhi(I))
2173         return NV;
2174     
2175     ConstantInt *XorRHS = 0;
2176     Value *XorLHS = 0;
2177     if (isa<ConstantInt>(RHSC) &&
2178         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2179       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2180       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2181       
2182       uint32_t Size = TySizeBits / 2;
2183       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2184       APInt CFF80Val(-C0080Val);
2185       do {
2186         if (TySizeBits > Size) {
2187           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2188           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2189           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2190               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2191             // This is a sign extend if the top bits are known zero.
2192             if (!MaskedValueIsZero(XorLHS, 
2193                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2194               Size = 0;  // Not a sign ext, but can't be any others either.
2195             break;
2196           }
2197         }
2198         Size >>= 1;
2199         C0080Val = APIntOps::lshr(C0080Val, Size);
2200         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2201       } while (Size >= 1);
2202       
2203       // FIXME: This shouldn't be necessary. When the backends can handle types
2204       // with funny bit widths then this switch statement should be removed. It
2205       // is just here to get the size of the "middle" type back up to something
2206       // that the back ends can handle.
2207       const Type *MiddleType = 0;
2208       switch (Size) {
2209         default: break;
2210         case 32: MiddleType = Type::getInt32Ty(*Context); break;
2211         case 16: MiddleType = Type::getInt16Ty(*Context); break;
2212         case  8: MiddleType = Type::getInt8Ty(*Context); break;
2213       }
2214       if (MiddleType) {
2215         Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
2216         return new SExtInst(NewTrunc, I.getType(), I.getName());
2217       }
2218     }
2219   }
2220
2221   if (I.getType() == Type::getInt1Ty(*Context))
2222     return BinaryOperator::CreateXor(LHS, RHS);
2223
2224   // X + X --> X << 1
2225   if (I.getType()->isInteger()) {
2226     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2227       return Result;
2228
2229     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2230       if (RHSI->getOpcode() == Instruction::Sub)
2231         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2232           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2233     }
2234     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2235       if (LHSI->getOpcode() == Instruction::Sub)
2236         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2237           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2238     }
2239   }
2240
2241   // -A + B  -->  B - A
2242   // -A + -B  -->  -(A + B)
2243   if (Value *LHSV = dyn_castNegVal(LHS)) {
2244     if (LHS->getType()->isIntOrIntVector()) {
2245       if (Value *RHSV = dyn_castNegVal(RHS)) {
2246         Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
2247         return BinaryOperator::CreateNeg(NewAdd);
2248       }
2249     }
2250     
2251     return BinaryOperator::CreateSub(RHS, LHSV);
2252   }
2253
2254   // A + -B  -->  A - B
2255   if (!isa<Constant>(RHS))
2256     if (Value *V = dyn_castNegVal(RHS))
2257       return BinaryOperator::CreateSub(LHS, V);
2258
2259
2260   ConstantInt *C2;
2261   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2262     if (X == RHS)   // X*C + X --> X * (C+1)
2263       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2264
2265     // X*C1 + X*C2 --> X * (C1+C2)
2266     ConstantInt *C1;
2267     if (X == dyn_castFoldableMul(RHS, C1))
2268       return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2269   }
2270
2271   // X + X*C --> X * (C+1)
2272   if (dyn_castFoldableMul(RHS, C2) == LHS)
2273     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2274
2275   // X + ~X --> -1   since   ~X = -X-1
2276   if (dyn_castNotVal(LHS) == RHS ||
2277       dyn_castNotVal(RHS) == LHS)
2278     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2279   
2280
2281   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2282   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2283     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2284       return R;
2285   
2286   // A+B --> A|B iff A and B have no bits set in common.
2287   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2288     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2289     APInt LHSKnownOne(IT->getBitWidth(), 0);
2290     APInt LHSKnownZero(IT->getBitWidth(), 0);
2291     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2292     if (LHSKnownZero != 0) {
2293       APInt RHSKnownOne(IT->getBitWidth(), 0);
2294       APInt RHSKnownZero(IT->getBitWidth(), 0);
2295       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2296       
2297       // No bits in common -> bitwise or.
2298       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2299         return BinaryOperator::CreateOr(LHS, RHS);
2300     }
2301   }
2302
2303   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2304   if (I.getType()->isIntOrIntVector()) {
2305     Value *W, *X, *Y, *Z;
2306     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2307         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2308       if (W != Y) {
2309         if (W == Z) {
2310           std::swap(Y, Z);
2311         } else if (Y == X) {
2312           std::swap(W, X);
2313         } else if (X == Z) {
2314           std::swap(Y, Z);
2315           std::swap(W, X);
2316         }
2317       }
2318
2319       if (W == Y) {
2320         Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
2321         return BinaryOperator::CreateMul(W, NewAdd);
2322       }
2323     }
2324   }
2325
2326   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2327     Value *X = 0;
2328     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2329       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2330
2331     // (X & FF00) + xx00  -> (X+xx00) & FF00
2332     if (LHS->hasOneUse() &&
2333         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2334       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2335       if (Anded == CRHS) {
2336         // See if all bits from the first bit set in the Add RHS up are included
2337         // in the mask.  First, get the rightmost bit.
2338         const APInt& AddRHSV = CRHS->getValue();
2339
2340         // Form a mask of all bits from the lowest bit added through the top.
2341         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2342
2343         // See if the and mask includes all of these bits.
2344         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2345
2346         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2347           // Okay, the xform is safe.  Insert the new add pronto.
2348           Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
2349           return BinaryOperator::CreateAnd(NewAdd, C2);
2350         }
2351       }
2352     }
2353
2354     // Try to fold constant add into select arguments.
2355     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2356       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2357         return R;
2358   }
2359
2360   // add (select X 0 (sub n A)) A  -->  select X A n
2361   {
2362     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2363     Value *A = RHS;
2364     if (!SI) {
2365       SI = dyn_cast<SelectInst>(RHS);
2366       A = LHS;
2367     }
2368     if (SI && SI->hasOneUse()) {
2369       Value *TV = SI->getTrueValue();
2370       Value *FV = SI->getFalseValue();
2371       Value *N;
2372
2373       // Can we fold the add into the argument of the select?
2374       // We check both true and false select arguments for a matching subtract.
2375       if (match(FV, m_Zero()) &&
2376           match(TV, m_Sub(m_Value(N), m_Specific(A))))
2377         // Fold the add into the true select value.
2378         return SelectInst::Create(SI->getCondition(), N, A);
2379       if (match(TV, m_Zero()) &&
2380           match(FV, m_Sub(m_Value(N), m_Specific(A))))
2381         // Fold the add into the false select value.
2382         return SelectInst::Create(SI->getCondition(), A, N);
2383     }
2384   }
2385
2386   // Check for (add (sext x), y), see if we can merge this into an
2387   // integer add followed by a sext.
2388   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2389     // (add (sext x), cst) --> (sext (add x, cst'))
2390     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2391       Constant *CI = 
2392         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2393       if (LHSConv->hasOneUse() &&
2394           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2395           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2396         // Insert the new, smaller add.
2397         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0), 
2398                                            CI, "addconv");
2399         return new SExtInst(NewAdd, I.getType());
2400       }
2401     }
2402     
2403     // (add (sext x), (sext y)) --> (sext (add int x, y))
2404     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2405       // Only do this if x/y have the same type, if at last one of them has a
2406       // single use (so we don't increase the number of sexts), and if the
2407       // integer add will not overflow.
2408       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2409           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2410           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2411                                    RHSConv->getOperand(0))) {
2412         // Insert the new integer add.
2413         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0), 
2414                                            RHSConv->getOperand(0), "addconv");
2415         return new SExtInst(NewAdd, I.getType());
2416       }
2417     }
2418   }
2419
2420   return Changed ? &I : 0;
2421 }
2422
2423 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2424   bool Changed = SimplifyCommutative(I);
2425   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2426
2427   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2428     // X + 0 --> X
2429     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2430       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2431                               (I.getType())->getValueAPF()))
2432         return ReplaceInstUsesWith(I, LHS);
2433     }
2434
2435     if (isa<PHINode>(LHS))
2436       if (Instruction *NV = FoldOpIntoPhi(I))
2437         return NV;
2438   }
2439
2440   // -A + B  -->  B - A
2441   // -A + -B  -->  -(A + B)
2442   if (Value *LHSV = dyn_castFNegVal(LHS))
2443     return BinaryOperator::CreateFSub(RHS, LHSV);
2444
2445   // A + -B  -->  A - B
2446   if (!isa<Constant>(RHS))
2447     if (Value *V = dyn_castFNegVal(RHS))
2448       return BinaryOperator::CreateFSub(LHS, V);
2449
2450   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2451   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2452     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2453       return ReplaceInstUsesWith(I, LHS);
2454
2455   // Check for (add double (sitofp x), y), see if we can merge this into an
2456   // integer add followed by a promotion.
2457   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2458     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2459     // ... if the constant fits in the integer value.  This is useful for things
2460     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2461     // requires a constant pool load, and generally allows the add to be better
2462     // instcombined.
2463     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2464       Constant *CI = 
2465       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2466       if (LHSConv->hasOneUse() &&
2467           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2468           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2469         // Insert the new integer add.
2470         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2471                                            CI, "addconv");
2472         return new SIToFPInst(NewAdd, I.getType());
2473       }
2474     }
2475     
2476     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2477     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2478       // Only do this if x/y have the same type, if at last one of them has a
2479       // single use (so we don't increase the number of int->fp conversions),
2480       // and if the integer add will not overflow.
2481       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2482           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2483           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2484                                    RHSConv->getOperand(0))) {
2485         // Insert the new integer add.
2486         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0), 
2487                                            RHSConv->getOperand(0), "addconv");
2488         return new SIToFPInst(NewAdd, I.getType());
2489       }
2490     }
2491   }
2492   
2493   return Changed ? &I : 0;
2494 }
2495
2496 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2497   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2498
2499   if (Op0 == Op1)                        // sub X, X  -> 0
2500     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2501
2502   // If this is a 'B = x-(-A)', change to B = x+A...
2503   if (Value *V = dyn_castNegVal(Op1))
2504     return BinaryOperator::CreateAdd(Op0, V);
2505
2506   if (isa<UndefValue>(Op0))
2507     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2508   if (isa<UndefValue>(Op1))
2509     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2510
2511   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2512     // Replace (-1 - A) with (~A)...
2513     if (C->isAllOnesValue())
2514       return BinaryOperator::CreateNot(Op1);
2515
2516     // C - ~X == X + (1+C)
2517     Value *X = 0;
2518     if (match(Op1, m_Not(m_Value(X))))
2519       return BinaryOperator::CreateAdd(X, AddOne(C));
2520
2521     // -(X >>u 31) -> (X >>s 31)
2522     // -(X >>s 31) -> (X >>u 31)
2523     if (C->isZero()) {
2524       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2525         if (SI->getOpcode() == Instruction::LShr) {
2526           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2527             // Check to see if we are shifting out everything but the sign bit.
2528             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2529                 SI->getType()->getPrimitiveSizeInBits()-1) {
2530               // Ok, the transformation is safe.  Insert AShr.
2531               return BinaryOperator::Create(Instruction::AShr, 
2532                                           SI->getOperand(0), CU, SI->getName());
2533             }
2534           }
2535         }
2536         else if (SI->getOpcode() == Instruction::AShr) {
2537           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2538             // Check to see if we are shifting out everything but the sign bit.
2539             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2540                 SI->getType()->getPrimitiveSizeInBits()-1) {
2541               // Ok, the transformation is safe.  Insert LShr. 
2542               return BinaryOperator::CreateLShr(
2543                                           SI->getOperand(0), CU, SI->getName());
2544             }
2545           }
2546         }
2547       }
2548     }
2549
2550     // Try to fold constant sub into select arguments.
2551     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2552       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2553         return R;
2554
2555     // C - zext(bool) -> bool ? C - 1 : C
2556     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2557       if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2558         return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2559   }
2560
2561   if (I.getType() == Type::getInt1Ty(*Context))
2562     return BinaryOperator::CreateXor(Op0, Op1);
2563
2564   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2565     if (Op1I->getOpcode() == Instruction::Add) {
2566       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2567         return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2568                                          I.getName());
2569       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2570         return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2571                                          I.getName());
2572       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2573         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2574           // C1-(X+C2) --> (C1-C2)-X
2575           return BinaryOperator::CreateSub(
2576             ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2577       }
2578     }
2579
2580     if (Op1I->hasOneUse()) {
2581       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2582       // is not used by anyone else...
2583       //
2584       if (Op1I->getOpcode() == Instruction::Sub) {
2585         // Swap the two operands of the subexpr...
2586         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2587         Op1I->setOperand(0, IIOp1);
2588         Op1I->setOperand(1, IIOp0);
2589
2590         // Create the new top level add instruction...
2591         return BinaryOperator::CreateAdd(Op0, Op1);
2592       }
2593
2594       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2595       //
2596       if (Op1I->getOpcode() == Instruction::And &&
2597           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2598         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2599
2600         Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
2601         return BinaryOperator::CreateAnd(Op0, NewNot);
2602       }
2603
2604       // 0 - (X sdiv C)  -> (X sdiv -C)
2605       if (Op1I->getOpcode() == Instruction::SDiv)
2606         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2607           if (CSI->isZero())
2608             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2609               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2610                                           ConstantExpr::getNeg(DivRHS));
2611
2612       // X - X*C --> X * (1-C)
2613       ConstantInt *C2 = 0;
2614       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2615         Constant *CP1 = 
2616           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2617                                              C2);
2618         return BinaryOperator::CreateMul(Op0, CP1);
2619       }
2620     }
2621   }
2622
2623   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2624     if (Op0I->getOpcode() == Instruction::Add) {
2625       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2626         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2627       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2628         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2629     } else if (Op0I->getOpcode() == Instruction::Sub) {
2630       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2631         return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2632                                          I.getName());
2633     }
2634   }
2635
2636   ConstantInt *C1;
2637   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2638     if (X == Op1)  // X*C - X --> X * (C-1)
2639       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2640
2641     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2642     if (X == dyn_castFoldableMul(Op1, C2))
2643       return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2644   }
2645   return 0;
2646 }
2647
2648 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2649   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2650
2651   // If this is a 'B = x-(-A)', change to B = x+A...
2652   if (Value *V = dyn_castFNegVal(Op1))
2653     return BinaryOperator::CreateFAdd(Op0, V);
2654
2655   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2656     if (Op1I->getOpcode() == Instruction::FAdd) {
2657       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2658         return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
2659                                           I.getName());
2660       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2661         return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
2662                                           I.getName());
2663     }
2664   }
2665
2666   return 0;
2667 }
2668
2669 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2670 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2671 /// TrueIfSigned if the result of the comparison is true when the input value is
2672 /// signed.
2673 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2674                            bool &TrueIfSigned) {
2675   switch (pred) {
2676   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2677     TrueIfSigned = true;
2678     return RHS->isZero();
2679   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2680     TrueIfSigned = true;
2681     return RHS->isAllOnesValue();
2682   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2683     TrueIfSigned = false;
2684     return RHS->isAllOnesValue();
2685   case ICmpInst::ICMP_UGT:
2686     // True if LHS u> RHS and RHS == high-bit-mask - 1
2687     TrueIfSigned = true;
2688     return RHS->getValue() ==
2689       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2690   case ICmpInst::ICMP_UGE: 
2691     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2692     TrueIfSigned = true;
2693     return RHS->getValue().isSignBit();
2694   default:
2695     return false;
2696   }
2697 }
2698
2699 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2700   bool Changed = SimplifyCommutative(I);
2701   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2702
2703   if (isa<UndefValue>(Op1))              // undef * X -> 0
2704     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2705
2706   // Simplify mul instructions with a constant RHS.
2707   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2708     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
2709
2710       // ((X << C1)*C2) == (X * (C2 << C1))
2711       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2712         if (SI->getOpcode() == Instruction::Shl)
2713           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2714             return BinaryOperator::CreateMul(SI->getOperand(0),
2715                                         ConstantExpr::getShl(CI, ShOp));
2716
2717       if (CI->isZero())
2718         return ReplaceInstUsesWith(I, Op1C);  // X * 0  == 0
2719       if (CI->equalsInt(1))                  // X * 1  == X
2720         return ReplaceInstUsesWith(I, Op0);
2721       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2722         return BinaryOperator::CreateNeg(Op0, I.getName());
2723
2724       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2725       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2726         return BinaryOperator::CreateShl(Op0,
2727                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2728       }
2729     } else if (isa<VectorType>(Op1C->getType())) {
2730       if (Op1C->isNullValue())
2731         return ReplaceInstUsesWith(I, Op1C);
2732
2733       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
2734         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2735           return BinaryOperator::CreateNeg(Op0, I.getName());
2736
2737         // As above, vector X*splat(1.0) -> X in all defined cases.
2738         if (Constant *Splat = Op1V->getSplatValue()) {
2739           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2740             if (CI->equalsInt(1))
2741               return ReplaceInstUsesWith(I, Op0);
2742         }
2743       }
2744     }
2745     
2746     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2747       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2748           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
2749         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2750         Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
2751         Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
2752         return BinaryOperator::CreateAdd(Add, C1C2);
2753         
2754       }
2755
2756     // Try to fold constant mul into select arguments.
2757     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2758       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2759         return R;
2760
2761     if (isa<PHINode>(Op0))
2762       if (Instruction *NV = FoldOpIntoPhi(I))
2763         return NV;
2764   }
2765
2766   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2767     if (Value *Op1v = dyn_castNegVal(Op1))
2768       return BinaryOperator::CreateMul(Op0v, Op1v);
2769
2770   // (X / Y) *  Y = X - (X % Y)
2771   // (X / Y) * -Y = (X % Y) - X
2772   {
2773     Value *Op1C = Op1;
2774     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2775     if (!BO ||
2776         (BO->getOpcode() != Instruction::UDiv && 
2777          BO->getOpcode() != Instruction::SDiv)) {
2778       Op1C = Op0;
2779       BO = dyn_cast<BinaryOperator>(Op1);
2780     }
2781     Value *Neg = dyn_castNegVal(Op1C);
2782     if (BO && BO->hasOneUse() &&
2783         (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
2784         (BO->getOpcode() == Instruction::UDiv ||
2785          BO->getOpcode() == Instruction::SDiv)) {
2786       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2787
2788       // If the division is exact, X % Y is zero.
2789       if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2790         if (SDiv->isExact()) {
2791           if (Op1BO == Op1C)
2792             return ReplaceInstUsesWith(I, Op0BO);
2793           return BinaryOperator::CreateNeg(Op0BO);
2794         }
2795
2796       Value *Rem;
2797       if (BO->getOpcode() == Instruction::UDiv)
2798         Rem = Builder->CreateURem(Op0BO, Op1BO);
2799       else
2800         Rem = Builder->CreateSRem(Op0BO, Op1BO);
2801       Rem->takeName(BO);
2802
2803       if (Op1BO == Op1C)
2804         return BinaryOperator::CreateSub(Op0BO, Rem);
2805       return BinaryOperator::CreateSub(Rem, Op0BO);
2806     }
2807   }
2808
2809   /// i1 mul -> i1 and.
2810   if (I.getType() == Type::getInt1Ty(*Context))
2811     return BinaryOperator::CreateAnd(Op0, Op1);
2812
2813   // X*(1 << Y) --> X << Y
2814   // (1 << Y)*X --> X << Y
2815   {
2816     Value *Y;
2817     if (match(Op0, m_Shl(m_One(), m_Value(Y))))
2818       return BinaryOperator::CreateShl(Op1, Y);
2819     if (match(Op1, m_Shl(m_One(), m_Value(Y))))
2820       return BinaryOperator::CreateShl(Op0, Y);
2821   }
2822   
2823   // If one of the operands of the multiply is a cast from a boolean value, then
2824   // we know the bool is either zero or one, so this is a 'masking' multiply.
2825   //   X * Y (where Y is 0 or 1) -> X & (0-Y)
2826   if (!isa<VectorType>(I.getType())) {
2827     // -2 is "-1 << 1" so it is all bits set except the low one.
2828     APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
2829     
2830     Value *BoolCast = 0, *OtherOp = 0;
2831     if (MaskedValueIsZero(Op0, Negative2))
2832       BoolCast = Op0, OtherOp = Op1;
2833     else if (MaskedValueIsZero(Op1, Negative2))
2834       BoolCast = Op1, OtherOp = Op0;
2835
2836     if (BoolCast) {
2837       Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
2838                                     BoolCast, "tmp");
2839       return BinaryOperator::CreateAnd(V, OtherOp);
2840     }
2841   }
2842
2843   return Changed ? &I : 0;
2844 }
2845
2846 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2847   bool Changed = SimplifyCommutative(I);
2848   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2849
2850   // Simplify mul instructions with a constant RHS...
2851   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2852     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
2853       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2854       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2855       if (Op1F->isExactlyValue(1.0))
2856         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2857     } else if (isa<VectorType>(Op1C->getType())) {
2858       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
2859         // As above, vector X*splat(1.0) -> X in all defined cases.
2860         if (Constant *Splat = Op1V->getSplatValue()) {
2861           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2862             if (F->isExactlyValue(1.0))
2863               return ReplaceInstUsesWith(I, Op0);
2864         }
2865       }
2866     }
2867
2868     // Try to fold constant mul into select arguments.
2869     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2870       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2871         return R;
2872
2873     if (isa<PHINode>(Op0))
2874       if (Instruction *NV = FoldOpIntoPhi(I))
2875         return NV;
2876   }
2877
2878   if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
2879     if (Value *Op1v = dyn_castFNegVal(Op1))
2880       return BinaryOperator::CreateFMul(Op0v, Op1v);
2881
2882   return Changed ? &I : 0;
2883 }
2884
2885 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2886 /// instruction.
2887 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2888   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2889   
2890   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2891   int NonNullOperand = -1;
2892   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2893     if (ST->isNullValue())
2894       NonNullOperand = 2;
2895   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2896   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2897     if (ST->isNullValue())
2898       NonNullOperand = 1;
2899   
2900   if (NonNullOperand == -1)
2901     return false;
2902   
2903   Value *SelectCond = SI->getOperand(0);
2904   
2905   // Change the div/rem to use 'Y' instead of the select.
2906   I.setOperand(1, SI->getOperand(NonNullOperand));
2907   
2908   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2909   // problem.  However, the select, or the condition of the select may have
2910   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2911   // propagate the known value for the select into other uses of it, and
2912   // propagate a known value of the condition into its other users.
2913   
2914   // If the select and condition only have a single use, don't bother with this,
2915   // early exit.
2916   if (SI->use_empty() && SelectCond->hasOneUse())
2917     return true;
2918   
2919   // Scan the current block backward, looking for other uses of SI.
2920   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2921   
2922   while (BBI != BBFront) {
2923     --BBI;
2924     // If we found a call to a function, we can't assume it will return, so
2925     // information from below it cannot be propagated above it.
2926     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2927       break;
2928     
2929     // Replace uses of the select or its condition with the known values.
2930     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2931          I != E; ++I) {
2932       if (*I == SI) {
2933         *I = SI->getOperand(NonNullOperand);
2934         Worklist.Add(BBI);
2935       } else if (*I == SelectCond) {
2936         *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2937                                    ConstantInt::getFalse(*Context);
2938         Worklist.Add(BBI);
2939       }
2940     }
2941     
2942     // If we past the instruction, quit looking for it.
2943     if (&*BBI == SI)
2944       SI = 0;
2945     if (&*BBI == SelectCond)
2946       SelectCond = 0;
2947     
2948     // If we ran out of things to eliminate, break out of the loop.
2949     if (SelectCond == 0 && SI == 0)
2950       break;
2951     
2952   }
2953   return true;
2954 }
2955
2956
2957 /// This function implements the transforms on div instructions that work
2958 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2959 /// used by the visitors to those instructions.
2960 /// @brief Transforms common to all three div instructions
2961 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2962   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2963
2964   // undef / X -> 0        for integer.
2965   // undef / X -> undef    for FP (the undef could be a snan).
2966   if (isa<UndefValue>(Op0)) {
2967     if (Op0->getType()->isFPOrFPVector())
2968       return ReplaceInstUsesWith(I, Op0);
2969     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2970   }
2971
2972   // X / undef -> undef
2973   if (isa<UndefValue>(Op1))
2974     return ReplaceInstUsesWith(I, Op1);
2975
2976   return 0;
2977 }
2978
2979 /// This function implements the transforms common to both integer division
2980 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2981 /// division instructions.
2982 /// @brief Common integer divide transforms
2983 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2984   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2985
2986   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2987   if (Op0 == Op1) {
2988     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2989       Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
2990       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2991       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2992     }
2993
2994     Constant *CI = ConstantInt::get(I.getType(), 1);
2995     return ReplaceInstUsesWith(I, CI);
2996   }
2997   
2998   if (Instruction *Common = commonDivTransforms(I))
2999     return Common;
3000   
3001   // Handle cases involving: [su]div X, (select Cond, Y, Z)
3002   // This does not apply for fdiv.
3003   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3004     return &I;
3005
3006   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3007     // div X, 1 == X
3008     if (RHS->equalsInt(1))
3009       return ReplaceInstUsesWith(I, Op0);
3010
3011     // (X / C1) / C2  -> X / (C1*C2)
3012     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3013       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3014         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3015           if (MultiplyOverflows(RHS, LHSRHS,
3016                                 I.getOpcode()==Instruction::SDiv))
3017             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3018           else 
3019             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
3020                                       ConstantExpr::getMul(RHS, LHSRHS));
3021         }
3022
3023     if (!RHS->isZero()) { // avoid X udiv 0
3024       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3025         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3026           return R;
3027       if (isa<PHINode>(Op0))
3028         if (Instruction *NV = FoldOpIntoPhi(I))
3029           return NV;
3030     }
3031   }
3032
3033   // 0 / X == 0, we don't need to preserve faults!
3034   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3035     if (LHS->equalsInt(0))
3036       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3037
3038   // It can't be division by zero, hence it must be division by one.
3039   if (I.getType() == Type::getInt1Ty(*Context))
3040     return ReplaceInstUsesWith(I, Op0);
3041
3042   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3043     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3044       // div X, 1 == X
3045       if (X->isOne())
3046         return ReplaceInstUsesWith(I, Op0);
3047   }
3048
3049   return 0;
3050 }
3051
3052 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3053   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3054
3055   // Handle the integer div common cases
3056   if (Instruction *Common = commonIDivTransforms(I))
3057     return Common;
3058
3059   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3060     // X udiv C^2 -> X >> C
3061     // Check to see if this is an unsigned division with an exact power of 2,
3062     // if so, convert to a right shift.
3063     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3064       return BinaryOperator::CreateLShr(Op0, 
3065             ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3066
3067     // X udiv C, where C >= signbit
3068     if (C->getValue().isNegative()) {
3069       Value *IC = Builder->CreateICmpULT( Op0, C);
3070       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3071                                 ConstantInt::get(I.getType(), 1));
3072     }
3073   }
3074
3075   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3076   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3077     if (RHSI->getOpcode() == Instruction::Shl &&
3078         isa<ConstantInt>(RHSI->getOperand(0))) {
3079       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3080       if (C1.isPowerOf2()) {
3081         Value *N = RHSI->getOperand(1);
3082         const Type *NTy = N->getType();
3083         if (uint32_t C2 = C1.logBase2())
3084           N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
3085         return BinaryOperator::CreateLShr(Op0, N);
3086       }
3087     }
3088   }
3089   
3090   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3091   // where C1&C2 are powers of two.
3092   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3093     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3094       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3095         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3096         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3097           // Compute the shift amounts
3098           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3099           // Construct the "on true" case of the select
3100           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3101           Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
3102   
3103           // Construct the "on false" case of the select
3104           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3105           Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
3106
3107           // construct the select instruction and return it.
3108           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3109         }
3110       }
3111   return 0;
3112 }
3113
3114 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3115   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3116
3117   // Handle the integer div common cases
3118   if (Instruction *Common = commonIDivTransforms(I))
3119     return Common;
3120
3121   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3122     // sdiv X, -1 == -X
3123     if (RHS->isAllOnesValue())
3124       return BinaryOperator::CreateNeg(Op0);
3125
3126     // sdiv X, C  -->  ashr X, log2(C)
3127     if (cast<SDivOperator>(&I)->isExact() &&
3128         RHS->getValue().isNonNegative() &&
3129         RHS->getValue().isPowerOf2()) {
3130       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3131                                             RHS->getValue().exactLogBase2());
3132       return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3133     }
3134
3135     // -X/C  -->  X/-C  provided the negation doesn't overflow.
3136     if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3137       if (isa<Constant>(Sub->getOperand(0)) &&
3138           cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3139           Sub->hasNoSignedWrap())
3140         return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3141                                           ConstantExpr::getNeg(RHS));
3142   }
3143
3144   // If the sign bits of both operands are zero (i.e. we can prove they are
3145   // unsigned inputs), turn this into a udiv.
3146   if (I.getType()->isInteger()) {
3147     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3148     if (MaskedValueIsZero(Op0, Mask)) {
3149       if (MaskedValueIsZero(Op1, Mask)) {
3150         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3151         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3152       }
3153       ConstantInt *ShiftedInt;
3154       if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3155           ShiftedInt->getValue().isPowerOf2()) {
3156         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3157         // Safe because the only negative value (1 << Y) can take on is
3158         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3159         // the sign bit set.
3160         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3161       }
3162     }
3163   }
3164   
3165   return 0;
3166 }
3167
3168 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3169   return commonDivTransforms(I);
3170 }
3171
3172 /// This function implements the transforms on rem instructions that work
3173 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3174 /// is used by the visitors to those instructions.
3175 /// @brief Transforms common to all three rem instructions
3176 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3177   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3178
3179   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3180     if (I.getType()->isFPOrFPVector())
3181       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3182     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3183   }
3184   if (isa<UndefValue>(Op1))
3185     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3186
3187   // Handle cases involving: rem X, (select Cond, Y, Z)
3188   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3189     return &I;
3190
3191   return 0;
3192 }
3193
3194 /// This function implements the transforms common to both integer remainder
3195 /// instructions (urem and srem). It is called by the visitors to those integer
3196 /// remainder instructions.
3197 /// @brief Common integer remainder transforms
3198 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3199   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3200
3201   if (Instruction *common = commonRemTransforms(I))
3202     return common;
3203
3204   // 0 % X == 0 for integer, we don't need to preserve faults!
3205   if (Constant *LHS = dyn_cast<Constant>(Op0))
3206     if (LHS->isNullValue())
3207       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3208
3209   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3210     // X % 0 == undef, we don't need to preserve faults!
3211     if (RHS->equalsInt(0))
3212       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3213     
3214     if (RHS->equalsInt(1))  // X % 1 == 0
3215       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3216
3217     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3218       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3219         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3220           return R;
3221       } else if (isa<PHINode>(Op0I)) {
3222         if (Instruction *NV = FoldOpIntoPhi(I))
3223           return NV;
3224       }
3225
3226       // See if we can fold away this rem instruction.
3227       if (SimplifyDemandedInstructionBits(I))
3228         return &I;
3229     }
3230   }
3231
3232   return 0;
3233 }
3234
3235 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3236   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3237
3238   if (Instruction *common = commonIRemTransforms(I))
3239     return common;
3240   
3241   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3242     // X urem C^2 -> X and C
3243     // Check to see if this is an unsigned remainder with an exact power of 2,
3244     // if so, convert to a bitwise and.
3245     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3246       if (C->getValue().isPowerOf2())
3247         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3248   }
3249
3250   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3251     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3252     if (RHSI->getOpcode() == Instruction::Shl &&
3253         isa<ConstantInt>(RHSI->getOperand(0))) {
3254       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3255         Constant *N1 = Constant::getAllOnesValue(I.getType());
3256         Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
3257         return BinaryOperator::CreateAnd(Op0, Add);
3258       }
3259     }
3260   }
3261
3262   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3263   // where C1&C2 are powers of two.
3264   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3265     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3266       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3267         // STO == 0 and SFO == 0 handled above.
3268         if ((STO->getValue().isPowerOf2()) && 
3269             (SFO->getValue().isPowerOf2())) {
3270           Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3271                                               SI->getName()+".t");
3272           Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3273                                                SI->getName()+".f");
3274           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3275         }
3276       }
3277   }
3278   
3279   return 0;
3280 }
3281
3282 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3283   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3284
3285   // Handle the integer rem common cases
3286   if (Instruction *Common = commonIRemTransforms(I))
3287     return Common;
3288   
3289   if (Value *RHSNeg = dyn_castNegVal(Op1))
3290     if (!isa<Constant>(RHSNeg) ||
3291         (isa<ConstantInt>(RHSNeg) &&
3292          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3293       // X % -Y -> X % Y
3294       Worklist.AddValue(I.getOperand(1));
3295       I.setOperand(1, RHSNeg);
3296       return &I;
3297     }
3298
3299   // If the sign bits of both operands are zero (i.e. we can prove they are
3300   // unsigned inputs), turn this into a urem.
3301   if (I.getType()->isInteger()) {
3302     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3303     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3304       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3305       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3306     }
3307   }
3308
3309   // If it's a constant vector, flip any negative values positive.
3310   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3311     unsigned VWidth = RHSV->getNumOperands();
3312
3313     bool hasNegative = false;
3314     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3315       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3316         if (RHS->getValue().isNegative())
3317           hasNegative = true;
3318
3319     if (hasNegative) {
3320       std::vector<Constant *> Elts(VWidth);
3321       for (unsigned i = 0; i != VWidth; ++i) {
3322         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3323           if (RHS->getValue().isNegative())
3324             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3325           else
3326             Elts[i] = RHS;
3327         }
3328       }
3329
3330       Constant *NewRHSV = ConstantVector::get(Elts);
3331       if (NewRHSV != RHSV) {
3332         Worklist.AddValue(I.getOperand(1));
3333         I.setOperand(1, NewRHSV);
3334         return &I;
3335       }
3336     }
3337   }
3338
3339   return 0;
3340 }
3341
3342 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3343   return commonRemTransforms(I);
3344 }
3345
3346 // isOneBitSet - Return true if there is exactly one bit set in the specified
3347 // constant.
3348 static bool isOneBitSet(const ConstantInt *CI) {
3349   return CI->getValue().isPowerOf2();
3350 }
3351
3352 // isHighOnes - Return true if the constant is of the form 1+0+.
3353 // This is the same as lowones(~X).
3354 static bool isHighOnes(const ConstantInt *CI) {
3355   return (~CI->getValue() + 1).isPowerOf2();
3356 }
3357
3358 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3359 /// are carefully arranged to allow folding of expressions such as:
3360 ///
3361 ///      (A < B) | (A > B) --> (A != B)
3362 ///
3363 /// Note that this is only valid if the first and second predicates have the
3364 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3365 ///
3366 /// Three bits are used to represent the condition, as follows:
3367 ///   0  A > B
3368 ///   1  A == B
3369 ///   2  A < B
3370 ///
3371 /// <=>  Value  Definition
3372 /// 000     0   Always false
3373 /// 001     1   A >  B
3374 /// 010     2   A == B
3375 /// 011     3   A >= B
3376 /// 100     4   A <  B
3377 /// 101     5   A != B
3378 /// 110     6   A <= B
3379 /// 111     7   Always true
3380 ///  
3381 static unsigned getICmpCode(const ICmpInst *ICI) {
3382   switch (ICI->getPredicate()) {
3383     // False -> 0
3384   case ICmpInst::ICMP_UGT: return 1;  // 001
3385   case ICmpInst::ICMP_SGT: return 1;  // 001
3386   case ICmpInst::ICMP_EQ:  return 2;  // 010
3387   case ICmpInst::ICMP_UGE: return 3;  // 011
3388   case ICmpInst::ICMP_SGE: return 3;  // 011
3389   case ICmpInst::ICMP_ULT: return 4;  // 100
3390   case ICmpInst::ICMP_SLT: return 4;  // 100
3391   case ICmpInst::ICMP_NE:  return 5;  // 101
3392   case ICmpInst::ICMP_ULE: return 6;  // 110
3393   case ICmpInst::ICMP_SLE: return 6;  // 110
3394     // True -> 7
3395   default:
3396     llvm_unreachable("Invalid ICmp predicate!");
3397     return 0;
3398   }
3399 }
3400
3401 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3402 /// predicate into a three bit mask. It also returns whether it is an ordered
3403 /// predicate by reference.
3404 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3405   isOrdered = false;
3406   switch (CC) {
3407   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3408   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3409   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3410   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3411   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3412   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3413   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3414   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3415   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3416   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3417   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3418   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3419   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3420   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3421     // True -> 7
3422   default:
3423     // Not expecting FCMP_FALSE and FCMP_TRUE;
3424     llvm_unreachable("Unexpected FCmp predicate!");
3425     return 0;
3426   }
3427 }
3428
3429 /// getICmpValue - This is the complement of getICmpCode, which turns an
3430 /// opcode and two operands into either a constant true or false, or a brand 
3431 /// new ICmp instruction. The sign is passed in to determine which kind
3432 /// of predicate to use in the new icmp instruction.
3433 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3434                            LLVMContext *Context) {
3435   switch (code) {
3436   default: llvm_unreachable("Illegal ICmp code!");
3437   case  0: return ConstantInt::getFalse(*Context);
3438   case  1: 
3439     if (sign)
3440       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3441     else
3442       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3443   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3444   case  3: 
3445     if (sign)
3446       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3447     else
3448       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3449   case  4: 
3450     if (sign)
3451       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3452     else
3453       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3454   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3455   case  6: 
3456     if (sign)
3457       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3458     else
3459       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3460   case  7: return ConstantInt::getTrue(*Context);
3461   }
3462 }
3463
3464 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3465 /// opcode and two operands into either a FCmp instruction. isordered is passed
3466 /// in to determine which kind of predicate to use in the new fcmp instruction.
3467 static Value *getFCmpValue(bool isordered, unsigned code,
3468                            Value *LHS, Value *RHS, LLVMContext *Context) {
3469   switch (code) {
3470   default: llvm_unreachable("Illegal FCmp code!");
3471   case  0:
3472     if (isordered)
3473       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3474     else
3475       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3476   case  1: 
3477     if (isordered)
3478       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3479     else
3480       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3481   case  2: 
3482     if (isordered)
3483       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3484     else
3485       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3486   case  3: 
3487     if (isordered)
3488       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3489     else
3490       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3491   case  4: 
3492     if (isordered)
3493       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3494     else
3495       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3496   case  5: 
3497     if (isordered)
3498       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3499     else
3500       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3501   case  6: 
3502     if (isordered)
3503       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3504     else
3505       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3506   case  7: return ConstantInt::getTrue(*Context);
3507   }
3508 }
3509
3510 /// PredicatesFoldable - Return true if both predicates match sign or if at
3511 /// least one of them is an equality comparison (which is signless).
3512 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3513   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3514          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3515          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3516 }
3517
3518 namespace { 
3519 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3520 struct FoldICmpLogical {
3521   InstCombiner &IC;
3522   Value *LHS, *RHS;
3523   ICmpInst::Predicate pred;
3524   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3525     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3526       pred(ICI->getPredicate()) {}
3527   bool shouldApply(Value *V) const {
3528     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3529       if (PredicatesFoldable(pred, ICI->getPredicate()))
3530         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3531                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3532     return false;
3533   }
3534   Instruction *apply(Instruction &Log) const {
3535     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3536     if (ICI->getOperand(0) != LHS) {
3537       assert(ICI->getOperand(1) == LHS);
3538       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3539     }
3540
3541     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3542     unsigned LHSCode = getICmpCode(ICI);
3543     unsigned RHSCode = getICmpCode(RHSICI);
3544     unsigned Code;
3545     switch (Log.getOpcode()) {
3546     case Instruction::And: Code = LHSCode & RHSCode; break;
3547     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3548     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3549     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3550     }
3551
3552     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3553                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3554       
3555     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3556     if (Instruction *I = dyn_cast<Instruction>(RV))
3557       return I;
3558     // Otherwise, it's a constant boolean value...
3559     return IC.ReplaceInstUsesWith(Log, RV);
3560   }
3561 };
3562 } // end anonymous namespace
3563
3564 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3565 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3566 // guaranteed to be a binary operator.
3567 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3568                                     ConstantInt *OpRHS,
3569                                     ConstantInt *AndRHS,
3570                                     BinaryOperator &TheAnd) {
3571   Value *X = Op->getOperand(0);
3572   Constant *Together = 0;
3573   if (!Op->isShift())
3574     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3575
3576   switch (Op->getOpcode()) {
3577   case Instruction::Xor:
3578     if (Op->hasOneUse()) {
3579       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3580       Value *And = Builder->CreateAnd(X, AndRHS);
3581       And->takeName(Op);
3582       return BinaryOperator::CreateXor(And, Together);
3583     }
3584     break;
3585   case Instruction::Or:
3586     if (Together == AndRHS) // (X | C) & C --> C
3587       return ReplaceInstUsesWith(TheAnd, AndRHS);
3588
3589     if (Op->hasOneUse() && Together != OpRHS) {
3590       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3591       Value *Or = Builder->CreateOr(X, Together);
3592       Or->takeName(Op);
3593       return BinaryOperator::CreateAnd(Or, AndRHS);
3594     }
3595     break;
3596   case Instruction::Add:
3597     if (Op->hasOneUse()) {
3598       // Adding a one to a single bit bit-field should be turned into an XOR
3599       // of the bit.  First thing to check is to see if this AND is with a
3600       // single bit constant.
3601       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3602
3603       // If there is only one bit set...
3604       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3605         // Ok, at this point, we know that we are masking the result of the
3606         // ADD down to exactly one bit.  If the constant we are adding has
3607         // no bits set below this bit, then we can eliminate the ADD.
3608         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3609
3610         // Check to see if any bits below the one bit set in AndRHSV are set.
3611         if ((AddRHS & (AndRHSV-1)) == 0) {
3612           // If not, the only thing that can effect the output of the AND is
3613           // the bit specified by AndRHSV.  If that bit is set, the effect of
3614           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3615           // no effect.
3616           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3617             TheAnd.setOperand(0, X);
3618             return &TheAnd;
3619           } else {
3620             // Pull the XOR out of the AND.
3621             Value *NewAnd = Builder->CreateAnd(X, AndRHS);
3622             NewAnd->takeName(Op);
3623             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3624           }
3625         }
3626       }
3627     }
3628     break;
3629
3630   case Instruction::Shl: {
3631     // We know that the AND will not produce any of the bits shifted in, so if
3632     // the anded constant includes them, clear them now!
3633     //
3634     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3635     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3636     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3637     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3638
3639     if (CI->getValue() == ShlMask) { 
3640     // Masking out bits that the shift already masks
3641       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3642     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3643       TheAnd.setOperand(1, CI);
3644       return &TheAnd;
3645     }
3646     break;
3647   }
3648   case Instruction::LShr:
3649   {
3650     // We know that the AND will not produce any of the bits shifted in, so if
3651     // the anded constant includes them, clear them now!  This only applies to
3652     // unsigned shifts, because a signed shr may bring in set bits!
3653     //
3654     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3655     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3656     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3657     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3658
3659     if (CI->getValue() == ShrMask) {   
3660     // Masking out bits that the shift already masks.
3661       return ReplaceInstUsesWith(TheAnd, Op);
3662     } else if (CI != AndRHS) {
3663       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3664       return &TheAnd;
3665     }
3666     break;
3667   }
3668   case Instruction::AShr:
3669     // Signed shr.
3670     // See if this is shifting in some sign extension, then masking it out
3671     // with an and.
3672     if (Op->hasOneUse()) {
3673       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3674       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3675       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3676       Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3677       if (C == AndRHS) {          // Masking out bits shifted in.
3678         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3679         // Make the argument unsigned.
3680         Value *ShVal = Op->getOperand(0);
3681         ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
3682         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3683       }
3684     }
3685     break;
3686   }
3687   return 0;
3688 }
3689
3690
3691 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3692 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3693 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3694 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3695 /// insert new instructions.
3696 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3697                                            bool isSigned, bool Inside, 
3698                                            Instruction &IB) {
3699   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3700             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3701          "Lo is not <= Hi in range emission code!");
3702     
3703   if (Inside) {
3704     if (Lo == Hi)  // Trivially false.
3705       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3706
3707     // V >= Min && V < Hi --> V < Hi
3708     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3709       ICmpInst::Predicate pred = (isSigned ? 
3710         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3711       return new ICmpInst(pred, V, Hi);
3712     }
3713
3714     // Emit V-Lo <u Hi-Lo
3715     Constant *NegLo = ConstantExpr::getNeg(Lo);
3716     Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3717     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3718     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3719   }
3720
3721   if (Lo == Hi)  // Trivially true.
3722     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3723
3724   // V < Min || V >= Hi -> V > Hi-1
3725   Hi = SubOne(cast<ConstantInt>(Hi));
3726   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3727     ICmpInst::Predicate pred = (isSigned ? 
3728         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3729     return new ICmpInst(pred, V, Hi);
3730   }
3731
3732   // Emit V-Lo >u Hi-1-Lo
3733   // Note that Hi has already had one subtracted from it, above.
3734   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3735   Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3736   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3737   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3738 }
3739
3740 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3741 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3742 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3743 // not, since all 1s are not contiguous.
3744 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3745   const APInt& V = Val->getValue();
3746   uint32_t BitWidth = Val->getType()->getBitWidth();
3747   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3748
3749   // look for the first zero bit after the run of ones
3750   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3751   // look for the first non-zero bit
3752   ME = V.getActiveBits(); 
3753   return true;
3754 }
3755
3756 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3757 /// where isSub determines whether the operator is a sub.  If we can fold one of
3758 /// the following xforms:
3759 /// 
3760 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3761 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3762 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3763 ///
3764 /// return (A +/- B).
3765 ///
3766 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3767                                         ConstantInt *Mask, bool isSub,
3768                                         Instruction &I) {
3769   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3770   if (!LHSI || LHSI->getNumOperands() != 2 ||
3771       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3772
3773   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3774
3775   switch (LHSI->getOpcode()) {
3776   default: return 0;
3777   case Instruction::And:
3778     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3779       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3780       if ((Mask->getValue().countLeadingZeros() + 
3781            Mask->getValue().countPopulation()) == 
3782           Mask->getValue().getBitWidth())
3783         break;
3784
3785       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3786       // part, we don't need any explicit masks to take them out of A.  If that
3787       // is all N is, ignore it.
3788       uint32_t MB = 0, ME = 0;
3789       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3790         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3791         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3792         if (MaskedValueIsZero(RHS, Mask))
3793           break;
3794       }
3795     }
3796     return 0;
3797   case Instruction::Or:
3798   case Instruction::Xor:
3799     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3800     if ((Mask->getValue().countLeadingZeros() + 
3801          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3802         && ConstantExpr::getAnd(N, Mask)->isNullValue())
3803       break;
3804     return 0;
3805   }
3806   
3807   if (isSub)
3808     return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3809   return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
3810 }
3811
3812 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3813 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3814                                           ICmpInst *LHS, ICmpInst *RHS) {
3815   Value *Val, *Val2;
3816   ConstantInt *LHSCst, *RHSCst;
3817   ICmpInst::Predicate LHSCC, RHSCC;
3818   
3819   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3820   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3821                          m_ConstantInt(LHSCst))) ||
3822       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3823                          m_ConstantInt(RHSCst))))
3824     return 0;
3825   
3826   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3827   // where C is a power of 2
3828   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3829       LHSCst->getValue().isPowerOf2()) {
3830     Value *NewOr = Builder->CreateOr(Val, Val2);
3831     return new ICmpInst(LHSCC, NewOr, LHSCst);
3832   }
3833   
3834   // From here on, we only handle:
3835   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3836   if (Val != Val2) return 0;
3837   
3838   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3839   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3840       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3841       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3842       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3843     return 0;
3844   
3845   // We can't fold (ugt x, C) & (sgt x, C2).
3846   if (!PredicatesFoldable(LHSCC, RHSCC))
3847     return 0;
3848     
3849   // Ensure that the larger constant is on the RHS.
3850   bool ShouldSwap;
3851   if (ICmpInst::isSignedPredicate(LHSCC) ||
3852       (ICmpInst::isEquality(LHSCC) && 
3853        ICmpInst::isSignedPredicate(RHSCC)))
3854     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3855   else
3856     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3857     
3858   if (ShouldSwap) {
3859     std::swap(LHS, RHS);
3860     std::swap(LHSCst, RHSCst);
3861     std::swap(LHSCC, RHSCC);
3862   }
3863
3864   // At this point, we know we have have two icmp instructions
3865   // comparing a value against two constants and and'ing the result
3866   // together.  Because of the above check, we know that we only have
3867   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3868   // (from the FoldICmpLogical check above), that the two constants 
3869   // are not equal and that the larger constant is on the RHS
3870   assert(LHSCst != RHSCst && "Compares not folded above?");
3871
3872   switch (LHSCC) {
3873   default: llvm_unreachable("Unknown integer condition code!");
3874   case ICmpInst::ICMP_EQ:
3875     switch (RHSCC) {
3876     default: llvm_unreachable("Unknown integer condition code!");
3877     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3878     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3879     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3880       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3881     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3882     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3883     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3884       return ReplaceInstUsesWith(I, LHS);
3885     }
3886   case ICmpInst::ICMP_NE:
3887     switch (RHSCC) {
3888     default: llvm_unreachable("Unknown integer condition code!");
3889     case ICmpInst::ICMP_ULT:
3890       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3891         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3892       break;                        // (X != 13 & X u< 15) -> no change
3893     case ICmpInst::ICMP_SLT:
3894       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3895         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3896       break;                        // (X != 13 & X s< 15) -> no change
3897     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3898     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3899     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3900       return ReplaceInstUsesWith(I, RHS);
3901     case ICmpInst::ICMP_NE:
3902       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3903         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3904         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
3905         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3906                             ConstantInt::get(Add->getType(), 1));
3907       }
3908       break;                        // (X != 13 & X != 15) -> no change
3909     }
3910     break;
3911   case ICmpInst::ICMP_ULT:
3912     switch (RHSCC) {
3913     default: llvm_unreachable("Unknown integer condition code!");
3914     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3915     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3916       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3917     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3918       break;
3919     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3920     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3921       return ReplaceInstUsesWith(I, LHS);
3922     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3923       break;
3924     }
3925     break;
3926   case ICmpInst::ICMP_SLT:
3927     switch (RHSCC) {
3928     default: llvm_unreachable("Unknown integer condition code!");
3929     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3930     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3931       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3932     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3933       break;
3934     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3935     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3936       return ReplaceInstUsesWith(I, LHS);
3937     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3938       break;
3939     }
3940     break;
3941   case ICmpInst::ICMP_UGT:
3942     switch (RHSCC) {
3943     default: llvm_unreachable("Unknown integer condition code!");
3944     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3945     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3946       return ReplaceInstUsesWith(I, RHS);
3947     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3948       break;
3949     case ICmpInst::ICMP_NE:
3950       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3951         return new ICmpInst(LHSCC, Val, RHSCst);
3952       break;                        // (X u> 13 & X != 15) -> no change
3953     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3954       return InsertRangeTest(Val, AddOne(LHSCst),
3955                              RHSCst, false, true, I);
3956     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3957       break;
3958     }
3959     break;
3960   case ICmpInst::ICMP_SGT:
3961     switch (RHSCC) {
3962     default: llvm_unreachable("Unknown integer condition code!");
3963     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3964     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3965       return ReplaceInstUsesWith(I, RHS);
3966     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3967       break;
3968     case ICmpInst::ICMP_NE:
3969       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3970         return new ICmpInst(LHSCC, Val, RHSCst);
3971       break;                        // (X s> 13 & X != 15) -> no change
3972     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3973       return InsertRangeTest(Val, AddOne(LHSCst),
3974                              RHSCst, true, true, I);
3975     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3976       break;
3977     }
3978     break;
3979   }
3980  
3981   return 0;
3982 }
3983
3984 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3985                                           FCmpInst *RHS) {
3986   
3987   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3988       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3989     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3990     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3991       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3992         // If either of the constants are nans, then the whole thing returns
3993         // false.
3994         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3995           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3996         return new FCmpInst(FCmpInst::FCMP_ORD,
3997                             LHS->getOperand(0), RHS->getOperand(0));
3998       }
3999     
4000     // Handle vector zeros.  This occurs because the canonical form of
4001     // "fcmp ord x,x" is "fcmp ord x, 0".
4002     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4003         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4004       return new FCmpInst(FCmpInst::FCMP_ORD,
4005                           LHS->getOperand(0), RHS->getOperand(0));
4006     return 0;
4007   }
4008   
4009   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4010   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4011   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4012   
4013   
4014   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4015     // Swap RHS operands to match LHS.
4016     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4017     std::swap(Op1LHS, Op1RHS);
4018   }
4019   
4020   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4021     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4022     if (Op0CC == Op1CC)
4023       return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4024     
4025     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
4026       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4027     if (Op0CC == FCmpInst::FCMP_TRUE)
4028       return ReplaceInstUsesWith(I, RHS);
4029     if (Op1CC == FCmpInst::FCMP_TRUE)
4030       return ReplaceInstUsesWith(I, LHS);
4031     
4032     bool Op0Ordered;
4033     bool Op1Ordered;
4034     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4035     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4036     if (Op1Pred == 0) {
4037       std::swap(LHS, RHS);
4038       std::swap(Op0Pred, Op1Pred);
4039       std::swap(Op0Ordered, Op1Ordered);
4040     }
4041     if (Op0Pred == 0) {
4042       // uno && ueq -> uno && (uno || eq) -> ueq
4043       // ord && olt -> ord && (ord && lt) -> olt
4044       if (Op0Ordered == Op1Ordered)
4045         return ReplaceInstUsesWith(I, RHS);
4046       
4047       // uno && oeq -> uno && (ord && eq) -> false
4048       // uno && ord -> false
4049       if (!Op0Ordered)
4050         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4051       // ord && ueq -> ord && (uno || eq) -> oeq
4052       return cast<Instruction>(getFCmpValue(true, Op1Pred,
4053                                             Op0LHS, Op0RHS, Context));
4054     }
4055   }
4056
4057   return 0;
4058 }
4059
4060
4061 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4062   bool Changed = SimplifyCommutative(I);
4063   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4064
4065   if (isa<UndefValue>(Op1))                         // X & undef -> 0
4066     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4067
4068   // and X, X = X
4069   if (Op0 == Op1)
4070     return ReplaceInstUsesWith(I, Op1);
4071
4072   // See if we can simplify any instructions used by the instruction whose sole 
4073   // purpose is to compute bits we don't care about.
4074   if (SimplifyDemandedInstructionBits(I))
4075     return &I;
4076   if (isa<VectorType>(I.getType())) {
4077     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4078       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
4079         return ReplaceInstUsesWith(I, I.getOperand(0));
4080     } else if (isa<ConstantAggregateZero>(Op1)) {
4081       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
4082     }
4083   }
4084
4085   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4086     const APInt &AndRHSMask = AndRHS->getValue();
4087     APInt NotAndRHS(~AndRHSMask);
4088
4089     // Optimize a variety of ((val OP C1) & C2) combinations...
4090     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4091       Value *Op0LHS = Op0I->getOperand(0);
4092       Value *Op0RHS = Op0I->getOperand(1);
4093       switch (Op0I->getOpcode()) {
4094       default: break;
4095       case Instruction::Xor:
4096       case Instruction::Or:
4097         // If the mask is only needed on one incoming arm, push it up.
4098         if (!Op0I->hasOneUse()) break;
4099           
4100         if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4101           // Not masking anything out for the LHS, move to RHS.
4102           Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4103                                              Op0RHS->getName()+".masked");
4104           return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4105         }
4106         if (!isa<Constant>(Op0RHS) &&
4107             MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4108           // Not masking anything out for the RHS, move to LHS.
4109           Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4110                                              Op0LHS->getName()+".masked");
4111           return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
4112         }
4113
4114         break;
4115       case Instruction::Add:
4116         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4117         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4118         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4119         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4120           return BinaryOperator::CreateAnd(V, AndRHS);
4121         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4122           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4123         break;
4124
4125       case Instruction::Sub:
4126         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4127         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4128         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4129         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4130           return BinaryOperator::CreateAnd(V, AndRHS);
4131
4132         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4133         // has 1's for all bits that the subtraction with A might affect.
4134         if (Op0I->hasOneUse()) {
4135           uint32_t BitWidth = AndRHSMask.getBitWidth();
4136           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4137           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4138
4139           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4140           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4141               MaskedValueIsZero(Op0LHS, Mask)) {
4142             Value *NewNeg = Builder->CreateNeg(Op0RHS);
4143             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4144           }
4145         }
4146         break;
4147
4148       case Instruction::Shl:
4149       case Instruction::LShr:
4150         // (1 << x) & 1 --> zext(x == 0)
4151         // (1 >> x) & 1 --> zext(x == 0)
4152         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4153           Value *NewICmp =
4154             Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
4155           return new ZExtInst(NewICmp, I.getType());
4156         }
4157         break;
4158       }
4159
4160       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4161         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4162           return Res;
4163     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4164       // If this is an integer truncation or change from signed-to-unsigned, and
4165       // if the source is an and/or with immediate, transform it.  This
4166       // frequently occurs for bitfield accesses.
4167       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4168         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4169             CastOp->getNumOperands() == 2)
4170           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4171             if (CastOp->getOpcode() == Instruction::And) {
4172               // Change: and (cast (and X, C1) to T), C2
4173               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4174               // This will fold the two constants together, which may allow 
4175               // other simplifications.
4176               Value *NewCast = Builder->CreateTruncOrBitCast(
4177                 CastOp->getOperand(0), I.getType(), 
4178                 CastOp->getName()+".shrunk");
4179               // trunc_or_bitcast(C1)&C2
4180               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4181               C3 = ConstantExpr::getAnd(C3, AndRHS);
4182               return BinaryOperator::CreateAnd(NewCast, C3);
4183             } else if (CastOp->getOpcode() == Instruction::Or) {
4184               // Change: and (cast (or X, C1) to T), C2
4185               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4186               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4187               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4188                 // trunc(C1)&C2
4189                 return ReplaceInstUsesWith(I, AndRHS);
4190             }
4191           }
4192       }
4193     }
4194
4195     // Try to fold constant and into select arguments.
4196     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4197       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4198         return R;
4199     if (isa<PHINode>(Op0))
4200       if (Instruction *NV = FoldOpIntoPhi(I))
4201         return NV;
4202   }
4203
4204   Value *Op0NotVal = dyn_castNotVal(Op0);
4205   Value *Op1NotVal = dyn_castNotVal(Op1);
4206
4207   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4208     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4209
4210   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4211   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4212     Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4213                                   I.getName()+".demorgan");
4214     return BinaryOperator::CreateNot(Or);
4215   }
4216   
4217   {
4218     Value *A = 0, *B = 0, *C = 0, *D = 0;
4219     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4220       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4221         return ReplaceInstUsesWith(I, Op1);
4222     
4223       // (A|B) & ~(A&B) -> A^B
4224       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4225         if ((A == C && B == D) || (A == D && B == C))
4226           return BinaryOperator::CreateXor(A, B);
4227       }
4228     }
4229     
4230     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4231       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4232         return ReplaceInstUsesWith(I, Op0);
4233
4234       // ~(A&B) & (A|B) -> A^B
4235       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4236         if ((A == C && B == D) || (A == D && B == C))
4237           return BinaryOperator::CreateXor(A, B);
4238       }
4239     }
4240     
4241     if (Op0->hasOneUse() &&
4242         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4243       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4244         I.swapOperands();     // Simplify below
4245         std::swap(Op0, Op1);
4246       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4247         cast<BinaryOperator>(Op0)->swapOperands();
4248         I.swapOperands();     // Simplify below
4249         std::swap(Op0, Op1);
4250       }
4251     }
4252
4253     if (Op1->hasOneUse() &&
4254         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4255       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4256         cast<BinaryOperator>(Op1)->swapOperands();
4257         std::swap(A, B);
4258       }
4259       if (A == Op0)                                // A&(A^B) -> A & ~B
4260         return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
4261     }
4262
4263     // (A&((~A)|B)) -> A&B
4264     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4265         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4266       return BinaryOperator::CreateAnd(A, Op1);
4267     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4268         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4269       return BinaryOperator::CreateAnd(A, Op0);
4270   }
4271   
4272   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4273     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4274     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4275       return R;
4276
4277     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4278       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4279         return Res;
4280   }
4281
4282   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4283   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4284     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4285       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4286         const Type *SrcTy = Op0C->getOperand(0)->getType();
4287         if (SrcTy == Op1C->getOperand(0)->getType() &&
4288             SrcTy->isIntOrIntVector() &&
4289             // Only do this if the casts both really cause code to be generated.
4290             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4291                               I.getType(), TD) &&
4292             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4293                               I.getType(), TD)) {
4294           Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4295                                             Op1C->getOperand(0), I.getName());
4296           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4297         }
4298       }
4299     
4300   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4301   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4302     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4303       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4304           SI0->getOperand(1) == SI1->getOperand(1) &&
4305           (SI0->hasOneUse() || SI1->hasOneUse())) {
4306         Value *NewOp =
4307           Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4308                              SI0->getName());
4309         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4310                                       SI1->getOperand(1));
4311       }
4312   }
4313
4314   // If and'ing two fcmp, try combine them into one.
4315   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4316     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4317       if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4318         return Res;
4319   }
4320
4321   return Changed ? &I : 0;
4322 }
4323
4324 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4325 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4326 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4327 /// the expression came from the corresponding "byte swapped" byte in some other
4328 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4329 /// we know that the expression deposits the low byte of %X into the high byte
4330 /// of the bswap result and that all other bytes are zero.  This expression is
4331 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4332 /// match.
4333 ///
4334 /// This function returns true if the match was unsuccessful and false if so.
4335 /// On entry to the function the "OverallLeftShift" is a signed integer value
4336 /// indicating the number of bytes that the subexpression is later shifted.  For
4337 /// example, if the expression is later right shifted by 16 bits, the
4338 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4339 /// byte of ByteValues is actually being set.
4340 ///
4341 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4342 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4343 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4344 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4345 /// always in the local (OverallLeftShift) coordinate space.
4346 ///
4347 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4348                               SmallVector<Value*, 8> &ByteValues) {
4349   if (Instruction *I = dyn_cast<Instruction>(V)) {
4350     // If this is an or instruction, it may be an inner node of the bswap.
4351     if (I->getOpcode() == Instruction::Or) {
4352       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4353                                ByteValues) ||
4354              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4355                                ByteValues);
4356     }
4357   
4358     // If this is a logical shift by a constant multiple of 8, recurse with
4359     // OverallLeftShift and ByteMask adjusted.
4360     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4361       unsigned ShAmt = 
4362         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4363       // Ensure the shift amount is defined and of a byte value.
4364       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4365         return true;
4366
4367       unsigned ByteShift = ShAmt >> 3;
4368       if (I->getOpcode() == Instruction::Shl) {
4369         // X << 2 -> collect(X, +2)
4370         OverallLeftShift += ByteShift;
4371         ByteMask >>= ByteShift;
4372       } else {
4373         // X >>u 2 -> collect(X, -2)
4374         OverallLeftShift -= ByteShift;
4375         ByteMask <<= ByteShift;
4376         ByteMask &= (~0U >> (32-ByteValues.size()));
4377       }
4378
4379       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4380       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4381
4382       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4383                                ByteValues);
4384     }
4385
4386     // If this is a logical 'and' with a mask that clears bytes, clear the
4387     // corresponding bytes in ByteMask.
4388     if (I->getOpcode() == Instruction::And &&
4389         isa<ConstantInt>(I->getOperand(1))) {
4390       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4391       unsigned NumBytes = ByteValues.size();
4392       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4393       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4394       
4395       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4396         // If this byte is masked out by a later operation, we don't care what
4397         // the and mask is.
4398         if ((ByteMask & (1 << i)) == 0)
4399           continue;
4400         
4401         // If the AndMask is all zeros for this byte, clear the bit.
4402         APInt MaskB = AndMask & Byte;
4403         if (MaskB == 0) {
4404           ByteMask &= ~(1U << i);
4405           continue;
4406         }
4407         
4408         // If the AndMask is not all ones for this byte, it's not a bytezap.
4409         if (MaskB != Byte)
4410           return true;
4411
4412         // Otherwise, this byte is kept.
4413       }
4414
4415       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4416                                ByteValues);
4417     }
4418   }
4419   
4420   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4421   // the input value to the bswap.  Some observations: 1) if more than one byte
4422   // is demanded from this input, then it could not be successfully assembled
4423   // into a byteswap.  At least one of the two bytes would not be aligned with
4424   // their ultimate destination.
4425   if (!isPowerOf2_32(ByteMask)) return true;
4426   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4427   
4428   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4429   // is demanded, it needs to go into byte 0 of the result.  This means that the
4430   // byte needs to be shifted until it lands in the right byte bucket.  The
4431   // shift amount depends on the position: if the byte is coming from the high
4432   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4433   // low part, it must be shifted left.
4434   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4435   if (InputByteNo < ByteValues.size()/2) {
4436     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4437       return true;
4438   } else {
4439     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4440       return true;
4441   }
4442   
4443   // If the destination byte value is already defined, the values are or'd
4444   // together, which isn't a bswap (unless it's an or of the same bits).
4445   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4446     return true;
4447   ByteValues[DestByteNo] = V;
4448   return false;
4449 }
4450
4451 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4452 /// If so, insert the new bswap intrinsic and return it.
4453 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4454   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4455   if (!ITy || ITy->getBitWidth() % 16 || 
4456       // ByteMask only allows up to 32-byte values.
4457       ITy->getBitWidth() > 32*8) 
4458     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4459   
4460   /// ByteValues - For each byte of the result, we keep track of which value
4461   /// defines each byte.
4462   SmallVector<Value*, 8> ByteValues;
4463   ByteValues.resize(ITy->getBitWidth()/8);
4464     
4465   // Try to find all the pieces corresponding to the bswap.
4466   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4467   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4468     return 0;
4469   
4470   // Check to see if all of the bytes come from the same value.
4471   Value *V = ByteValues[0];
4472   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4473   
4474   // Check to make sure that all of the bytes come from the same value.
4475   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4476     if (ByteValues[i] != V)
4477       return 0;
4478   const Type *Tys[] = { ITy };
4479   Module *M = I.getParent()->getParent()->getParent();
4480   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4481   return CallInst::Create(F, V);
4482 }
4483
4484 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4485 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4486 /// we can simplify this expression to "cond ? C : D or B".
4487 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4488                                          Value *C, Value *D,
4489                                          LLVMContext *Context) {
4490   // If A is not a select of -1/0, this cannot match.
4491   Value *Cond = 0;
4492   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4493     return 0;
4494
4495   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4496   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4497     return SelectInst::Create(Cond, C, B);
4498   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4499     return SelectInst::Create(Cond, C, B);
4500   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4501   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4502     return SelectInst::Create(Cond, C, D);
4503   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4504     return SelectInst::Create(Cond, C, D);
4505   return 0;
4506 }
4507
4508 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4509 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4510                                          ICmpInst *LHS, ICmpInst *RHS) {
4511   Value *Val, *Val2;
4512   ConstantInt *LHSCst, *RHSCst;
4513   ICmpInst::Predicate LHSCC, RHSCC;
4514   
4515   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4516   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4517              m_ConstantInt(LHSCst))) ||
4518       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4519              m_ConstantInt(RHSCst))))
4520     return 0;
4521   
4522   // From here on, we only handle:
4523   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4524   if (Val != Val2) return 0;
4525   
4526   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4527   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4528       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4529       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4530       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4531     return 0;
4532   
4533   // We can't fold (ugt x, C) | (sgt x, C2).
4534   if (!PredicatesFoldable(LHSCC, RHSCC))
4535     return 0;
4536   
4537   // Ensure that the larger constant is on the RHS.
4538   bool ShouldSwap;
4539   if (ICmpInst::isSignedPredicate(LHSCC) ||
4540       (ICmpInst::isEquality(LHSCC) && 
4541        ICmpInst::isSignedPredicate(RHSCC)))
4542     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4543   else
4544     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4545   
4546   if (ShouldSwap) {
4547     std::swap(LHS, RHS);
4548     std::swap(LHSCst, RHSCst);
4549     std::swap(LHSCC, RHSCC);
4550   }
4551   
4552   // At this point, we know we have have two icmp instructions
4553   // comparing a value against two constants and or'ing the result
4554   // together.  Because of the above check, we know that we only have
4555   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4556   // FoldICmpLogical check above), that the two constants are not
4557   // equal.
4558   assert(LHSCst != RHSCst && "Compares not folded above?");
4559
4560   switch (LHSCC) {
4561   default: llvm_unreachable("Unknown integer condition code!");
4562   case ICmpInst::ICMP_EQ:
4563     switch (RHSCC) {
4564     default: llvm_unreachable("Unknown integer condition code!");
4565     case ICmpInst::ICMP_EQ:
4566       if (LHSCst == SubOne(RHSCst)) {
4567         // (X == 13 | X == 14) -> X-13 <u 2
4568         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4569         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4570         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4571         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4572       }
4573       break;                         // (X == 13 | X == 15) -> no change
4574     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4575     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4576       break;
4577     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4578     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4579     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4580       return ReplaceInstUsesWith(I, RHS);
4581     }
4582     break;
4583   case ICmpInst::ICMP_NE:
4584     switch (RHSCC) {
4585     default: llvm_unreachable("Unknown integer condition code!");
4586     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4587     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4588     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4589       return ReplaceInstUsesWith(I, LHS);
4590     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4591     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4592     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4593       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4594     }
4595     break;
4596   case ICmpInst::ICMP_ULT:
4597     switch (RHSCC) {
4598     default: llvm_unreachable("Unknown integer condition code!");
4599     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4600       break;
4601     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4602       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4603       // this can cause overflow.
4604       if (RHSCst->isMaxValue(false))
4605         return ReplaceInstUsesWith(I, LHS);
4606       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4607                              false, false, I);
4608     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4609       break;
4610     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4611     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4612       return ReplaceInstUsesWith(I, RHS);
4613     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4614       break;
4615     }
4616     break;
4617   case ICmpInst::ICMP_SLT:
4618     switch (RHSCC) {
4619     default: llvm_unreachable("Unknown integer condition code!");
4620     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4621       break;
4622     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4623       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4624       // this can cause overflow.
4625       if (RHSCst->isMaxValue(true))
4626         return ReplaceInstUsesWith(I, LHS);
4627       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4628                              true, false, I);
4629     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4630       break;
4631     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4632     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4633       return ReplaceInstUsesWith(I, RHS);
4634     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4635       break;
4636     }
4637     break;
4638   case ICmpInst::ICMP_UGT:
4639     switch (RHSCC) {
4640     default: llvm_unreachable("Unknown integer condition code!");
4641     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4642     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4643       return ReplaceInstUsesWith(I, LHS);
4644     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4645       break;
4646     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4647     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4648       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4649     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4650       break;
4651     }
4652     break;
4653   case ICmpInst::ICMP_SGT:
4654     switch (RHSCC) {
4655     default: llvm_unreachable("Unknown integer condition code!");
4656     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4657     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4658       return ReplaceInstUsesWith(I, LHS);
4659     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4660       break;
4661     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4662     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4663       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4664     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4665       break;
4666     }
4667     break;
4668   }
4669   return 0;
4670 }
4671
4672 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4673                                          FCmpInst *RHS) {
4674   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4675       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4676       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4677     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4678       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4679         // If either of the constants are nans, then the whole thing returns
4680         // true.
4681         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4682           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4683         
4684         // Otherwise, no need to compare the two constants, compare the
4685         // rest.
4686         return new FCmpInst(FCmpInst::FCMP_UNO,
4687                             LHS->getOperand(0), RHS->getOperand(0));
4688       }
4689     
4690     // Handle vector zeros.  This occurs because the canonical form of
4691     // "fcmp uno x,x" is "fcmp uno x, 0".
4692     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4693         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4694       return new FCmpInst(FCmpInst::FCMP_UNO,
4695                           LHS->getOperand(0), RHS->getOperand(0));
4696     
4697     return 0;
4698   }
4699   
4700   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4701   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4702   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4703   
4704   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4705     // Swap RHS operands to match LHS.
4706     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4707     std::swap(Op1LHS, Op1RHS);
4708   }
4709   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4710     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4711     if (Op0CC == Op1CC)
4712       return new FCmpInst((FCmpInst::Predicate)Op0CC,
4713                           Op0LHS, Op0RHS);
4714     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4715       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4716     if (Op0CC == FCmpInst::FCMP_FALSE)
4717       return ReplaceInstUsesWith(I, RHS);
4718     if (Op1CC == FCmpInst::FCMP_FALSE)
4719       return ReplaceInstUsesWith(I, LHS);
4720     bool Op0Ordered;
4721     bool Op1Ordered;
4722     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4723     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4724     if (Op0Ordered == Op1Ordered) {
4725       // If both are ordered or unordered, return a new fcmp with
4726       // or'ed predicates.
4727       Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4728                                Op0LHS, Op0RHS, Context);
4729       if (Instruction *I = dyn_cast<Instruction>(RV))
4730         return I;
4731       // Otherwise, it's a constant boolean value...
4732       return ReplaceInstUsesWith(I, RV);
4733     }
4734   }
4735   return 0;
4736 }
4737
4738 /// FoldOrWithConstants - This helper function folds:
4739 ///
4740 ///     ((A | B) & C1) | (B & C2)
4741 ///
4742 /// into:
4743 /// 
4744 ///     (A & C1) | B
4745 ///
4746 /// when the XOR of the two constants is "all ones" (-1).
4747 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4748                                                Value *A, Value *B, Value *C) {
4749   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4750   if (!CI1) return 0;
4751
4752   Value *V1 = 0;
4753   ConstantInt *CI2 = 0;
4754   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4755
4756   APInt Xor = CI1->getValue() ^ CI2->getValue();
4757   if (!Xor.isAllOnesValue()) return 0;
4758
4759   if (V1 == A || V1 == B) {
4760     Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
4761     return BinaryOperator::CreateOr(NewOp, V1);
4762   }
4763
4764   return 0;
4765 }
4766
4767 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4768   bool Changed = SimplifyCommutative(I);
4769   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4770
4771   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4772     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4773
4774   // or X, X = X
4775   if (Op0 == Op1)
4776     return ReplaceInstUsesWith(I, Op0);
4777
4778   // See if we can simplify any instructions used by the instruction whose sole 
4779   // purpose is to compute bits we don't care about.
4780   if (SimplifyDemandedInstructionBits(I))
4781     return &I;
4782   if (isa<VectorType>(I.getType())) {
4783     if (isa<ConstantAggregateZero>(Op1)) {
4784       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4785     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4786       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4787         return ReplaceInstUsesWith(I, I.getOperand(1));
4788     }
4789   }
4790
4791   // or X, -1 == -1
4792   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4793     ConstantInt *C1 = 0; Value *X = 0;
4794     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4795     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
4796         isOnlyUse(Op0)) {
4797       Value *Or = Builder->CreateOr(X, RHS);
4798       Or->takeName(Op0);
4799       return BinaryOperator::CreateAnd(Or, 
4800                ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
4801     }
4802
4803     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4804     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
4805         isOnlyUse(Op0)) {
4806       Value *Or = Builder->CreateOr(X, RHS);
4807       Or->takeName(Op0);
4808       return BinaryOperator::CreateXor(Or,
4809                  ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
4810     }
4811
4812     // Try to fold constant and into select arguments.
4813     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4814       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4815         return R;
4816     if (isa<PHINode>(Op0))
4817       if (Instruction *NV = FoldOpIntoPhi(I))
4818         return NV;
4819   }
4820
4821   Value *A = 0, *B = 0;
4822   ConstantInt *C1 = 0, *C2 = 0;
4823
4824   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4825     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4826       return ReplaceInstUsesWith(I, Op1);
4827   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4828     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4829       return ReplaceInstUsesWith(I, Op0);
4830
4831   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4832   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4833   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4834       match(Op1, m_Or(m_Value(), m_Value())) ||
4835       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4836        match(Op1, m_Shift(m_Value(), m_Value())))) {
4837     if (Instruction *BSwap = MatchBSwap(I))
4838       return BSwap;
4839   }
4840   
4841   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4842   if (Op0->hasOneUse() &&
4843       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4844       MaskedValueIsZero(Op1, C1->getValue())) {
4845     Value *NOr = Builder->CreateOr(A, Op1);
4846     NOr->takeName(Op0);
4847     return BinaryOperator::CreateXor(NOr, C1);
4848   }
4849
4850   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4851   if (Op1->hasOneUse() &&
4852       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4853       MaskedValueIsZero(Op0, C1->getValue())) {
4854     Value *NOr = Builder->CreateOr(A, Op0);
4855     NOr->takeName(Op0);
4856     return BinaryOperator::CreateXor(NOr, C1);
4857   }
4858
4859   // (A & C)|(B & D)
4860   Value *C = 0, *D = 0;
4861   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4862       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4863     Value *V1 = 0, *V2 = 0, *V3 = 0;
4864     C1 = dyn_cast<ConstantInt>(C);
4865     C2 = dyn_cast<ConstantInt>(D);
4866     if (C1 && C2) {  // (A & C1)|(B & C2)
4867       // If we have: ((V + N) & C1) | (V & C2)
4868       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4869       // replace with V+N.
4870       if (C1->getValue() == ~C2->getValue()) {
4871         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4872             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4873           // Add commutes, try both ways.
4874           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4875             return ReplaceInstUsesWith(I, A);
4876           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4877             return ReplaceInstUsesWith(I, A);
4878         }
4879         // Or commutes, try both ways.
4880         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4881             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4882           // Add commutes, try both ways.
4883           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4884             return ReplaceInstUsesWith(I, B);
4885           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4886             return ReplaceInstUsesWith(I, B);
4887         }
4888       }
4889       V1 = 0; V2 = 0; V3 = 0;
4890     }
4891     
4892     // Check to see if we have any common things being and'ed.  If so, find the
4893     // terms for V1 & (V2|V3).
4894     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4895       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4896         V1 = A, V2 = C, V3 = D;
4897       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4898         V1 = A, V2 = B, V3 = C;
4899       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4900         V1 = C, V2 = A, V3 = D;
4901       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4902         V1 = C, V2 = A, V3 = B;
4903       
4904       if (V1) {
4905         Value *Or = Builder->CreateOr(V2, V3, "tmp");
4906         return BinaryOperator::CreateAnd(V1, Or);
4907       }
4908     }
4909
4910     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4911     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4912       return Match;
4913     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4914       return Match;
4915     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4916       return Match;
4917     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4918       return Match;
4919
4920     // ((A&~B)|(~A&B)) -> A^B
4921     if ((match(C, m_Not(m_Specific(D))) &&
4922          match(B, m_Not(m_Specific(A)))))
4923       return BinaryOperator::CreateXor(A, D);
4924     // ((~B&A)|(~A&B)) -> A^B
4925     if ((match(A, m_Not(m_Specific(D))) &&
4926          match(B, m_Not(m_Specific(C)))))
4927       return BinaryOperator::CreateXor(C, D);
4928     // ((A&~B)|(B&~A)) -> A^B
4929     if ((match(C, m_Not(m_Specific(B))) &&
4930          match(D, m_Not(m_Specific(A)))))
4931       return BinaryOperator::CreateXor(A, B);
4932     // ((~B&A)|(B&~A)) -> A^B
4933     if ((match(A, m_Not(m_Specific(B))) &&
4934          match(D, m_Not(m_Specific(C)))))
4935       return BinaryOperator::CreateXor(C, B);
4936   }
4937   
4938   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4939   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4940     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4941       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4942           SI0->getOperand(1) == SI1->getOperand(1) &&
4943           (SI0->hasOneUse() || SI1->hasOneUse())) {
4944         Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4945                                          SI0->getName());
4946         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4947                                       SI1->getOperand(1));
4948       }
4949   }
4950
4951   // ((A|B)&1)|(B&-2) -> (A&1) | B
4952   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4953       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4954     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4955     if (Ret) return Ret;
4956   }
4957   // (B&-2)|((A|B)&1) -> (A&1) | B
4958   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4959       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4960     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4961     if (Ret) return Ret;
4962   }
4963
4964   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4965     if (A == Op1)   // ~A | A == -1
4966       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4967   } else {
4968     A = 0;
4969   }
4970   // Note, A is still live here!
4971   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4972     if (Op0 == B)
4973       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4974
4975     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4976     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4977       Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
4978       return BinaryOperator::CreateNot(And);
4979     }
4980   }
4981
4982   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4983   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4984     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4985       return R;
4986
4987     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4988       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4989         return Res;
4990   }
4991     
4992   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4993   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4994     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4995       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4996         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4997             !isa<ICmpInst>(Op1C->getOperand(0))) {
4998           const Type *SrcTy = Op0C->getOperand(0)->getType();
4999           if (SrcTy == Op1C->getOperand(0)->getType() &&
5000               SrcTy->isIntOrIntVector() &&
5001               // Only do this if the casts both really cause code to be
5002               // generated.
5003               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5004                                 I.getType(), TD) &&
5005               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5006                                 I.getType(), TD)) {
5007             Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5008                                              Op1C->getOperand(0), I.getName());
5009             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5010           }
5011         }
5012       }
5013   }
5014   
5015     
5016   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
5017   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
5018     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5019       if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5020         return Res;
5021   }
5022
5023   return Changed ? &I : 0;
5024 }
5025
5026 namespace {
5027
5028 // XorSelf - Implements: X ^ X --> 0
5029 struct XorSelf {
5030   Value *RHS;
5031   XorSelf(Value *rhs) : RHS(rhs) {}
5032   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5033   Instruction *apply(BinaryOperator &Xor) const {
5034     return &Xor;
5035   }
5036 };
5037
5038 }
5039
5040 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5041   bool Changed = SimplifyCommutative(I);
5042   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5043
5044   if (isa<UndefValue>(Op1)) {
5045     if (isa<UndefValue>(Op0))
5046       // Handle undef ^ undef -> 0 special case. This is a common
5047       // idiom (misuse).
5048       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5049     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5050   }
5051
5052   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5053   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
5054     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5055     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5056   }
5057   
5058   // See if we can simplify any instructions used by the instruction whose sole 
5059   // purpose is to compute bits we don't care about.
5060   if (SimplifyDemandedInstructionBits(I))
5061     return &I;
5062   if (isa<VectorType>(I.getType()))
5063     if (isa<ConstantAggregateZero>(Op1))
5064       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5065
5066   // Is this a ~ operation?
5067   if (Value *NotOp = dyn_castNotVal(&I)) {
5068     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5069     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5070     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5071       if (Op0I->getOpcode() == Instruction::And || 
5072           Op0I->getOpcode() == Instruction::Or) {
5073         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5074         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5075           Value *NotY =
5076             Builder->CreateNot(Op0I->getOperand(1),
5077                                Op0I->getOperand(1)->getName()+".not");
5078           if (Op0I->getOpcode() == Instruction::And)
5079             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5080           return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5081         }
5082       }
5083     }
5084   }
5085   
5086   
5087   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5088     if (RHS->isOne() && Op0->hasOneUse()) {
5089       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5090       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5091         return new ICmpInst(ICI->getInversePredicate(),
5092                             ICI->getOperand(0), ICI->getOperand(1));
5093
5094       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5095         return new FCmpInst(FCI->getInversePredicate(),
5096                             FCI->getOperand(0), FCI->getOperand(1));
5097     }
5098
5099     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5100     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5101       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5102         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5103           Instruction::CastOps Opcode = Op0C->getOpcode();
5104           if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5105               (RHS == ConstantExpr::getCast(Opcode, 
5106                                             ConstantInt::getTrue(*Context),
5107                                             Op0C->getDestTy()))) {
5108             CI->setPredicate(CI->getInversePredicate());
5109             return CastInst::Create(Opcode, CI, Op0C->getType());
5110           }
5111         }
5112       }
5113     }
5114
5115     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5116       // ~(c-X) == X-c-1 == X+(-c-1)
5117       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5118         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5119           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5120           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5121                                       ConstantInt::get(I.getType(), 1));
5122           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5123         }
5124           
5125       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5126         if (Op0I->getOpcode() == Instruction::Add) {
5127           // ~(X-c) --> (-c-1)-X
5128           if (RHS->isAllOnesValue()) {
5129             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5130             return BinaryOperator::CreateSub(
5131                            ConstantExpr::getSub(NegOp0CI,
5132                                       ConstantInt::get(I.getType(), 1)),
5133                                       Op0I->getOperand(0));
5134           } else if (RHS->getValue().isSignBit()) {
5135             // (X + C) ^ signbit -> (X + C + signbit)
5136             Constant *C = ConstantInt::get(*Context,
5137                                            RHS->getValue() + Op0CI->getValue());
5138             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5139
5140           }
5141         } else if (Op0I->getOpcode() == Instruction::Or) {
5142           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5143           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5144             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5145             // Anything in both C1 and C2 is known to be zero, remove it from
5146             // NewRHS.
5147             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5148             NewRHS = ConstantExpr::getAnd(NewRHS, 
5149                                        ConstantExpr::getNot(CommonBits));
5150             Worklist.Add(Op0I);
5151             I.setOperand(0, Op0I->getOperand(0));
5152             I.setOperand(1, NewRHS);
5153             return &I;
5154           }
5155         }
5156       }
5157     }
5158
5159     // Try to fold constant and into select arguments.
5160     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5161       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5162         return R;
5163     if (isa<PHINode>(Op0))
5164       if (Instruction *NV = FoldOpIntoPhi(I))
5165         return NV;
5166   }
5167
5168   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5169     if (X == Op1)
5170       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5171
5172   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5173     if (X == Op0)
5174       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5175
5176   
5177   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5178   if (Op1I) {
5179     Value *A, *B;
5180     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5181       if (A == Op0) {              // B^(B|A) == (A|B)^B
5182         Op1I->swapOperands();
5183         I.swapOperands();
5184         std::swap(Op0, Op1);
5185       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5186         I.swapOperands();     // Simplified below.
5187         std::swap(Op0, Op1);
5188       }
5189     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5190       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5191     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5192       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5193     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && 
5194                Op1I->hasOneUse()){
5195       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5196         Op1I->swapOperands();
5197         std::swap(A, B);
5198       }
5199       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5200         I.swapOperands();     // Simplified below.
5201         std::swap(Op0, Op1);
5202       }
5203     }
5204   }
5205   
5206   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5207   if (Op0I) {
5208     Value *A, *B;
5209     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5210         Op0I->hasOneUse()) {
5211       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5212         std::swap(A, B);
5213       if (B == Op1)                                  // (A|B)^B == A & ~B
5214         return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
5215     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5216       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5217     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5218       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5219     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && 
5220                Op0I->hasOneUse()){
5221       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5222         std::swap(A, B);
5223       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5224           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5225         return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
5226       }
5227     }
5228   }
5229   
5230   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5231   if (Op0I && Op1I && Op0I->isShift() && 
5232       Op0I->getOpcode() == Op1I->getOpcode() && 
5233       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5234       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5235     Value *NewOp =
5236       Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5237                          Op0I->getName());
5238     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5239                                   Op1I->getOperand(1));
5240   }
5241     
5242   if (Op0I && Op1I) {
5243     Value *A, *B, *C, *D;
5244     // (A & B)^(A | B) -> A ^ B
5245     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5246         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5247       if ((A == C && B == D) || (A == D && B == C)) 
5248         return BinaryOperator::CreateXor(A, B);
5249     }
5250     // (A | B)^(A & B) -> A ^ B
5251     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5252         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5253       if ((A == C && B == D) || (A == D && B == C)) 
5254         return BinaryOperator::CreateXor(A, B);
5255     }
5256     
5257     // (A & B)^(C & D)
5258     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5259         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5260         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5261       // (X & Y)^(X & Y) -> (Y^Z) & X
5262       Value *X = 0, *Y = 0, *Z = 0;
5263       if (A == C)
5264         X = A, Y = B, Z = D;
5265       else if (A == D)
5266         X = A, Y = B, Z = C;
5267       else if (B == C)
5268         X = B, Y = A, Z = D;
5269       else if (B == D)
5270         X = B, Y = A, Z = C;
5271       
5272       if (X) {
5273         Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
5274         return BinaryOperator::CreateAnd(NewOp, X);
5275       }
5276     }
5277   }
5278     
5279   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5280   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5281     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5282       return R;
5283
5284   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5285   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5286     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5287       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5288         const Type *SrcTy = Op0C->getOperand(0)->getType();
5289         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5290             // Only do this if the casts both really cause code to be generated.
5291             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5292                               I.getType(), TD) &&
5293             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5294                               I.getType(), TD)) {
5295           Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5296                                             Op1C->getOperand(0), I.getName());
5297           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5298         }
5299       }
5300   }
5301
5302   return Changed ? &I : 0;
5303 }
5304
5305 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5306                                    LLVMContext *Context) {
5307   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5308 }
5309
5310 static bool HasAddOverflow(ConstantInt *Result,
5311                            ConstantInt *In1, ConstantInt *In2,
5312                            bool IsSigned) {
5313   if (IsSigned)
5314     if (In2->getValue().isNegative())
5315       return Result->getValue().sgt(In1->getValue());
5316     else
5317       return Result->getValue().slt(In1->getValue());
5318   else
5319     return Result->getValue().ult(In1->getValue());
5320 }
5321
5322 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5323 /// overflowed for this type.
5324 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5325                             Constant *In2, LLVMContext *Context,
5326                             bool IsSigned = false) {
5327   Result = ConstantExpr::getAdd(In1, In2);
5328
5329   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5330     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5331       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5332       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5333                          ExtractElement(In1, Idx, Context),
5334                          ExtractElement(In2, Idx, Context),
5335                          IsSigned))
5336         return true;
5337     }
5338     return false;
5339   }
5340
5341   return HasAddOverflow(cast<ConstantInt>(Result),
5342                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5343                         IsSigned);
5344 }
5345
5346 static bool HasSubOverflow(ConstantInt *Result,
5347                            ConstantInt *In1, ConstantInt *In2,
5348                            bool IsSigned) {
5349   if (IsSigned)
5350     if (In2->getValue().isNegative())
5351       return Result->getValue().slt(In1->getValue());
5352     else
5353       return Result->getValue().sgt(In1->getValue());
5354   else
5355     return Result->getValue().ugt(In1->getValue());
5356 }
5357
5358 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5359 /// overflowed for this type.
5360 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5361                             Constant *In2, LLVMContext *Context,
5362                             bool IsSigned = false) {
5363   Result = ConstantExpr::getSub(In1, In2);
5364
5365   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5366     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5367       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5368       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5369                          ExtractElement(In1, Idx, Context),
5370                          ExtractElement(In2, Idx, Context),
5371                          IsSigned))
5372         return true;
5373     }
5374     return false;
5375   }
5376
5377   return HasSubOverflow(cast<ConstantInt>(Result),
5378                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5379                         IsSigned);
5380 }
5381
5382 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5383 /// code necessary to compute the offset from the base pointer (without adding
5384 /// in the base pointer).  Return the result as a signed integer of intptr size.
5385 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5386   TargetData &TD = *IC.getTargetData();
5387   gep_type_iterator GTI = gep_type_begin(GEP);
5388   const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
5389   Value *Result = Constant::getNullValue(IntPtrTy);
5390
5391   // Build a mask for high order bits.
5392   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5393   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5394
5395   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5396        ++i, ++GTI) {
5397     Value *Op = *i;
5398     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5399     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5400       if (OpC->isZero()) continue;
5401       
5402       // Handle a struct index, which adds its field offset to the pointer.
5403       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5404         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5405         
5406         Result = IC.Builder->CreateAdd(Result,
5407                                        ConstantInt::get(IntPtrTy, Size),
5408                                        GEP->getName()+".offs");
5409         continue;
5410       }
5411       
5412       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5413       Constant *OC =
5414               ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5415       Scale = ConstantExpr::getMul(OC, Scale);
5416       // Emit an add instruction.
5417       Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
5418       continue;
5419     }
5420     // Convert to correct type.
5421     if (Op->getType() != IntPtrTy)
5422       Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
5423     if (Size != 1) {
5424       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5425       // We'll let instcombine(mul) convert this to a shl if possible.
5426       Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
5427     }
5428
5429     // Emit an add instruction.
5430     Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
5431   }
5432   return Result;
5433 }
5434
5435
5436 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5437 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
5438 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
5439 /// be complex, and scales are involved.  The above expression would also be
5440 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5441 /// This later form is less amenable to optimization though, and we are allowed
5442 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5443 ///
5444 /// If we can't emit an optimized form for this expression, this returns null.
5445 /// 
5446 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5447                                           InstCombiner &IC) {
5448   TargetData &TD = *IC.getTargetData();
5449   gep_type_iterator GTI = gep_type_begin(GEP);
5450
5451   // Check to see if this gep only has a single variable index.  If so, and if
5452   // any constant indices are a multiple of its scale, then we can compute this
5453   // in terms of the scale of the variable index.  For example, if the GEP
5454   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5455   // because the expression will cross zero at the same point.
5456   unsigned i, e = GEP->getNumOperands();
5457   int64_t Offset = 0;
5458   for (i = 1; i != e; ++i, ++GTI) {
5459     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5460       // Compute the aggregate offset of constant indices.
5461       if (CI->isZero()) continue;
5462
5463       // Handle a struct index, which adds its field offset to the pointer.
5464       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5465         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5466       } else {
5467         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5468         Offset += Size*CI->getSExtValue();
5469       }
5470     } else {
5471       // Found our variable index.
5472       break;
5473     }
5474   }
5475   
5476   // If there are no variable indices, we must have a constant offset, just
5477   // evaluate it the general way.
5478   if (i == e) return 0;
5479   
5480   Value *VariableIdx = GEP->getOperand(i);
5481   // Determine the scale factor of the variable element.  For example, this is
5482   // 4 if the variable index is into an array of i32.
5483   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5484   
5485   // Verify that there are no other variable indices.  If so, emit the hard way.
5486   for (++i, ++GTI; i != e; ++i, ++GTI) {
5487     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5488     if (!CI) return 0;
5489    
5490     // Compute the aggregate offset of constant indices.
5491     if (CI->isZero()) continue;
5492     
5493     // Handle a struct index, which adds its field offset to the pointer.
5494     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5495       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5496     } else {
5497       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5498       Offset += Size*CI->getSExtValue();
5499     }
5500   }
5501   
5502   // Okay, we know we have a single variable index, which must be a
5503   // pointer/array/vector index.  If there is no offset, life is simple, return
5504   // the index.
5505   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5506   if (Offset == 0) {
5507     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5508     // we don't need to bother extending: the extension won't affect where the
5509     // computation crosses zero.
5510     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5511       VariableIdx = new TruncInst(VariableIdx, 
5512                                   TD.getIntPtrType(VariableIdx->getContext()),
5513                                   VariableIdx->getName(), &I);
5514     return VariableIdx;
5515   }
5516   
5517   // Otherwise, there is an index.  The computation we will do will be modulo
5518   // the pointer size, so get it.
5519   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5520   
5521   Offset &= PtrSizeMask;
5522   VariableScale &= PtrSizeMask;
5523
5524   // To do this transformation, any constant index must be a multiple of the
5525   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5526   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5527   // multiple of the variable scale.
5528   int64_t NewOffs = Offset / (int64_t)VariableScale;
5529   if (Offset != NewOffs*(int64_t)VariableScale)
5530     return 0;
5531
5532   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5533   const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
5534   if (VariableIdx->getType() != IntPtrTy)
5535     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5536                                               true /*SExt*/, 
5537                                               VariableIdx->getName(), &I);
5538   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5539   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5540 }
5541
5542
5543 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5544 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5545 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5546                                        ICmpInst::Predicate Cond,
5547                                        Instruction &I) {
5548   // Look through bitcasts.
5549   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5550     RHS = BCI->getOperand(0);
5551
5552   Value *PtrBase = GEPLHS->getOperand(0);
5553   if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5554     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5555     // This transformation (ignoring the base and scales) is valid because we
5556     // know pointers can't overflow since the gep is inbounds.  See if we can
5557     // output an optimized form.
5558     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5559     
5560     // If not, synthesize the offset the hard way.
5561     if (Offset == 0)
5562       Offset = EmitGEPOffset(GEPLHS, I, *this);
5563     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5564                         Constant::getNullValue(Offset->getType()));
5565   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5566     // If the base pointers are different, but the indices are the same, just
5567     // compare the base pointer.
5568     if (PtrBase != GEPRHS->getOperand(0)) {
5569       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5570       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5571                         GEPRHS->getOperand(0)->getType();
5572       if (IndicesTheSame)
5573         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5574           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5575             IndicesTheSame = false;
5576             break;
5577           }
5578
5579       // If all indices are the same, just compare the base pointers.
5580       if (IndicesTheSame)
5581         return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5582                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5583
5584       // Otherwise, the base pointers are different and the indices are
5585       // different, bail out.
5586       return 0;
5587     }
5588
5589     // If one of the GEPs has all zero indices, recurse.
5590     bool AllZeros = true;
5591     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5592       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5593           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5594         AllZeros = false;
5595         break;
5596       }
5597     if (AllZeros)
5598       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5599                           ICmpInst::getSwappedPredicate(Cond), I);
5600
5601     // If the other GEP has all zero indices, recurse.
5602     AllZeros = true;
5603     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5604       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5605           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5606         AllZeros = false;
5607         break;
5608       }
5609     if (AllZeros)
5610       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5611
5612     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5613       // If the GEPs only differ by one index, compare it.
5614       unsigned NumDifferences = 0;  // Keep track of # differences.
5615       unsigned DiffOperand = 0;     // The operand that differs.
5616       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5617         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5618           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5619                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5620             // Irreconcilable differences.
5621             NumDifferences = 2;
5622             break;
5623           } else {
5624             if (NumDifferences++) break;
5625             DiffOperand = i;
5626           }
5627         }
5628
5629       if (NumDifferences == 0)   // SAME GEP?
5630         return ReplaceInstUsesWith(I, // No comparison is needed here.
5631                                    ConstantInt::get(Type::getInt1Ty(*Context),
5632                                              ICmpInst::isTrueWhenEqual(Cond)));
5633
5634       else if (NumDifferences == 1) {
5635         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5636         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5637         // Make sure we do a signed comparison here.
5638         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5639       }
5640     }
5641
5642     // Only lower this if the icmp is the only user of the GEP or if we expect
5643     // the result to fold to a constant!
5644     if (TD &&
5645         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5646         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5647       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5648       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5649       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5650       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5651     }
5652   }
5653   return 0;
5654 }
5655
5656 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5657 ///
5658 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5659                                                 Instruction *LHSI,
5660                                                 Constant *RHSC) {
5661   if (!isa<ConstantFP>(RHSC)) return 0;
5662   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5663   
5664   // Get the width of the mantissa.  We don't want to hack on conversions that
5665   // might lose information from the integer, e.g. "i64 -> float"
5666   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5667   if (MantissaWidth == -1) return 0;  // Unknown.
5668   
5669   // Check to see that the input is converted from an integer type that is small
5670   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5671   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5672   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5673   
5674   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5675   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5676   if (LHSUnsigned)
5677     ++InputSize;
5678   
5679   // If the conversion would lose info, don't hack on this.
5680   if ((int)InputSize > MantissaWidth)
5681     return 0;
5682   
5683   // Otherwise, we can potentially simplify the comparison.  We know that it
5684   // will always come through as an integer value and we know the constant is
5685   // not a NAN (it would have been previously simplified).
5686   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5687   
5688   ICmpInst::Predicate Pred;
5689   switch (I.getPredicate()) {
5690   default: llvm_unreachable("Unexpected predicate!");
5691   case FCmpInst::FCMP_UEQ:
5692   case FCmpInst::FCMP_OEQ:
5693     Pred = ICmpInst::ICMP_EQ;
5694     break;
5695   case FCmpInst::FCMP_UGT:
5696   case FCmpInst::FCMP_OGT:
5697     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5698     break;
5699   case FCmpInst::FCMP_UGE:
5700   case FCmpInst::FCMP_OGE:
5701     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5702     break;
5703   case FCmpInst::FCMP_ULT:
5704   case FCmpInst::FCMP_OLT:
5705     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5706     break;
5707   case FCmpInst::FCMP_ULE:
5708   case FCmpInst::FCMP_OLE:
5709     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5710     break;
5711   case FCmpInst::FCMP_UNE:
5712   case FCmpInst::FCMP_ONE:
5713     Pred = ICmpInst::ICMP_NE;
5714     break;
5715   case FCmpInst::FCMP_ORD:
5716     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5717   case FCmpInst::FCMP_UNO:
5718     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5719   }
5720   
5721   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5722   
5723   // Now we know that the APFloat is a normal number, zero or inf.
5724   
5725   // See if the FP constant is too large for the integer.  For example,
5726   // comparing an i8 to 300.0.
5727   unsigned IntWidth = IntTy->getScalarSizeInBits();
5728   
5729   if (!LHSUnsigned) {
5730     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5731     // and large values.
5732     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5733     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5734                           APFloat::rmNearestTiesToEven);
5735     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5736       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5737           Pred == ICmpInst::ICMP_SLE)
5738         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5739       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5740     }
5741   } else {
5742     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5743     // +INF and large values.
5744     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5745     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5746                           APFloat::rmNearestTiesToEven);
5747     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5748       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5749           Pred == ICmpInst::ICMP_ULE)
5750         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5751       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5752     }
5753   }
5754   
5755   if (!LHSUnsigned) {
5756     // See if the RHS value is < SignedMin.
5757     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5758     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5759                           APFloat::rmNearestTiesToEven);
5760     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5761       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5762           Pred == ICmpInst::ICMP_SGE)
5763         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5764       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5765     }
5766   }
5767
5768   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5769   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5770   // casting the FP value to the integer value and back, checking for equality.
5771   // Don't do this for zero, because -0.0 is not fractional.
5772   Constant *RHSInt = LHSUnsigned
5773     ? ConstantExpr::getFPToUI(RHSC, IntTy)
5774     : ConstantExpr::getFPToSI(RHSC, IntTy);
5775   if (!RHS.isZero()) {
5776     bool Equal = LHSUnsigned
5777       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5778       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5779     if (!Equal) {
5780       // If we had a comparison against a fractional value, we have to adjust
5781       // the compare predicate and sometimes the value.  RHSC is rounded towards
5782       // zero at this point.
5783       switch (Pred) {
5784       default: llvm_unreachable("Unexpected integer comparison!");
5785       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5786         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5787       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5788         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5789       case ICmpInst::ICMP_ULE:
5790         // (float)int <= 4.4   --> int <= 4
5791         // (float)int <= -4.4  --> false
5792         if (RHS.isNegative())
5793           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5794         break;
5795       case ICmpInst::ICMP_SLE:
5796         // (float)int <= 4.4   --> int <= 4
5797         // (float)int <= -4.4  --> int < -4
5798         if (RHS.isNegative())
5799           Pred = ICmpInst::ICMP_SLT;
5800         break;
5801       case ICmpInst::ICMP_ULT:
5802         // (float)int < -4.4   --> false
5803         // (float)int < 4.4    --> int <= 4
5804         if (RHS.isNegative())
5805           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5806         Pred = ICmpInst::ICMP_ULE;
5807         break;
5808       case ICmpInst::ICMP_SLT:
5809         // (float)int < -4.4   --> int < -4
5810         // (float)int < 4.4    --> int <= 4
5811         if (!RHS.isNegative())
5812           Pred = ICmpInst::ICMP_SLE;
5813         break;
5814       case ICmpInst::ICMP_UGT:
5815         // (float)int > 4.4    --> int > 4
5816         // (float)int > -4.4   --> true
5817         if (RHS.isNegative())
5818           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5819         break;
5820       case ICmpInst::ICMP_SGT:
5821         // (float)int > 4.4    --> int > 4
5822         // (float)int > -4.4   --> int >= -4
5823         if (RHS.isNegative())
5824           Pred = ICmpInst::ICMP_SGE;
5825         break;
5826       case ICmpInst::ICMP_UGE:
5827         // (float)int >= -4.4   --> true
5828         // (float)int >= 4.4    --> int > 4
5829         if (!RHS.isNegative())
5830           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5831         Pred = ICmpInst::ICMP_UGT;
5832         break;
5833       case ICmpInst::ICMP_SGE:
5834         // (float)int >= -4.4   --> int >= -4
5835         // (float)int >= 4.4    --> int > 4
5836         if (!RHS.isNegative())
5837           Pred = ICmpInst::ICMP_SGT;
5838         break;
5839       }
5840     }
5841   }
5842
5843   // Lower this FP comparison into an appropriate integer version of the
5844   // comparison.
5845   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5846 }
5847
5848 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5849   bool Changed = SimplifyCompare(I);
5850   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5851
5852   // Fold trivial predicates.
5853   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5854     return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
5855   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5856     return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
5857   
5858   // Simplify 'fcmp pred X, X'
5859   if (Op0 == Op1) {
5860     switch (I.getPredicate()) {
5861     default: llvm_unreachable("Unknown predicate!");
5862     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5863     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5864     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5865       return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
5866     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5867     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5868     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5869       return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
5870       
5871     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5872     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5873     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5874     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5875       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5876       I.setPredicate(FCmpInst::FCMP_UNO);
5877       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5878       return &I;
5879       
5880     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5881     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5882     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5883     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5884       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5885       I.setPredicate(FCmpInst::FCMP_ORD);
5886       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5887       return &I;
5888     }
5889   }
5890     
5891   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5892     return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
5893
5894   // Handle fcmp with constant RHS
5895   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5896     // If the constant is a nan, see if we can fold the comparison based on it.
5897     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5898       if (CFP->getValueAPF().isNaN()) {
5899         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5900           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5901         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5902                "Comparison must be either ordered or unordered!");
5903         // True if unordered.
5904         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5905       }
5906     }
5907     
5908     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5909       switch (LHSI->getOpcode()) {
5910       case Instruction::PHI:
5911         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5912         // block.  If in the same block, we're encouraging jump threading.  If
5913         // not, we are just pessimizing the code by making an i1 phi.
5914         if (LHSI->getParent() == I.getParent())
5915           if (Instruction *NV = FoldOpIntoPhi(I, true))
5916             return NV;
5917         break;
5918       case Instruction::SIToFP:
5919       case Instruction::UIToFP:
5920         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5921           return NV;
5922         break;
5923       case Instruction::Select:
5924         // If either operand of the select is a constant, we can fold the
5925         // comparison into the select arms, which will cause one to be
5926         // constant folded and the select turned into a bitwise or.
5927         Value *Op1 = 0, *Op2 = 0;
5928         if (LHSI->hasOneUse()) {
5929           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5930             // Fold the known value into the constant operand.
5931             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5932             // Insert a new FCmp of the other select operand.
5933             Op2 = Builder->CreateFCmp(I.getPredicate(),
5934                                       LHSI->getOperand(2), RHSC, I.getName());
5935           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5936             // Fold the known value into the constant operand.
5937             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5938             // Insert a new FCmp of the other select operand.
5939             Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5940                                       RHSC, I.getName());
5941           }
5942         }
5943
5944         if (Op1)
5945           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5946         break;
5947       }
5948   }
5949
5950   return Changed ? &I : 0;
5951 }
5952
5953 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5954   bool Changed = SimplifyCompare(I);
5955   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5956   const Type *Ty = Op0->getType();
5957
5958   // icmp X, X
5959   if (Op0 == Op1)
5960     return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
5961                                                    I.isTrueWhenEqual()));
5962
5963   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5964     return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
5965   
5966   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5967   // addresses never equal each other!  We already know that Op0 != Op1.
5968   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) || 
5969        isa<ConstantPointerNull>(Op0)) &&
5970       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) || 
5971        isa<ConstantPointerNull>(Op1)))
5972     return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context), 
5973                                                    !I.isTrueWhenEqual()));
5974
5975   // icmp's with boolean values can always be turned into bitwise operations
5976   if (Ty == Type::getInt1Ty(*Context)) {
5977     switch (I.getPredicate()) {
5978     default: llvm_unreachable("Invalid icmp instruction!");
5979     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5980       Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
5981       return BinaryOperator::CreateNot(Xor);
5982     }
5983     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5984       return BinaryOperator::CreateXor(Op0, Op1);
5985
5986     case ICmpInst::ICMP_UGT:
5987       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5988       // FALL THROUGH
5989     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5990       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
5991       return BinaryOperator::CreateAnd(Not, Op1);
5992     }
5993     case ICmpInst::ICMP_SGT:
5994       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5995       // FALL THROUGH
5996     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5997       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
5998       return BinaryOperator::CreateAnd(Not, Op0);
5999     }
6000     case ICmpInst::ICMP_UGE:
6001       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6002       // FALL THROUGH
6003     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6004       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
6005       return BinaryOperator::CreateOr(Not, Op1);
6006     }
6007     case ICmpInst::ICMP_SGE:
6008       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6009       // FALL THROUGH
6010     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6011       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
6012       return BinaryOperator::CreateOr(Not, Op0);
6013     }
6014     }
6015   }
6016
6017   unsigned BitWidth = 0;
6018   if (TD)
6019     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6020   else if (Ty->isIntOrIntVector())
6021     BitWidth = Ty->getScalarSizeInBits();
6022
6023   bool isSignBit = false;
6024
6025   // See if we are doing a comparison with a constant.
6026   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6027     Value *A = 0, *B = 0;
6028     
6029     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6030     if (I.isEquality() && CI->isNullValue() &&
6031         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
6032       // (icmp cond A B) if cond is equality
6033       return new ICmpInst(I.getPredicate(), A, B);
6034     }
6035     
6036     // If we have an icmp le or icmp ge instruction, turn it into the
6037     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6038     // them being folded in the code below.
6039     switch (I.getPredicate()) {
6040     default: break;
6041     case ICmpInst::ICMP_ULE:
6042       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6043         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6044       return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
6045                           AddOne(CI));
6046     case ICmpInst::ICMP_SLE:
6047       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6048         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6049       return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6050                           AddOne(CI));
6051     case ICmpInst::ICMP_UGE:
6052       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6053         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6054       return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
6055                           SubOne(CI));
6056     case ICmpInst::ICMP_SGE:
6057       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6058         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6059       return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6060                           SubOne(CI));
6061     }
6062     
6063     // If this comparison is a normal comparison, it demands all
6064     // bits, if it is a sign bit comparison, it only demands the sign bit.
6065     bool UnusedBit;
6066     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6067   }
6068
6069   // See if we can fold the comparison based on range information we can get
6070   // by checking whether bits are known to be zero or one in the input.
6071   if (BitWidth != 0) {
6072     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6073     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6074
6075     if (SimplifyDemandedBits(I.getOperandUse(0),
6076                              isSignBit ? APInt::getSignBit(BitWidth)
6077                                        : APInt::getAllOnesValue(BitWidth),
6078                              Op0KnownZero, Op0KnownOne, 0))
6079       return &I;
6080     if (SimplifyDemandedBits(I.getOperandUse(1),
6081                              APInt::getAllOnesValue(BitWidth),
6082                              Op1KnownZero, Op1KnownOne, 0))
6083       return &I;
6084
6085     // Given the known and unknown bits, compute a range that the LHS could be
6086     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6087     // EQ and NE we use unsigned values.
6088     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6089     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6090     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6091       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6092                                              Op0Min, Op0Max);
6093       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6094                                              Op1Min, Op1Max);
6095     } else {
6096       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6097                                                Op0Min, Op0Max);
6098       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6099                                                Op1Min, Op1Max);
6100     }
6101
6102     // If Min and Max are known to be the same, then SimplifyDemandedBits
6103     // figured out that the LHS is a constant.  Just constant fold this now so
6104     // that code below can assume that Min != Max.
6105     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6106       return new ICmpInst(I.getPredicate(),
6107                           ConstantInt::get(*Context, Op0Min), Op1);
6108     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6109       return new ICmpInst(I.getPredicate(), Op0,
6110                           ConstantInt::get(*Context, Op1Min));
6111
6112     // Based on the range information we know about the LHS, see if we can
6113     // simplify this comparison.  For example, (x&4) < 8  is always true.
6114     switch (I.getPredicate()) {
6115     default: llvm_unreachable("Unknown icmp opcode!");
6116     case ICmpInst::ICMP_EQ:
6117       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6118         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6119       break;
6120     case ICmpInst::ICMP_NE:
6121       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6122         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6123       break;
6124     case ICmpInst::ICMP_ULT:
6125       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6126         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6127       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6128         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6129       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6130         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6131       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6132         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6133           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6134                               SubOne(CI));
6135
6136         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6137         if (CI->isMinValue(true))
6138           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6139                            Constant::getAllOnesValue(Op0->getType()));
6140       }
6141       break;
6142     case ICmpInst::ICMP_UGT:
6143       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6144         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6145       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6146         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6147
6148       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6149         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6150       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6151         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6152           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6153                               AddOne(CI));
6154
6155         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6156         if (CI->isMaxValue(true))
6157           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6158                               Constant::getNullValue(Op0->getType()));
6159       }
6160       break;
6161     case ICmpInst::ICMP_SLT:
6162       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6163         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6164       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6165         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6166       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6167         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6168       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6169         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6170           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6171                               SubOne(CI));
6172       }
6173       break;
6174     case ICmpInst::ICMP_SGT:
6175       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6176         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6177       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6178         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6179
6180       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6181         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6182       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6183         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6184           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6185                               AddOne(CI));
6186       }
6187       break;
6188     case ICmpInst::ICMP_SGE:
6189       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6190       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6191         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6192       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6193         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6194       break;
6195     case ICmpInst::ICMP_SLE:
6196       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6197       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6198         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6199       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6200         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6201       break;
6202     case ICmpInst::ICMP_UGE:
6203       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6204       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6205         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6206       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6207         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6208       break;
6209     case ICmpInst::ICMP_ULE:
6210       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6211       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6212         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6213       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6214         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6215       break;
6216     }
6217
6218     // Turn a signed comparison into an unsigned one if both operands
6219     // are known to have the same sign.
6220     if (I.isSignedPredicate() &&
6221         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6222          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6223       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6224   }
6225
6226   // Test if the ICmpInst instruction is used exclusively by a select as
6227   // part of a minimum or maximum operation. If so, refrain from doing
6228   // any other folding. This helps out other analyses which understand
6229   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6230   // and CodeGen. And in this case, at least one of the comparison
6231   // operands has at least one user besides the compare (the select),
6232   // which would often largely negate the benefit of folding anyway.
6233   if (I.hasOneUse())
6234     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6235       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6236           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6237         return 0;
6238
6239   // See if we are doing a comparison between a constant and an instruction that
6240   // can be folded into the comparison.
6241   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6242     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6243     // instruction, see if that instruction also has constants so that the 
6244     // instruction can be folded into the icmp 
6245     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6246       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6247         return Res;
6248   }
6249
6250   // Handle icmp with constant (but not simple integer constant) RHS
6251   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6252     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6253       switch (LHSI->getOpcode()) {
6254       case Instruction::GetElementPtr:
6255         if (RHSC->isNullValue()) {
6256           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6257           bool isAllZeros = true;
6258           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6259             if (!isa<Constant>(LHSI->getOperand(i)) ||
6260                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6261               isAllZeros = false;
6262               break;
6263             }
6264           if (isAllZeros)
6265             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6266                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6267         }
6268         break;
6269
6270       case Instruction::PHI:
6271         // Only fold icmp into the PHI if the phi and icmp are in the same
6272         // block.  If in the same block, we're encouraging jump threading.  If
6273         // not, we are just pessimizing the code by making an i1 phi.
6274         if (LHSI->getParent() == I.getParent())
6275           if (Instruction *NV = FoldOpIntoPhi(I, true))
6276             return NV;
6277         break;
6278       case Instruction::Select: {
6279         // If either operand of the select is a constant, we can fold the
6280         // comparison into the select arms, which will cause one to be
6281         // constant folded and the select turned into a bitwise or.
6282         Value *Op1 = 0, *Op2 = 0;
6283         if (LHSI->hasOneUse()) {
6284           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6285             // Fold the known value into the constant operand.
6286             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6287             // Insert a new ICmp of the other select operand.
6288             Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6289                                       RHSC, I.getName());
6290           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6291             // Fold the known value into the constant operand.
6292             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6293             // Insert a new ICmp of the other select operand.
6294             Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6295                                       RHSC, I.getName());
6296           }
6297         }
6298
6299         if (Op1)
6300           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6301         break;
6302       }
6303       case Instruction::Call:
6304         // If we have (malloc != null), and if the malloc has a single use, we
6305         // can assume it is successful and remove the malloc.
6306         if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6307             isa<ConstantPointerNull>(RHSC)) {
6308           // Need to explicitly erase malloc call here, instead of adding it to
6309           // Worklist, because it won't get DCE'd from the Worklist since
6310           // isInstructionTriviallyDead() returns false for function calls.
6311           // It is OK to replace LHSI/MallocCall with Undef because the 
6312           // instruction that uses it will be erased via Worklist.
6313           if (extractMallocCall(LHSI)) {
6314             LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6315             EraseInstFromFunction(*LHSI);
6316             return ReplaceInstUsesWith(I,
6317                                      ConstantInt::get(Type::getInt1Ty(*Context),
6318                                                       !I.isTrueWhenEqual()));
6319           }
6320           if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6321             if (MallocCall->hasOneUse()) {
6322               MallocCall->replaceAllUsesWith(
6323                                         UndefValue::get(MallocCall->getType()));
6324               EraseInstFromFunction(*MallocCall);
6325               Worklist.Add(LHSI); // The malloc's bitcast use.
6326               return ReplaceInstUsesWith(I,
6327                                      ConstantInt::get(Type::getInt1Ty(*Context),
6328                                                       !I.isTrueWhenEqual()));
6329             }
6330         }
6331         break;
6332       }
6333   }
6334
6335   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6336   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6337     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6338       return NI;
6339   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6340     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6341                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6342       return NI;
6343
6344   // Test to see if the operands of the icmp are casted versions of other
6345   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6346   // now.
6347   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6348     if (isa<PointerType>(Op0->getType()) && 
6349         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6350       // We keep moving the cast from the left operand over to the right
6351       // operand, where it can often be eliminated completely.
6352       Op0 = CI->getOperand(0);
6353
6354       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6355       // so eliminate it as well.
6356       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6357         Op1 = CI2->getOperand(0);
6358
6359       // If Op1 is a constant, we can fold the cast into the constant.
6360       if (Op0->getType() != Op1->getType()) {
6361         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6362           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6363         } else {
6364           // Otherwise, cast the RHS right before the icmp
6365           Op1 = Builder->CreateBitCast(Op1, Op0->getType());
6366         }
6367       }
6368       return new ICmpInst(I.getPredicate(), Op0, Op1);
6369     }
6370   }
6371   
6372   if (isa<CastInst>(Op0)) {
6373     // Handle the special case of: icmp (cast bool to X), <cst>
6374     // This comes up when you have code like
6375     //   int X = A < B;
6376     //   if (X) ...
6377     // For generality, we handle any zero-extension of any operand comparison
6378     // with a constant or another cast from the same type.
6379     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6380       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6381         return R;
6382   }
6383   
6384   // See if it's the same type of instruction on the left and right.
6385   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6386     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6387       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6388           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6389         switch (Op0I->getOpcode()) {
6390         default: break;
6391         case Instruction::Add:
6392         case Instruction::Sub:
6393         case Instruction::Xor:
6394           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6395             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6396                                 Op1I->getOperand(0));
6397           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6398           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6399             if (CI->getValue().isSignBit()) {
6400               ICmpInst::Predicate Pred = I.isSignedPredicate()
6401                                              ? I.getUnsignedPredicate()
6402                                              : I.getSignedPredicate();
6403               return new ICmpInst(Pred, Op0I->getOperand(0),
6404                                   Op1I->getOperand(0));
6405             }
6406             
6407             if (CI->getValue().isMaxSignedValue()) {
6408               ICmpInst::Predicate Pred = I.isSignedPredicate()
6409                                              ? I.getUnsignedPredicate()
6410                                              : I.getSignedPredicate();
6411               Pred = I.getSwappedPredicate(Pred);
6412               return new ICmpInst(Pred, Op0I->getOperand(0),
6413                                   Op1I->getOperand(0));
6414             }
6415           }
6416           break;
6417         case Instruction::Mul:
6418           if (!I.isEquality())
6419             break;
6420
6421           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6422             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6423             // Mask = -1 >> count-trailing-zeros(Cst).
6424             if (!CI->isZero() && !CI->isOne()) {
6425               const APInt &AP = CI->getValue();
6426               ConstantInt *Mask = ConstantInt::get(*Context, 
6427                                       APInt::getLowBitsSet(AP.getBitWidth(),
6428                                                            AP.getBitWidth() -
6429                                                       AP.countTrailingZeros()));
6430               Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6431               Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
6432               return new ICmpInst(I.getPredicate(), And1, And2);
6433             }
6434           }
6435           break;
6436         }
6437       }
6438     }
6439   }
6440   
6441   // ~x < ~y --> y < x
6442   { Value *A, *B;
6443     if (match(Op0, m_Not(m_Value(A))) &&
6444         match(Op1, m_Not(m_Value(B))))
6445       return new ICmpInst(I.getPredicate(), B, A);
6446   }
6447   
6448   if (I.isEquality()) {
6449     Value *A, *B, *C, *D;
6450     
6451     // -x == -y --> x == y
6452     if (match(Op0, m_Neg(m_Value(A))) &&
6453         match(Op1, m_Neg(m_Value(B))))
6454       return new ICmpInst(I.getPredicate(), A, B);
6455     
6456     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6457       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6458         Value *OtherVal = A == Op1 ? B : A;
6459         return new ICmpInst(I.getPredicate(), OtherVal,
6460                             Constant::getNullValue(A->getType()));
6461       }
6462
6463       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6464         // A^c1 == C^c2 --> A == C^(c1^c2)
6465         ConstantInt *C1, *C2;
6466         if (match(B, m_ConstantInt(C1)) &&
6467             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6468           Constant *NC = 
6469                    ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6470           Value *Xor = Builder->CreateXor(C, NC, "tmp");
6471           return new ICmpInst(I.getPredicate(), A, Xor);
6472         }
6473         
6474         // A^B == A^D -> B == D
6475         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6476         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6477         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6478         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6479       }
6480     }
6481     
6482     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6483         (A == Op0 || B == Op0)) {
6484       // A == (A^B)  ->  B == 0
6485       Value *OtherVal = A == Op0 ? B : A;
6486       return new ICmpInst(I.getPredicate(), OtherVal,
6487                           Constant::getNullValue(A->getType()));
6488     }
6489
6490     // (A-B) == A  ->  B == 0
6491     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6492       return new ICmpInst(I.getPredicate(), B, 
6493                           Constant::getNullValue(B->getType()));
6494
6495     // A == (A-B)  ->  B == 0
6496     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6497       return new ICmpInst(I.getPredicate(), B,
6498                           Constant::getNullValue(B->getType()));
6499     
6500     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6501     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6502         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6503         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6504       Value *X = 0, *Y = 0, *Z = 0;
6505       
6506       if (A == C) {
6507         X = B; Y = D; Z = A;
6508       } else if (A == D) {
6509         X = B; Y = C; Z = A;
6510       } else if (B == C) {
6511         X = A; Y = D; Z = B;
6512       } else if (B == D) {
6513         X = A; Y = C; Z = B;
6514       }
6515       
6516       if (X) {   // Build (X^Y) & Z
6517         Op1 = Builder->CreateXor(X, Y, "tmp");
6518         Op1 = Builder->CreateAnd(Op1, Z, "tmp");
6519         I.setOperand(0, Op1);
6520         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6521         return &I;
6522       }
6523     }
6524   }
6525   return Changed ? &I : 0;
6526 }
6527
6528
6529 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6530 /// and CmpRHS are both known to be integer constants.
6531 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6532                                           ConstantInt *DivRHS) {
6533   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6534   const APInt &CmpRHSV = CmpRHS->getValue();
6535   
6536   // FIXME: If the operand types don't match the type of the divide 
6537   // then don't attempt this transform. The code below doesn't have the
6538   // logic to deal with a signed divide and an unsigned compare (and
6539   // vice versa). This is because (x /s C1) <s C2  produces different 
6540   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6541   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6542   // work. :(  The if statement below tests that condition and bails 
6543   // if it finds it. 
6544   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6545   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6546     return 0;
6547   if (DivRHS->isZero())
6548     return 0; // The ProdOV computation fails on divide by zero.
6549   if (DivIsSigned && DivRHS->isAllOnesValue())
6550     return 0; // The overflow computation also screws up here
6551   if (DivRHS->isOne())
6552     return 0; // Not worth bothering, and eliminates some funny cases
6553               // with INT_MIN.
6554
6555   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6556   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6557   // C2 (CI). By solving for X we can turn this into a range check 
6558   // instead of computing a divide. 
6559   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6560
6561   // Determine if the product overflows by seeing if the product is
6562   // not equal to the divide. Make sure we do the same kind of divide
6563   // as in the LHS instruction that we're folding. 
6564   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6565                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6566
6567   // Get the ICmp opcode
6568   ICmpInst::Predicate Pred = ICI.getPredicate();
6569
6570   // Figure out the interval that is being checked.  For example, a comparison
6571   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6572   // Compute this interval based on the constants involved and the signedness of
6573   // the compare/divide.  This computes a half-open interval, keeping track of
6574   // whether either value in the interval overflows.  After analysis each
6575   // overflow variable is set to 0 if it's corresponding bound variable is valid
6576   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6577   int LoOverflow = 0, HiOverflow = 0;
6578   Constant *LoBound = 0, *HiBound = 0;
6579   
6580   if (!DivIsSigned) {  // udiv
6581     // e.g. X/5 op 3  --> [15, 20)
6582     LoBound = Prod;
6583     HiOverflow = LoOverflow = ProdOV;
6584     if (!HiOverflow)
6585       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6586   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6587     if (CmpRHSV == 0) {       // (X / pos) op 0
6588       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6589       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6590       HiBound = DivRHS;
6591     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6592       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6593       HiOverflow = LoOverflow = ProdOV;
6594       if (!HiOverflow)
6595         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6596     } else {                       // (X / pos) op neg
6597       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6598       HiBound = AddOne(Prod);
6599       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6600       if (!LoOverflow) {
6601         ConstantInt* DivNeg =
6602                          cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6603         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6604                                      true) ? -1 : 0;
6605        }
6606     }
6607   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6608     if (CmpRHSV == 0) {       // (X / neg) op 0
6609       // e.g. X/-5 op 0  --> [-4, 5)
6610       LoBound = AddOne(DivRHS);
6611       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6612       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6613         HiOverflow = 1;            // [INTMIN+1, overflow)
6614         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6615       }
6616     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6617       // e.g. X/-5 op 3  --> [-19, -14)
6618       HiBound = AddOne(Prod);
6619       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6620       if (!LoOverflow)
6621         LoOverflow = AddWithOverflow(LoBound, HiBound,
6622                                      DivRHS, Context, true) ? -1 : 0;
6623     } else {                       // (X / neg) op neg
6624       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6625       LoOverflow = HiOverflow = ProdOV;
6626       if (!HiOverflow)
6627         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6628     }
6629     
6630     // Dividing by a negative swaps the condition.  LT <-> GT
6631     Pred = ICmpInst::getSwappedPredicate(Pred);
6632   }
6633
6634   Value *X = DivI->getOperand(0);
6635   switch (Pred) {
6636   default: llvm_unreachable("Unhandled icmp opcode!");
6637   case ICmpInst::ICMP_EQ:
6638     if (LoOverflow && HiOverflow)
6639       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6640     else if (HiOverflow)
6641       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6642                           ICmpInst::ICMP_UGE, X, LoBound);
6643     else if (LoOverflow)
6644       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6645                           ICmpInst::ICMP_ULT, X, HiBound);
6646     else
6647       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6648   case ICmpInst::ICMP_NE:
6649     if (LoOverflow && HiOverflow)
6650       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6651     else if (HiOverflow)
6652       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6653                           ICmpInst::ICMP_ULT, X, LoBound);
6654     else if (LoOverflow)
6655       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6656                           ICmpInst::ICMP_UGE, X, HiBound);
6657     else
6658       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6659   case ICmpInst::ICMP_ULT:
6660   case ICmpInst::ICMP_SLT:
6661     if (LoOverflow == +1)   // Low bound is greater than input range.
6662       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6663     if (LoOverflow == -1)   // Low bound is less than input range.
6664       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6665     return new ICmpInst(Pred, X, LoBound);
6666   case ICmpInst::ICMP_UGT:
6667   case ICmpInst::ICMP_SGT:
6668     if (HiOverflow == +1)       // High bound greater than input range.
6669       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6670     else if (HiOverflow == -1)  // High bound less than input range.
6671       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6672     if (Pred == ICmpInst::ICMP_UGT)
6673       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6674     else
6675       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6676   }
6677 }
6678
6679
6680 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6681 ///
6682 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6683                                                           Instruction *LHSI,
6684                                                           ConstantInt *RHS) {
6685   const APInt &RHSV = RHS->getValue();
6686   
6687   switch (LHSI->getOpcode()) {
6688   case Instruction::Trunc:
6689     if (ICI.isEquality() && LHSI->hasOneUse()) {
6690       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6691       // of the high bits truncated out of x are known.
6692       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6693              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6694       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6695       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6696       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6697       
6698       // If all the high bits are known, we can do this xform.
6699       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6700         // Pull in the high bits from known-ones set.
6701         APInt NewRHS(RHS->getValue());
6702         NewRHS.zext(SrcBits);
6703         NewRHS |= KnownOne;
6704         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6705                             ConstantInt::get(*Context, NewRHS));
6706       }
6707     }
6708     break;
6709       
6710   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6711     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6712       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6713       // fold the xor.
6714       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6715           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6716         Value *CompareVal = LHSI->getOperand(0);
6717         
6718         // If the sign bit of the XorCST is not set, there is no change to
6719         // the operation, just stop using the Xor.
6720         if (!XorCST->getValue().isNegative()) {
6721           ICI.setOperand(0, CompareVal);
6722           Worklist.Add(LHSI);
6723           return &ICI;
6724         }
6725         
6726         // Was the old condition true if the operand is positive?
6727         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6728         
6729         // If so, the new one isn't.
6730         isTrueIfPositive ^= true;
6731         
6732         if (isTrueIfPositive)
6733           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
6734                               SubOne(RHS));
6735         else
6736           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
6737                               AddOne(RHS));
6738       }
6739
6740       if (LHSI->hasOneUse()) {
6741         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6742         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6743           const APInt &SignBit = XorCST->getValue();
6744           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6745                                          ? ICI.getUnsignedPredicate()
6746                                          : ICI.getSignedPredicate();
6747           return new ICmpInst(Pred, LHSI->getOperand(0),
6748                               ConstantInt::get(*Context, RHSV ^ SignBit));
6749         }
6750
6751         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6752         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6753           const APInt &NotSignBit = XorCST->getValue();
6754           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6755                                          ? ICI.getUnsignedPredicate()
6756                                          : ICI.getSignedPredicate();
6757           Pred = ICI.getSwappedPredicate(Pred);
6758           return new ICmpInst(Pred, LHSI->getOperand(0),
6759                               ConstantInt::get(*Context, RHSV ^ NotSignBit));
6760         }
6761       }
6762     }
6763     break;
6764   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6765     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6766         LHSI->getOperand(0)->hasOneUse()) {
6767       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6768       
6769       // If the LHS is an AND of a truncating cast, we can widen the
6770       // and/compare to be the input width without changing the value
6771       // produced, eliminating a cast.
6772       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6773         // We can do this transformation if either the AND constant does not
6774         // have its sign bit set or if it is an equality comparison. 
6775         // Extending a relational comparison when we're checking the sign
6776         // bit would not work.
6777         if (Cast->hasOneUse() &&
6778             (ICI.isEquality() ||
6779              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6780           uint32_t BitWidth = 
6781             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6782           APInt NewCST = AndCST->getValue();
6783           NewCST.zext(BitWidth);
6784           APInt NewCI = RHSV;
6785           NewCI.zext(BitWidth);
6786           Value *NewAnd = 
6787             Builder->CreateAnd(Cast->getOperand(0),
6788                            ConstantInt::get(*Context, NewCST), LHSI->getName());
6789           return new ICmpInst(ICI.getPredicate(), NewAnd,
6790                               ConstantInt::get(*Context, NewCI));
6791         }
6792       }
6793       
6794       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6795       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6796       // happens a LOT in code produced by the C front-end, for bitfield
6797       // access.
6798       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6799       if (Shift && !Shift->isShift())
6800         Shift = 0;
6801       
6802       ConstantInt *ShAmt;
6803       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6804       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6805       const Type *AndTy = AndCST->getType();          // Type of the and.
6806       
6807       // We can fold this as long as we can't shift unknown bits
6808       // into the mask.  This can only happen with signed shift
6809       // rights, as they sign-extend.
6810       if (ShAmt) {
6811         bool CanFold = Shift->isLogicalShift();
6812         if (!CanFold) {
6813           // To test for the bad case of the signed shr, see if any
6814           // of the bits shifted in could be tested after the mask.
6815           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6816           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6817           
6818           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6819           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6820                AndCST->getValue()) == 0)
6821             CanFold = true;
6822         }
6823         
6824         if (CanFold) {
6825           Constant *NewCst;
6826           if (Shift->getOpcode() == Instruction::Shl)
6827             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6828           else
6829             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6830           
6831           // Check to see if we are shifting out any of the bits being
6832           // compared.
6833           if (ConstantExpr::get(Shift->getOpcode(),
6834                                        NewCst, ShAmt) != RHS) {
6835             // If we shifted bits out, the fold is not going to work out.
6836             // As a special case, check to see if this means that the
6837             // result is always true or false now.
6838             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6839               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6840             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6841               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6842           } else {
6843             ICI.setOperand(1, NewCst);
6844             Constant *NewAndCST;
6845             if (Shift->getOpcode() == Instruction::Shl)
6846               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6847             else
6848               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6849             LHSI->setOperand(1, NewAndCST);
6850             LHSI->setOperand(0, Shift->getOperand(0));
6851             Worklist.Add(Shift); // Shift is dead.
6852             return &ICI;
6853           }
6854         }
6855       }
6856       
6857       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6858       // preferable because it allows the C<<Y expression to be hoisted out
6859       // of a loop if Y is invariant and X is not.
6860       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6861           ICI.isEquality() && !Shift->isArithmeticShift() &&
6862           !isa<Constant>(Shift->getOperand(0))) {
6863         // Compute C << Y.
6864         Value *NS;
6865         if (Shift->getOpcode() == Instruction::LShr) {
6866           NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
6867         } else {
6868           // Insert a logical shift.
6869           NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
6870         }
6871         
6872         // Compute X & (C << Y).
6873         Value *NewAnd = 
6874           Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6875         
6876         ICI.setOperand(0, NewAnd);
6877         return &ICI;
6878       }
6879     }
6880     break;
6881     
6882   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6883     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6884     if (!ShAmt) break;
6885     
6886     uint32_t TypeBits = RHSV.getBitWidth();
6887     
6888     // Check that the shift amount is in range.  If not, don't perform
6889     // undefined shifts.  When the shift is visited it will be
6890     // simplified.
6891     if (ShAmt->uge(TypeBits))
6892       break;
6893     
6894     if (ICI.isEquality()) {
6895       // If we are comparing against bits always shifted out, the
6896       // comparison cannot succeed.
6897       Constant *Comp =
6898         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
6899                                                                  ShAmt);
6900       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6901         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6902         Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6903         return ReplaceInstUsesWith(ICI, Cst);
6904       }
6905       
6906       if (LHSI->hasOneUse()) {
6907         // Otherwise strength reduce the shift into an and.
6908         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6909         Constant *Mask =
6910           ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits, 
6911                                                        TypeBits-ShAmtVal));
6912         
6913         Value *And =
6914           Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
6915         return new ICmpInst(ICI.getPredicate(), And,
6916                             ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
6917       }
6918     }
6919     
6920     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6921     bool TrueIfSigned = false;
6922     if (LHSI->hasOneUse() &&
6923         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6924       // (X << 31) <s 0  --> (X&1) != 0
6925       Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
6926                                            (TypeBits-ShAmt->getZExtValue()-1));
6927       Value *And =
6928         Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
6929       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6930                           And, Constant::getNullValue(And->getType()));
6931     }
6932     break;
6933   }
6934     
6935   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6936   case Instruction::AShr: {
6937     // Only handle equality comparisons of shift-by-constant.
6938     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6939     if (!ShAmt || !ICI.isEquality()) break;
6940
6941     // Check that the shift amount is in range.  If not, don't perform
6942     // undefined shifts.  When the shift is visited it will be
6943     // simplified.
6944     uint32_t TypeBits = RHSV.getBitWidth();
6945     if (ShAmt->uge(TypeBits))
6946       break;
6947     
6948     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6949       
6950     // If we are comparing against bits always shifted out, the
6951     // comparison cannot succeed.
6952     APInt Comp = RHSV << ShAmtVal;
6953     if (LHSI->getOpcode() == Instruction::LShr)
6954       Comp = Comp.lshr(ShAmtVal);
6955     else
6956       Comp = Comp.ashr(ShAmtVal);
6957     
6958     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6959       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6960       Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6961       return ReplaceInstUsesWith(ICI, Cst);
6962     }
6963     
6964     // Otherwise, check to see if the bits shifted out are known to be zero.
6965     // If so, we can compare against the unshifted value:
6966     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6967     if (LHSI->hasOneUse() &&
6968         MaskedValueIsZero(LHSI->getOperand(0), 
6969                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6970       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6971                           ConstantExpr::getShl(RHS, ShAmt));
6972     }
6973       
6974     if (LHSI->hasOneUse()) {
6975       // Otherwise strength reduce the shift into an and.
6976       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6977       Constant *Mask = ConstantInt::get(*Context, Val);
6978       
6979       Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6980                                       Mask, LHSI->getName()+".mask");
6981       return new ICmpInst(ICI.getPredicate(), And,
6982                           ConstantExpr::getShl(RHS, ShAmt));
6983     }
6984     break;
6985   }
6986     
6987   case Instruction::SDiv:
6988   case Instruction::UDiv:
6989     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6990     // Fold this div into the comparison, producing a range check. 
6991     // Determine, based on the divide type, what the range is being 
6992     // checked.  If there is an overflow on the low or high side, remember 
6993     // it, otherwise compute the range [low, hi) bounding the new value.
6994     // See: InsertRangeTest above for the kinds of replacements possible.
6995     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6996       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6997                                           DivRHS))
6998         return R;
6999     break;
7000
7001   case Instruction::Add:
7002     // Fold: icmp pred (add, X, C1), C2
7003
7004     if (!ICI.isEquality()) {
7005       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7006       if (!LHSC) break;
7007       const APInt &LHSV = LHSC->getValue();
7008
7009       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7010                             .subtract(LHSV);
7011
7012       if (ICI.isSignedPredicate()) {
7013         if (CR.getLower().isSignBit()) {
7014           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7015                               ConstantInt::get(*Context, CR.getUpper()));
7016         } else if (CR.getUpper().isSignBit()) {
7017           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7018                               ConstantInt::get(*Context, CR.getLower()));
7019         }
7020       } else {
7021         if (CR.getLower().isMinValue()) {
7022           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7023                               ConstantInt::get(*Context, CR.getUpper()));
7024         } else if (CR.getUpper().isMinValue()) {
7025           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7026                               ConstantInt::get(*Context, CR.getLower()));
7027         }
7028       }
7029     }
7030     break;
7031   }
7032   
7033   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7034   if (ICI.isEquality()) {
7035     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7036     
7037     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7038     // the second operand is a constant, simplify a bit.
7039     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7040       switch (BO->getOpcode()) {
7041       case Instruction::SRem:
7042         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7043         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7044           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7045           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7046             Value *NewRem =
7047               Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7048                                   BO->getName());
7049             return new ICmpInst(ICI.getPredicate(), NewRem,
7050                                 Constant::getNullValue(BO->getType()));
7051           }
7052         }
7053         break;
7054       case Instruction::Add:
7055         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7056         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7057           if (BO->hasOneUse())
7058             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7059                                 ConstantExpr::getSub(RHS, BOp1C));
7060         } else if (RHSV == 0) {
7061           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7062           // efficiently invertible, or if the add has just this one use.
7063           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7064           
7065           if (Value *NegVal = dyn_castNegVal(BOp1))
7066             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
7067           else if (Value *NegVal = dyn_castNegVal(BOp0))
7068             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
7069           else if (BO->hasOneUse()) {
7070             Value *Neg = Builder->CreateNeg(BOp1);
7071             Neg->takeName(BO);
7072             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
7073           }
7074         }
7075         break;
7076       case Instruction::Xor:
7077         // For the xor case, we can xor two constants together, eliminating
7078         // the explicit xor.
7079         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7080           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
7081                               ConstantExpr::getXor(RHS, BOC));
7082         
7083         // FALLTHROUGH
7084       case Instruction::Sub:
7085         // Replace (([sub|xor] A, B) != 0) with (A != B)
7086         if (RHSV == 0)
7087           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7088                               BO->getOperand(1));
7089         break;
7090         
7091       case Instruction::Or:
7092         // If bits are being or'd in that are not present in the constant we
7093         // are comparing against, then the comparison could never succeed!
7094         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7095           Constant *NotCI = ConstantExpr::getNot(RHS);
7096           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7097             return ReplaceInstUsesWith(ICI,
7098                                        ConstantInt::get(Type::getInt1Ty(*Context), 
7099                                        isICMP_NE));
7100         }
7101         break;
7102         
7103       case Instruction::And:
7104         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7105           // If bits are being compared against that are and'd out, then the
7106           // comparison can never succeed!
7107           if ((RHSV & ~BOC->getValue()) != 0)
7108             return ReplaceInstUsesWith(ICI,
7109                                        ConstantInt::get(Type::getInt1Ty(*Context),
7110                                        isICMP_NE));
7111           
7112           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7113           if (RHS == BOC && RHSV.isPowerOf2())
7114             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7115                                 ICmpInst::ICMP_NE, LHSI,
7116                                 Constant::getNullValue(RHS->getType()));
7117           
7118           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7119           if (BOC->getValue().isSignBit()) {
7120             Value *X = BO->getOperand(0);
7121             Constant *Zero = Constant::getNullValue(X->getType());
7122             ICmpInst::Predicate pred = isICMP_NE ? 
7123               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7124             return new ICmpInst(pred, X, Zero);
7125           }
7126           
7127           // ((X & ~7) == 0) --> X < 8
7128           if (RHSV == 0 && isHighOnes(BOC)) {
7129             Value *X = BO->getOperand(0);
7130             Constant *NegX = ConstantExpr::getNeg(BOC);
7131             ICmpInst::Predicate pred = isICMP_NE ? 
7132               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7133             return new ICmpInst(pred, X, NegX);
7134           }
7135         }
7136       default: break;
7137       }
7138     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7139       // Handle icmp {eq|ne} <intrinsic>, intcst.
7140       if (II->getIntrinsicID() == Intrinsic::bswap) {
7141         Worklist.Add(II);
7142         ICI.setOperand(0, II->getOperand(1));
7143         ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7144         return &ICI;
7145       }
7146     }
7147   }
7148   return 0;
7149 }
7150
7151 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7152 /// We only handle extending casts so far.
7153 ///
7154 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7155   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7156   Value *LHSCIOp        = LHSCI->getOperand(0);
7157   const Type *SrcTy     = LHSCIOp->getType();
7158   const Type *DestTy    = LHSCI->getType();
7159   Value *RHSCIOp;
7160
7161   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7162   // integer type is the same size as the pointer type.
7163   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7164       TD->getPointerSizeInBits() ==
7165          cast<IntegerType>(DestTy)->getBitWidth()) {
7166     Value *RHSOp = 0;
7167     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7168       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7169     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7170       RHSOp = RHSC->getOperand(0);
7171       // If the pointer types don't match, insert a bitcast.
7172       if (LHSCIOp->getType() != RHSOp->getType())
7173         RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
7174     }
7175
7176     if (RHSOp)
7177       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7178   }
7179   
7180   // The code below only handles extension cast instructions, so far.
7181   // Enforce this.
7182   if (LHSCI->getOpcode() != Instruction::ZExt &&
7183       LHSCI->getOpcode() != Instruction::SExt)
7184     return 0;
7185
7186   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7187   bool isSignedCmp = ICI.isSignedPredicate();
7188
7189   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7190     // Not an extension from the same type?
7191     RHSCIOp = CI->getOperand(0);
7192     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7193       return 0;
7194     
7195     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7196     // and the other is a zext), then we can't handle this.
7197     if (CI->getOpcode() != LHSCI->getOpcode())
7198       return 0;
7199
7200     // Deal with equality cases early.
7201     if (ICI.isEquality())
7202       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7203
7204     // A signed comparison of sign extended values simplifies into a
7205     // signed comparison.
7206     if (isSignedCmp && isSignedExt)
7207       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7208
7209     // The other three cases all fold into an unsigned comparison.
7210     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7211   }
7212
7213   // If we aren't dealing with a constant on the RHS, exit early
7214   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7215   if (!CI)
7216     return 0;
7217
7218   // Compute the constant that would happen if we truncated to SrcTy then
7219   // reextended to DestTy.
7220   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7221   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7222                                                 Res1, DestTy);
7223
7224   // If the re-extended constant didn't change...
7225   if (Res2 == CI) {
7226     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7227     // For example, we might have:
7228     //    %A = sext i16 %X to i32
7229     //    %B = icmp ugt i32 %A, 1330
7230     // It is incorrect to transform this into 
7231     //    %B = icmp ugt i16 %X, 1330
7232     // because %A may have negative value. 
7233     //
7234     // However, we allow this when the compare is EQ/NE, because they are
7235     // signless.
7236     if (isSignedExt == isSignedCmp || ICI.isEquality())
7237       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7238     return 0;
7239   }
7240
7241   // The re-extended constant changed so the constant cannot be represented 
7242   // in the shorter type. Consequently, we cannot emit a simple comparison.
7243
7244   // First, handle some easy cases. We know the result cannot be equal at this
7245   // point so handle the ICI.isEquality() cases
7246   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7247     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7248   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7249     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7250
7251   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7252   // should have been folded away previously and not enter in here.
7253   Value *Result;
7254   if (isSignedCmp) {
7255     // We're performing a signed comparison.
7256     if (cast<ConstantInt>(CI)->getValue().isNegative())
7257       Result = ConstantInt::getFalse(*Context);          // X < (small) --> false
7258     else
7259       Result = ConstantInt::getTrue(*Context);           // X < (large) --> true
7260   } else {
7261     // We're performing an unsigned comparison.
7262     if (isSignedExt) {
7263       // We're performing an unsigned comp with a sign extended value.
7264       // This is true if the input is >= 0. [aka >s -1]
7265       Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7266       Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
7267     } else {
7268       // Unsigned extend & unsigned compare -> always true.
7269       Result = ConstantInt::getTrue(*Context);
7270     }
7271   }
7272
7273   // Finally, return the value computed.
7274   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7275       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7276     return ReplaceInstUsesWith(ICI, Result);
7277
7278   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7279           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7280          "ICmp should be folded!");
7281   if (Constant *CI = dyn_cast<Constant>(Result))
7282     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7283   return BinaryOperator::CreateNot(Result);
7284 }
7285
7286 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7287   return commonShiftTransforms(I);
7288 }
7289
7290 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7291   return commonShiftTransforms(I);
7292 }
7293
7294 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7295   if (Instruction *R = commonShiftTransforms(I))
7296     return R;
7297   
7298   Value *Op0 = I.getOperand(0);
7299   
7300   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7301   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7302     if (CSI->isAllOnesValue())
7303       return ReplaceInstUsesWith(I, CSI);
7304
7305   // See if we can turn a signed shr into an unsigned shr.
7306   if (MaskedValueIsZero(Op0,
7307                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7308     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7309
7310   // Arithmetic shifting an all-sign-bit value is a no-op.
7311   unsigned NumSignBits = ComputeNumSignBits(Op0);
7312   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7313     return ReplaceInstUsesWith(I, Op0);
7314
7315   return 0;
7316 }
7317
7318 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7319   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7320   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7321
7322   // shl X, 0 == X and shr X, 0 == X
7323   // shl 0, X == 0 and shr 0, X == 0
7324   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7325       Op0 == Constant::getNullValue(Op0->getType()))
7326     return ReplaceInstUsesWith(I, Op0);
7327   
7328   if (isa<UndefValue>(Op0)) {            
7329     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7330       return ReplaceInstUsesWith(I, Op0);
7331     else                                    // undef << X -> 0, undef >>u X -> 0
7332       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7333   }
7334   if (isa<UndefValue>(Op1)) {
7335     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7336       return ReplaceInstUsesWith(I, Op0);          
7337     else                                     // X << undef, X >>u undef -> 0
7338       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7339   }
7340
7341   // See if we can fold away this shift.
7342   if (SimplifyDemandedInstructionBits(I))
7343     return &I;
7344
7345   // Try to fold constant and into select arguments.
7346   if (isa<Constant>(Op0))
7347     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7348       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7349         return R;
7350
7351   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7352     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7353       return Res;
7354   return 0;
7355 }
7356
7357 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7358                                                BinaryOperator &I) {
7359   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7360
7361   // See if we can simplify any instructions used by the instruction whose sole 
7362   // purpose is to compute bits we don't care about.
7363   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7364   
7365   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7366   // a signed shift.
7367   //
7368   if (Op1->uge(TypeBits)) {
7369     if (I.getOpcode() != Instruction::AShr)
7370       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7371     else {
7372       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7373       return &I;
7374     }
7375   }
7376   
7377   // ((X*C1) << C2) == (X * (C1 << C2))
7378   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7379     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7380       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7381         return BinaryOperator::CreateMul(BO->getOperand(0),
7382                                         ConstantExpr::getShl(BOOp, Op1));
7383   
7384   // Try to fold constant and into select arguments.
7385   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7386     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7387       return R;
7388   if (isa<PHINode>(Op0))
7389     if (Instruction *NV = FoldOpIntoPhi(I))
7390       return NV;
7391   
7392   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7393   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7394     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7395     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7396     // place.  Don't try to do this transformation in this case.  Also, we
7397     // require that the input operand is a shift-by-constant so that we have
7398     // confidence that the shifts will get folded together.  We could do this
7399     // xform in more cases, but it is unlikely to be profitable.
7400     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7401         isa<ConstantInt>(TrOp->getOperand(1))) {
7402       // Okay, we'll do this xform.  Make the shift of shift.
7403       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7404       // (shift2 (shift1 & 0x00FF), c2)
7405       Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
7406
7407       // For logical shifts, the truncation has the effect of making the high
7408       // part of the register be zeros.  Emulate this by inserting an AND to
7409       // clear the top bits as needed.  This 'and' will usually be zapped by
7410       // other xforms later if dead.
7411       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7412       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7413       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7414       
7415       // The mask we constructed says what the trunc would do if occurring
7416       // between the shifts.  We want to know the effect *after* the second
7417       // shift.  We know that it is a logical shift by a constant, so adjust the
7418       // mask as appropriate.
7419       if (I.getOpcode() == Instruction::Shl)
7420         MaskV <<= Op1->getZExtValue();
7421       else {
7422         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7423         MaskV = MaskV.lshr(Op1->getZExtValue());
7424       }
7425
7426       // shift1 & 0x00FF
7427       Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7428                                       TI->getName());
7429
7430       // Return the value truncated to the interesting size.
7431       return new TruncInst(And, I.getType());
7432     }
7433   }
7434   
7435   if (Op0->hasOneUse()) {
7436     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7437       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7438       Value *V1, *V2;
7439       ConstantInt *CC;
7440       switch (Op0BO->getOpcode()) {
7441         default: break;
7442         case Instruction::Add:
7443         case Instruction::And:
7444         case Instruction::Or:
7445         case Instruction::Xor: {
7446           // These operators commute.
7447           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7448           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7449               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7450                     m_Specific(Op1)))) {
7451             Value *YS =         // (Y << C)
7452               Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7453             // (X + (Y << C))
7454             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7455                                             Op0BO->getOperand(1)->getName());
7456             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7457             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7458                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7459           }
7460           
7461           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7462           Value *Op0BOOp1 = Op0BO->getOperand(1);
7463           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7464               match(Op0BOOp1, 
7465                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7466                           m_ConstantInt(CC))) &&
7467               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7468             Value *YS =   // (Y << C)
7469               Builder->CreateShl(Op0BO->getOperand(0), Op1,
7470                                            Op0BO->getName());
7471             // X & (CC << C)
7472             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7473                                            V1->getName()+".mask");
7474             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7475           }
7476         }
7477           
7478         // FALL THROUGH.
7479         case Instruction::Sub: {
7480           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7481           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7482               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7483                     m_Specific(Op1)))) {
7484             Value *YS =  // (Y << C)
7485               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7486             // (X + (Y << C))
7487             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7488                                             Op0BO->getOperand(0)->getName());
7489             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7490             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7491                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7492           }
7493           
7494           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7495           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7496               match(Op0BO->getOperand(0),
7497                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7498                           m_ConstantInt(CC))) && V2 == Op1 &&
7499               cast<BinaryOperator>(Op0BO->getOperand(0))
7500                   ->getOperand(0)->hasOneUse()) {
7501             Value *YS = // (Y << C)
7502               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7503             // X & (CC << C)
7504             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7505                                            V1->getName()+".mask");
7506             
7507             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7508           }
7509           
7510           break;
7511         }
7512       }
7513       
7514       
7515       // If the operand is an bitwise operator with a constant RHS, and the
7516       // shift is the only use, we can pull it out of the shift.
7517       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7518         bool isValid = true;     // Valid only for And, Or, Xor
7519         bool highBitSet = false; // Transform if high bit of constant set?
7520         
7521         switch (Op0BO->getOpcode()) {
7522           default: isValid = false; break;   // Do not perform transform!
7523           case Instruction::Add:
7524             isValid = isLeftShift;
7525             break;
7526           case Instruction::Or:
7527           case Instruction::Xor:
7528             highBitSet = false;
7529             break;
7530           case Instruction::And:
7531             highBitSet = true;
7532             break;
7533         }
7534         
7535         // If this is a signed shift right, and the high bit is modified
7536         // by the logical operation, do not perform the transformation.
7537         // The highBitSet boolean indicates the value of the high bit of
7538         // the constant which would cause it to be modified for this
7539         // operation.
7540         //
7541         if (isValid && I.getOpcode() == Instruction::AShr)
7542           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7543         
7544         if (isValid) {
7545           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7546           
7547           Value *NewShift =
7548             Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
7549           NewShift->takeName(Op0BO);
7550           
7551           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7552                                         NewRHS);
7553         }
7554       }
7555     }
7556   }
7557   
7558   // Find out if this is a shift of a shift by a constant.
7559   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7560   if (ShiftOp && !ShiftOp->isShift())
7561     ShiftOp = 0;
7562   
7563   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7564     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7565     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7566     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7567     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7568     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7569     Value *X = ShiftOp->getOperand(0);
7570     
7571     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7572     
7573     const IntegerType *Ty = cast<IntegerType>(I.getType());
7574     
7575     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7576     if (I.getOpcode() == ShiftOp->getOpcode()) {
7577       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7578       // saturates.
7579       if (AmtSum >= TypeBits) {
7580         if (I.getOpcode() != Instruction::AShr)
7581           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7582         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7583       }
7584       
7585       return BinaryOperator::Create(I.getOpcode(), X,
7586                                     ConstantInt::get(Ty, AmtSum));
7587     }
7588     
7589     if (ShiftOp->getOpcode() == Instruction::LShr &&
7590         I.getOpcode() == Instruction::AShr) {
7591       if (AmtSum >= TypeBits)
7592         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7593       
7594       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7595       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7596     }
7597     
7598     if (ShiftOp->getOpcode() == Instruction::AShr &&
7599         I.getOpcode() == Instruction::LShr) {
7600       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7601       if (AmtSum >= TypeBits)
7602         AmtSum = TypeBits-1;
7603       
7604       Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7605
7606       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7607       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7608     }
7609     
7610     // Okay, if we get here, one shift must be left, and the other shift must be
7611     // right.  See if the amounts are equal.
7612     if (ShiftAmt1 == ShiftAmt2) {
7613       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7614       if (I.getOpcode() == Instruction::Shl) {
7615         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7616         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7617       }
7618       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7619       if (I.getOpcode() == Instruction::LShr) {
7620         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7621         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7622       }
7623       // We can simplify ((X << C) >>s C) into a trunc + sext.
7624       // NOTE: we could do this for any C, but that would make 'unusual' integer
7625       // types.  For now, just stick to ones well-supported by the code
7626       // generators.
7627       const Type *SExtType = 0;
7628       switch (Ty->getBitWidth() - ShiftAmt1) {
7629       case 1  :
7630       case 8  :
7631       case 16 :
7632       case 32 :
7633       case 64 :
7634       case 128:
7635         SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
7636         break;
7637       default: break;
7638       }
7639       if (SExtType)
7640         return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
7641       // Otherwise, we can't handle it yet.
7642     } else if (ShiftAmt1 < ShiftAmt2) {
7643       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7644       
7645       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7646       if (I.getOpcode() == Instruction::Shl) {
7647         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7648                ShiftOp->getOpcode() == Instruction::AShr);
7649         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7650         
7651         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7652         return BinaryOperator::CreateAnd(Shift,
7653                                          ConstantInt::get(*Context, Mask));
7654       }
7655       
7656       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7657       if (I.getOpcode() == Instruction::LShr) {
7658         assert(ShiftOp->getOpcode() == Instruction::Shl);
7659         Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7660         
7661         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7662         return BinaryOperator::CreateAnd(Shift,
7663                                          ConstantInt::get(*Context, Mask));
7664       }
7665       
7666       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7667     } else {
7668       assert(ShiftAmt2 < ShiftAmt1);
7669       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7670
7671       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7672       if (I.getOpcode() == Instruction::Shl) {
7673         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7674                ShiftOp->getOpcode() == Instruction::AShr);
7675         Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7676                                             ConstantInt::get(Ty, ShiftDiff));
7677         
7678         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7679         return BinaryOperator::CreateAnd(Shift,
7680                                          ConstantInt::get(*Context, Mask));
7681       }
7682       
7683       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7684       if (I.getOpcode() == Instruction::LShr) {
7685         assert(ShiftOp->getOpcode() == Instruction::Shl);
7686         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7687         
7688         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7689         return BinaryOperator::CreateAnd(Shift,
7690                                          ConstantInt::get(*Context, Mask));
7691       }
7692       
7693       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7694     }
7695   }
7696   return 0;
7697 }
7698
7699
7700 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7701 /// expression.  If so, decompose it, returning some value X, such that Val is
7702 /// X*Scale+Offset.
7703 ///
7704 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7705                                         int &Offset, LLVMContext *Context) {
7706   assert(Val->getType() == Type::getInt32Ty(*Context) && 
7707          "Unexpected allocation size type!");
7708   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7709     Offset = CI->getZExtValue();
7710     Scale  = 0;
7711     return ConstantInt::get(Type::getInt32Ty(*Context), 0);
7712   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7713     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7714       if (I->getOpcode() == Instruction::Shl) {
7715         // This is a value scaled by '1 << the shift amt'.
7716         Scale = 1U << RHS->getZExtValue();
7717         Offset = 0;
7718         return I->getOperand(0);
7719       } else if (I->getOpcode() == Instruction::Mul) {
7720         // This value is scaled by 'RHS'.
7721         Scale = RHS->getZExtValue();
7722         Offset = 0;
7723         return I->getOperand(0);
7724       } else if (I->getOpcode() == Instruction::Add) {
7725         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7726         // where C1 is divisible by C2.
7727         unsigned SubScale;
7728         Value *SubVal = 
7729           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7730                                     Offset, Context);
7731         Offset += RHS->getZExtValue();
7732         Scale = SubScale;
7733         return SubVal;
7734       }
7735     }
7736   }
7737
7738   // Otherwise, we can't look past this.
7739   Scale = 1;
7740   Offset = 0;
7741   return Val;
7742 }
7743
7744
7745 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7746 /// try to eliminate the cast by moving the type information into the alloc.
7747 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7748                                                    AllocationInst &AI) {
7749   const PointerType *PTy = cast<PointerType>(CI.getType());
7750   
7751   BuilderTy AllocaBuilder(*Builder);
7752   AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7753   
7754   // Remove any uses of AI that are dead.
7755   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7756   
7757   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7758     Instruction *User = cast<Instruction>(*UI++);
7759     if (isInstructionTriviallyDead(User)) {
7760       while (UI != E && *UI == User)
7761         ++UI; // If this instruction uses AI more than once, don't break UI.
7762       
7763       ++NumDeadInst;
7764       DEBUG(errs() << "IC: DCE: " << *User << '\n');
7765       EraseInstFromFunction(*User);
7766     }
7767   }
7768
7769   // This requires TargetData to get the alloca alignment and size information.
7770   if (!TD) return 0;
7771
7772   // Get the type really allocated and the type casted to.
7773   const Type *AllocElTy = AI.getAllocatedType();
7774   const Type *CastElTy = PTy->getElementType();
7775   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7776
7777   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7778   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7779   if (CastElTyAlign < AllocElTyAlign) return 0;
7780
7781   // If the allocation has multiple uses, only promote it if we are strictly
7782   // increasing the alignment of the resultant allocation.  If we keep it the
7783   // same, we open the door to infinite loops of various kinds.  (A reference
7784   // from a dbg.declare doesn't count as a use for this purpose.)
7785   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7786       CastElTyAlign == AllocElTyAlign) return 0;
7787
7788   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7789   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7790   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7791
7792   // See if we can satisfy the modulus by pulling a scale out of the array
7793   // size argument.
7794   unsigned ArraySizeScale;
7795   int ArrayOffset;
7796   Value *NumElements = // See if the array size is a decomposable linear expr.
7797     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7798                               ArrayOffset, Context);
7799  
7800   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7801   // do the xform.
7802   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7803       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7804
7805   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7806   Value *Amt = 0;
7807   if (Scale == 1) {
7808     Amt = NumElements;
7809   } else {
7810     Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
7811     // Insert before the alloca, not before the cast.
7812     Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
7813   }
7814   
7815   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7816     Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
7817     Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
7818   }
7819   
7820   AllocationInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7821   New->setAlignment(AI.getAlignment());
7822   New->takeName(&AI);
7823   
7824   // If the allocation has one real use plus a dbg.declare, just remove the
7825   // declare.
7826   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7827     EraseInstFromFunction(*DI);
7828   }
7829   // If the allocation has multiple real uses, insert a cast and change all
7830   // things that used it to use the new cast.  This will also hack on CI, but it
7831   // will die soon.
7832   else if (!AI.hasOneUse()) {
7833     // New is the allocation instruction, pointer typed. AI is the original
7834     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7835     Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
7836     AI.replaceAllUsesWith(NewCast);
7837   }
7838   return ReplaceInstUsesWith(CI, New);
7839 }
7840
7841 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7842 /// and return it as type Ty without inserting any new casts and without
7843 /// changing the computed value.  This is used by code that tries to decide
7844 /// whether promoting or shrinking integer operations to wider or smaller types
7845 /// will allow us to eliminate a truncate or extend.
7846 ///
7847 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7848 /// extension operation if Ty is larger.
7849 ///
7850 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7851 /// should return true if trunc(V) can be computed by computing V in the smaller
7852 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7853 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7854 /// efficiently truncated.
7855 ///
7856 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7857 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7858 /// the final result.
7859 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7860                                               unsigned CastOpc,
7861                                               int &NumCastsRemoved){
7862   // We can always evaluate constants in another type.
7863   if (isa<Constant>(V))
7864     return true;
7865   
7866   Instruction *I = dyn_cast<Instruction>(V);
7867   if (!I) return false;
7868   
7869   const Type *OrigTy = V->getType();
7870   
7871   // If this is an extension or truncate, we can often eliminate it.
7872   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7873     // If this is a cast from the destination type, we can trivially eliminate
7874     // it, and this will remove a cast overall.
7875     if (I->getOperand(0)->getType() == Ty) {
7876       // If the first operand is itself a cast, and is eliminable, do not count
7877       // this as an eliminable cast.  We would prefer to eliminate those two
7878       // casts first.
7879       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7880         ++NumCastsRemoved;
7881       return true;
7882     }
7883   }
7884
7885   // We can't extend or shrink something that has multiple uses: doing so would
7886   // require duplicating the instruction in general, which isn't profitable.
7887   if (!I->hasOneUse()) return false;
7888
7889   unsigned Opc = I->getOpcode();
7890   switch (Opc) {
7891   case Instruction::Add:
7892   case Instruction::Sub:
7893   case Instruction::Mul:
7894   case Instruction::And:
7895   case Instruction::Or:
7896   case Instruction::Xor:
7897     // These operators can all arbitrarily be extended or truncated.
7898     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7899                                       NumCastsRemoved) &&
7900            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7901                                       NumCastsRemoved);
7902
7903   case Instruction::UDiv:
7904   case Instruction::URem: {
7905     // UDiv and URem can be truncated if all the truncated bits are zero.
7906     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7907     uint32_t BitWidth = Ty->getScalarSizeInBits();
7908     if (BitWidth < OrigBitWidth) {
7909       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7910       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7911           MaskedValueIsZero(I->getOperand(1), Mask)) {
7912         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7913                                           NumCastsRemoved) &&
7914                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7915                                           NumCastsRemoved);
7916       }
7917     }
7918     break;
7919   }
7920   case Instruction::Shl:
7921     // If we are truncating the result of this SHL, and if it's a shift of a
7922     // constant amount, we can always perform a SHL in a smaller type.
7923     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7924       uint32_t BitWidth = Ty->getScalarSizeInBits();
7925       if (BitWidth < OrigTy->getScalarSizeInBits() &&
7926           CI->getLimitedValue(BitWidth) < BitWidth)
7927         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7928                                           NumCastsRemoved);
7929     }
7930     break;
7931   case Instruction::LShr:
7932     // If this is a truncate of a logical shr, we can truncate it to a smaller
7933     // lshr iff we know that the bits we would otherwise be shifting in are
7934     // already zeros.
7935     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7936       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7937       uint32_t BitWidth = Ty->getScalarSizeInBits();
7938       if (BitWidth < OrigBitWidth &&
7939           MaskedValueIsZero(I->getOperand(0),
7940             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7941           CI->getLimitedValue(BitWidth) < BitWidth) {
7942         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7943                                           NumCastsRemoved);
7944       }
7945     }
7946     break;
7947   case Instruction::ZExt:
7948   case Instruction::SExt:
7949   case Instruction::Trunc:
7950     // If this is the same kind of case as our original (e.g. zext+zext), we
7951     // can safely replace it.  Note that replacing it does not reduce the number
7952     // of casts in the input.
7953     if (Opc == CastOpc)
7954       return true;
7955
7956     // sext (zext ty1), ty2 -> zext ty2
7957     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7958       return true;
7959     break;
7960   case Instruction::Select: {
7961     SelectInst *SI = cast<SelectInst>(I);
7962     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7963                                       NumCastsRemoved) &&
7964            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7965                                       NumCastsRemoved);
7966   }
7967   case Instruction::PHI: {
7968     // We can change a phi if we can change all operands.
7969     PHINode *PN = cast<PHINode>(I);
7970     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7971       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7972                                       NumCastsRemoved))
7973         return false;
7974     return true;
7975   }
7976   default:
7977     // TODO: Can handle more cases here.
7978     break;
7979   }
7980   
7981   return false;
7982 }
7983
7984 /// EvaluateInDifferentType - Given an expression that 
7985 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7986 /// evaluate the expression.
7987 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7988                                              bool isSigned) {
7989   if (Constant *C = dyn_cast<Constant>(V))
7990     return ConstantExpr::getIntegerCast(C, Ty,
7991                                                isSigned /*Sext or ZExt*/);
7992
7993   // Otherwise, it must be an instruction.
7994   Instruction *I = cast<Instruction>(V);
7995   Instruction *Res = 0;
7996   unsigned Opc = I->getOpcode();
7997   switch (Opc) {
7998   case Instruction::Add:
7999   case Instruction::Sub:
8000   case Instruction::Mul:
8001   case Instruction::And:
8002   case Instruction::Or:
8003   case Instruction::Xor:
8004   case Instruction::AShr:
8005   case Instruction::LShr:
8006   case Instruction::Shl:
8007   case Instruction::UDiv:
8008   case Instruction::URem: {
8009     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8010     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8011     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8012     break;
8013   }    
8014   case Instruction::Trunc:
8015   case Instruction::ZExt:
8016   case Instruction::SExt:
8017     // If the source type of the cast is the type we're trying for then we can
8018     // just return the source.  There's no need to insert it because it is not
8019     // new.
8020     if (I->getOperand(0)->getType() == Ty)
8021       return I->getOperand(0);
8022     
8023     // Otherwise, must be the same type of cast, so just reinsert a new one.
8024     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8025                            Ty);
8026     break;
8027   case Instruction::Select: {
8028     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8029     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8030     Res = SelectInst::Create(I->getOperand(0), True, False);
8031     break;
8032   }
8033   case Instruction::PHI: {
8034     PHINode *OPN = cast<PHINode>(I);
8035     PHINode *NPN = PHINode::Create(Ty);
8036     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8037       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8038       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8039     }
8040     Res = NPN;
8041     break;
8042   }
8043   default: 
8044     // TODO: Can handle more cases here.
8045     llvm_unreachable("Unreachable!");
8046     break;
8047   }
8048   
8049   Res->takeName(I);
8050   return InsertNewInstBefore(Res, *I);
8051 }
8052
8053 /// @brief Implement the transforms common to all CastInst visitors.
8054 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8055   Value *Src = CI.getOperand(0);
8056
8057   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8058   // eliminate it now.
8059   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8060     if (Instruction::CastOps opc = 
8061         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8062       // The first cast (CSrc) is eliminable so we need to fix up or replace
8063       // the second cast (CI). CSrc will then have a good chance of being dead.
8064       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8065     }
8066   }
8067
8068   // If we are casting a select then fold the cast into the select
8069   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8070     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8071       return NV;
8072
8073   // If we are casting a PHI then fold the cast into the PHI
8074   if (isa<PHINode>(Src))
8075     if (Instruction *NV = FoldOpIntoPhi(CI))
8076       return NV;
8077   
8078   return 0;
8079 }
8080
8081 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8082 /// or not there is a sequence of GEP indices into the type that will land us at
8083 /// the specified offset.  If so, fill them into NewIndices and return the
8084 /// resultant element type, otherwise return null.
8085 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8086                                        SmallVectorImpl<Value*> &NewIndices,
8087                                        const TargetData *TD,
8088                                        LLVMContext *Context) {
8089   if (!TD) return 0;
8090   if (!Ty->isSized()) return 0;
8091   
8092   // Start with the index over the outer type.  Note that the type size
8093   // might be zero (even if the offset isn't zero) if the indexed type
8094   // is something like [0 x {int, int}]
8095   const Type *IntPtrTy = TD->getIntPtrType(*Context);
8096   int64_t FirstIdx = 0;
8097   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8098     FirstIdx = Offset/TySize;
8099     Offset -= FirstIdx*TySize;
8100     
8101     // Handle hosts where % returns negative instead of values [0..TySize).
8102     if (Offset < 0) {
8103       --FirstIdx;
8104       Offset += TySize;
8105       assert(Offset >= 0);
8106     }
8107     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8108   }
8109   
8110   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8111     
8112   // Index into the types.  If we fail, set OrigBase to null.
8113   while (Offset) {
8114     // Indexing into tail padding between struct/array elements.
8115     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8116       return 0;
8117     
8118     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8119       const StructLayout *SL = TD->getStructLayout(STy);
8120       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8121              "Offset must stay within the indexed type");
8122       
8123       unsigned Elt = SL->getElementContainingOffset(Offset);
8124       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8125       
8126       Offset -= SL->getElementOffset(Elt);
8127       Ty = STy->getElementType(Elt);
8128     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8129       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8130       assert(EltSize && "Cannot index into a zero-sized array");
8131       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8132       Offset %= EltSize;
8133       Ty = AT->getElementType();
8134     } else {
8135       // Otherwise, we can't index into the middle of this atomic type, bail.
8136       return 0;
8137     }
8138   }
8139   
8140   return Ty;
8141 }
8142
8143 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8144 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8145   Value *Src = CI.getOperand(0);
8146   
8147   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8148     // If casting the result of a getelementptr instruction with no offset, turn
8149     // this into a cast of the original pointer!
8150     if (GEP->hasAllZeroIndices()) {
8151       // Changing the cast operand is usually not a good idea but it is safe
8152       // here because the pointer operand is being replaced with another 
8153       // pointer operand so the opcode doesn't need to change.
8154       Worklist.Add(GEP);
8155       CI.setOperand(0, GEP->getOperand(0));
8156       return &CI;
8157     }
8158     
8159     // If the GEP has a single use, and the base pointer is a bitcast, and the
8160     // GEP computes a constant offset, see if we can convert these three
8161     // instructions into fewer.  This typically happens with unions and other
8162     // non-type-safe code.
8163     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8164       if (GEP->hasAllConstantIndices()) {
8165         // We are guaranteed to get a constant from EmitGEPOffset.
8166         ConstantInt *OffsetV =
8167                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8168         int64_t Offset = OffsetV->getSExtValue();
8169         
8170         // Get the base pointer input of the bitcast, and the type it points to.
8171         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8172         const Type *GEPIdxTy =
8173           cast<PointerType>(OrigBase->getType())->getElementType();
8174         SmallVector<Value*, 8> NewIndices;
8175         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8176           // If we were able to index down into an element, create the GEP
8177           // and bitcast the result.  This eliminates one bitcast, potentially
8178           // two.
8179           Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8180             Builder->CreateInBoundsGEP(OrigBase,
8181                                        NewIndices.begin(), NewIndices.end()) :
8182             Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
8183           NGEP->takeName(GEP);
8184           
8185           if (isa<BitCastInst>(CI))
8186             return new BitCastInst(NGEP, CI.getType());
8187           assert(isa<PtrToIntInst>(CI));
8188           return new PtrToIntInst(NGEP, CI.getType());
8189         }
8190       }      
8191     }
8192   }
8193     
8194   return commonCastTransforms(CI);
8195 }
8196
8197 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8198 /// type like i42.  We don't want to introduce operations on random non-legal
8199 /// integer types where they don't already exist in the code.  In the future,
8200 /// we should consider making this based off target-data, so that 32-bit targets
8201 /// won't get i64 operations etc.
8202 static bool isSafeIntegerType(const Type *Ty) {
8203   switch (Ty->getPrimitiveSizeInBits()) {
8204   case 8:
8205   case 16:
8206   case 32:
8207   case 64:
8208     return true;
8209   default: 
8210     return false;
8211   }
8212 }
8213
8214 /// commonIntCastTransforms - This function implements the common transforms
8215 /// for trunc, zext, and sext.
8216 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8217   if (Instruction *Result = commonCastTransforms(CI))
8218     return Result;
8219
8220   Value *Src = CI.getOperand(0);
8221   const Type *SrcTy = Src->getType();
8222   const Type *DestTy = CI.getType();
8223   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8224   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8225
8226   // See if we can simplify any instructions used by the LHS whose sole 
8227   // purpose is to compute bits we don't care about.
8228   if (SimplifyDemandedInstructionBits(CI))
8229     return &CI;
8230
8231   // If the source isn't an instruction or has more than one use then we
8232   // can't do anything more. 
8233   Instruction *SrcI = dyn_cast<Instruction>(Src);
8234   if (!SrcI || !Src->hasOneUse())
8235     return 0;
8236
8237   // Attempt to propagate the cast into the instruction for int->int casts.
8238   int NumCastsRemoved = 0;
8239   // Only do this if the dest type is a simple type, don't convert the
8240   // expression tree to something weird like i93 unless the source is also
8241   // strange.
8242   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8243        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8244       CanEvaluateInDifferentType(SrcI, DestTy,
8245                                  CI.getOpcode(), NumCastsRemoved)) {
8246     // If this cast is a truncate, evaluting in a different type always
8247     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8248     // we need to do an AND to maintain the clear top-part of the computation,
8249     // so we require that the input have eliminated at least one cast.  If this
8250     // is a sign extension, we insert two new casts (to do the extension) so we
8251     // require that two casts have been eliminated.
8252     bool DoXForm = false;
8253     bool JustReplace = false;
8254     switch (CI.getOpcode()) {
8255     default:
8256       // All the others use floating point so we shouldn't actually 
8257       // get here because of the check above.
8258       llvm_unreachable("Unknown cast type");
8259     case Instruction::Trunc:
8260       DoXForm = true;
8261       break;
8262     case Instruction::ZExt: {
8263       DoXForm = NumCastsRemoved >= 1;
8264       if (!DoXForm && 0) {
8265         // If it's unnecessary to issue an AND to clear the high bits, it's
8266         // always profitable to do this xform.
8267         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8268         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8269         if (MaskedValueIsZero(TryRes, Mask))
8270           return ReplaceInstUsesWith(CI, TryRes);
8271         
8272         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8273           if (TryI->use_empty())
8274             EraseInstFromFunction(*TryI);
8275       }
8276       break;
8277     }
8278     case Instruction::SExt: {
8279       DoXForm = NumCastsRemoved >= 2;
8280       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8281         // If we do not have to emit the truncate + sext pair, then it's always
8282         // profitable to do this xform.
8283         //
8284         // It's not safe to eliminate the trunc + sext pair if one of the
8285         // eliminated cast is a truncate. e.g.
8286         // t2 = trunc i32 t1 to i16
8287         // t3 = sext i16 t2 to i32
8288         // !=
8289         // i32 t1
8290         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8291         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8292         if (NumSignBits > (DestBitSize - SrcBitSize))
8293           return ReplaceInstUsesWith(CI, TryRes);
8294         
8295         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8296           if (TryI->use_empty())
8297             EraseInstFromFunction(*TryI);
8298       }
8299       break;
8300     }
8301     }
8302     
8303     if (DoXForm) {
8304       DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8305             " to avoid cast: " << CI);
8306       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8307                                            CI.getOpcode() == Instruction::SExt);
8308       if (JustReplace)
8309         // Just replace this cast with the result.
8310         return ReplaceInstUsesWith(CI, Res);
8311
8312       assert(Res->getType() == DestTy);
8313       switch (CI.getOpcode()) {
8314       default: llvm_unreachable("Unknown cast type!");
8315       case Instruction::Trunc:
8316         // Just replace this cast with the result.
8317         return ReplaceInstUsesWith(CI, Res);
8318       case Instruction::ZExt: {
8319         assert(SrcBitSize < DestBitSize && "Not a zext?");
8320
8321         // If the high bits are already zero, just replace this cast with the
8322         // result.
8323         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8324         if (MaskedValueIsZero(Res, Mask))
8325           return ReplaceInstUsesWith(CI, Res);
8326
8327         // We need to emit an AND to clear the high bits.
8328         Constant *C = ConstantInt::get(*Context, 
8329                                  APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8330         return BinaryOperator::CreateAnd(Res, C);
8331       }
8332       case Instruction::SExt: {
8333         // If the high bits are already filled with sign bit, just replace this
8334         // cast with the result.
8335         unsigned NumSignBits = ComputeNumSignBits(Res);
8336         if (NumSignBits > (DestBitSize - SrcBitSize))
8337           return ReplaceInstUsesWith(CI, Res);
8338
8339         // We need to emit a cast to truncate, then a cast to sext.
8340         return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
8341       }
8342       }
8343     }
8344   }
8345   
8346   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8347   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8348
8349   switch (SrcI->getOpcode()) {
8350   case Instruction::Add:
8351   case Instruction::Mul:
8352   case Instruction::And:
8353   case Instruction::Or:
8354   case Instruction::Xor:
8355     // If we are discarding information, rewrite.
8356     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8357       // Don't insert two casts unless at least one can be eliminated.
8358       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8359           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8360         Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8361         Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8362         return BinaryOperator::Create(
8363             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8364       }
8365     }
8366
8367     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8368     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8369         SrcI->getOpcode() == Instruction::Xor &&
8370         Op1 == ConstantInt::getTrue(*Context) &&
8371         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8372       Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
8373       return BinaryOperator::CreateXor(New,
8374                                       ConstantInt::get(CI.getType(), 1));
8375     }
8376     break;
8377
8378   case Instruction::Shl: {
8379     // Canonicalize trunc inside shl, if we can.
8380     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8381     if (CI && DestBitSize < SrcBitSize &&
8382         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8383       Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8384       Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8385       return BinaryOperator::CreateShl(Op0c, Op1c);
8386     }
8387     break;
8388   }
8389   }
8390   return 0;
8391 }
8392
8393 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8394   if (Instruction *Result = commonIntCastTransforms(CI))
8395     return Result;
8396   
8397   Value *Src = CI.getOperand(0);
8398   const Type *Ty = CI.getType();
8399   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8400   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8401
8402   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8403   if (DestBitWidth == 1) {
8404     Constant *One = ConstantInt::get(Src->getType(), 1);
8405     Src = Builder->CreateAnd(Src, One, "tmp");
8406     Value *Zero = Constant::getNullValue(Src->getType());
8407     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8408   }
8409
8410   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8411   ConstantInt *ShAmtV = 0;
8412   Value *ShiftOp = 0;
8413   if (Src->hasOneUse() &&
8414       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8415     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8416     
8417     // Get a mask for the bits shifting in.
8418     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8419     if (MaskedValueIsZero(ShiftOp, Mask)) {
8420       if (ShAmt >= DestBitWidth)        // All zeros.
8421         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8422       
8423       // Okay, we can shrink this.  Truncate the input, then return a new
8424       // shift.
8425       Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
8426       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8427       return BinaryOperator::CreateLShr(V1, V2);
8428     }
8429   }
8430   
8431   return 0;
8432 }
8433
8434 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8435 /// in order to eliminate the icmp.
8436 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8437                                              bool DoXform) {
8438   // If we are just checking for a icmp eq of a single bit and zext'ing it
8439   // to an integer, then shift the bit to the appropriate place and then
8440   // cast to integer to avoid the comparison.
8441   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8442     const APInt &Op1CV = Op1C->getValue();
8443       
8444     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8445     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8446     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8447         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8448       if (!DoXform) return ICI;
8449
8450       Value *In = ICI->getOperand(0);
8451       Value *Sh = ConstantInt::get(In->getType(),
8452                                    In->getType()->getScalarSizeInBits()-1);
8453       In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
8454       if (In->getType() != CI.getType())
8455         In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
8456
8457       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8458         Constant *One = ConstantInt::get(In->getType(), 1);
8459         In = Builder->CreateXor(In, One, In->getName()+".not");
8460       }
8461
8462       return ReplaceInstUsesWith(CI, In);
8463     }
8464       
8465       
8466       
8467     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8468     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8469     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8470     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8471     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8472     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8473     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8474     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8475     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8476         // This only works for EQ and NE
8477         ICI->isEquality()) {
8478       // If Op1C some other power of two, convert:
8479       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8480       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8481       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8482       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8483         
8484       APInt KnownZeroMask(~KnownZero);
8485       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8486         if (!DoXform) return ICI;
8487
8488         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8489         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8490           // (X&4) == 2 --> false
8491           // (X&4) != 2 --> true
8492           Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8493           Res = ConstantExpr::getZExt(Res, CI.getType());
8494           return ReplaceInstUsesWith(CI, Res);
8495         }
8496           
8497         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8498         Value *In = ICI->getOperand(0);
8499         if (ShiftAmt) {
8500           // Perform a logical shr by shiftamt.
8501           // Insert the shift to put the result in the low bit.
8502           In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8503                                    In->getName()+".lobit");
8504         }
8505           
8506         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8507           Constant *One = ConstantInt::get(In->getType(), 1);
8508           In = Builder->CreateXor(In, One, "tmp");
8509         }
8510           
8511         if (CI.getType() == In->getType())
8512           return ReplaceInstUsesWith(CI, In);
8513         else
8514           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8515       }
8516     }
8517   }
8518
8519   return 0;
8520 }
8521
8522 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8523   // If one of the common conversion will work ..
8524   if (Instruction *Result = commonIntCastTransforms(CI))
8525     return Result;
8526
8527   Value *Src = CI.getOperand(0);
8528
8529   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8530   // types and if the sizes are just right we can convert this into a logical
8531   // 'and' which will be much cheaper than the pair of casts.
8532   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8533     // Get the sizes of the types involved.  We know that the intermediate type
8534     // will be smaller than A or C, but don't know the relation between A and C.
8535     Value *A = CSrc->getOperand(0);
8536     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8537     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8538     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8539     // If we're actually extending zero bits, then if
8540     // SrcSize <  DstSize: zext(a & mask)
8541     // SrcSize == DstSize: a & mask
8542     // SrcSize  > DstSize: trunc(a) & mask
8543     if (SrcSize < DstSize) {
8544       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8545       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8546       Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
8547       return new ZExtInst(And, CI.getType());
8548     }
8549     
8550     if (SrcSize == DstSize) {
8551       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8552       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8553                                                            AndValue));
8554     }
8555     if (SrcSize > DstSize) {
8556       Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
8557       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8558       return BinaryOperator::CreateAnd(Trunc, 
8559                                        ConstantInt::get(Trunc->getType(),
8560                                                                AndValue));
8561     }
8562   }
8563
8564   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8565     return transformZExtICmp(ICI, CI);
8566
8567   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8568   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8569     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8570     // of the (zext icmp) will be transformed.
8571     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8572     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8573     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8574         (transformZExtICmp(LHS, CI, false) ||
8575          transformZExtICmp(RHS, CI, false))) {
8576       Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8577       Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
8578       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8579     }
8580   }
8581
8582   // zext(trunc(t) & C) -> (t & zext(C)).
8583   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8584     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8585       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8586         Value *TI0 = TI->getOperand(0);
8587         if (TI0->getType() == CI.getType())
8588           return
8589             BinaryOperator::CreateAnd(TI0,
8590                                 ConstantExpr::getZExt(C, CI.getType()));
8591       }
8592
8593   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8594   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8595     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8596       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8597         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8598             And->getOperand(1) == C)
8599           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8600             Value *TI0 = TI->getOperand(0);
8601             if (TI0->getType() == CI.getType()) {
8602               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8603               Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
8604               return BinaryOperator::CreateXor(NewAnd, ZC);
8605             }
8606           }
8607
8608   return 0;
8609 }
8610
8611 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8612   if (Instruction *I = commonIntCastTransforms(CI))
8613     return I;
8614   
8615   Value *Src = CI.getOperand(0);
8616   
8617   // Canonicalize sign-extend from i1 to a select.
8618   if (Src->getType() == Type::getInt1Ty(*Context))
8619     return SelectInst::Create(Src,
8620                               Constant::getAllOnesValue(CI.getType()),
8621                               Constant::getNullValue(CI.getType()));
8622
8623   // See if the value being truncated is already sign extended.  If so, just
8624   // eliminate the trunc/sext pair.
8625   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8626     Value *Op = cast<User>(Src)->getOperand(0);
8627     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8628     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8629     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8630     unsigned NumSignBits = ComputeNumSignBits(Op);
8631
8632     if (OpBits == DestBits) {
8633       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8634       // bits, it is already ready.
8635       if (NumSignBits > DestBits-MidBits)
8636         return ReplaceInstUsesWith(CI, Op);
8637     } else if (OpBits < DestBits) {
8638       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8639       // bits, just sext from i32.
8640       if (NumSignBits > OpBits-MidBits)
8641         return new SExtInst(Op, CI.getType(), "tmp");
8642     } else {
8643       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8644       // bits, just truncate to i32.
8645       if (NumSignBits > OpBits-MidBits)
8646         return new TruncInst(Op, CI.getType(), "tmp");
8647     }
8648   }
8649
8650   // If the input is a shl/ashr pair of a same constant, then this is a sign
8651   // extension from a smaller value.  If we could trust arbitrary bitwidth
8652   // integers, we could turn this into a truncate to the smaller bit and then
8653   // use a sext for the whole extension.  Since we don't, look deeper and check
8654   // for a truncate.  If the source and dest are the same type, eliminate the
8655   // trunc and extend and just do shifts.  For example, turn:
8656   //   %a = trunc i32 %i to i8
8657   //   %b = shl i8 %a, 6
8658   //   %c = ashr i8 %b, 6
8659   //   %d = sext i8 %c to i32
8660   // into:
8661   //   %a = shl i32 %i, 30
8662   //   %d = ashr i32 %a, 30
8663   Value *A = 0;
8664   ConstantInt *BA = 0, *CA = 0;
8665   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8666                         m_ConstantInt(CA))) &&
8667       BA == CA && isa<TruncInst>(A)) {
8668     Value *I = cast<TruncInst>(A)->getOperand(0);
8669     if (I->getType() == CI.getType()) {
8670       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8671       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8672       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8673       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8674       I = Builder->CreateShl(I, ShAmtV, CI.getName());
8675       return BinaryOperator::CreateAShr(I, ShAmtV);
8676     }
8677   }
8678   
8679   return 0;
8680 }
8681
8682 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8683 /// in the specified FP type without changing its value.
8684 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8685                               LLVMContext *Context) {
8686   bool losesInfo;
8687   APFloat F = CFP->getValueAPF();
8688   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8689   if (!losesInfo)
8690     return ConstantFP::get(*Context, F);
8691   return 0;
8692 }
8693
8694 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8695 /// through it until we get the source value.
8696 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8697   if (Instruction *I = dyn_cast<Instruction>(V))
8698     if (I->getOpcode() == Instruction::FPExt)
8699       return LookThroughFPExtensions(I->getOperand(0), Context);
8700   
8701   // If this value is a constant, return the constant in the smallest FP type
8702   // that can accurately represent it.  This allows us to turn
8703   // (float)((double)X+2.0) into x+2.0f.
8704   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8705     if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
8706       return V;  // No constant folding of this.
8707     // See if the value can be truncated to float and then reextended.
8708     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8709       return V;
8710     if (CFP->getType() == Type::getDoubleTy(*Context))
8711       return V;  // Won't shrink.
8712     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8713       return V;
8714     // Don't try to shrink to various long double types.
8715   }
8716   
8717   return V;
8718 }
8719
8720 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8721   if (Instruction *I = commonCastTransforms(CI))
8722     return I;
8723   
8724   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8725   // smaller than the destination type, we can eliminate the truncate by doing
8726   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8727   // many builtins (sqrt, etc).
8728   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8729   if (OpI && OpI->hasOneUse()) {
8730     switch (OpI->getOpcode()) {
8731     default: break;
8732     case Instruction::FAdd:
8733     case Instruction::FSub:
8734     case Instruction::FMul:
8735     case Instruction::FDiv:
8736     case Instruction::FRem:
8737       const Type *SrcTy = OpI->getType();
8738       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8739       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8740       if (LHSTrunc->getType() != SrcTy && 
8741           RHSTrunc->getType() != SrcTy) {
8742         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8743         // If the source types were both smaller than the destination type of
8744         // the cast, do this xform.
8745         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8746             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8747           LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8748           RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
8749           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8750         }
8751       }
8752       break;  
8753     }
8754   }
8755   return 0;
8756 }
8757
8758 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8759   return commonCastTransforms(CI);
8760 }
8761
8762 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8763   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8764   if (OpI == 0)
8765     return commonCastTransforms(FI);
8766
8767   // fptoui(uitofp(X)) --> X
8768   // fptoui(sitofp(X)) --> X
8769   // This is safe if the intermediate type has enough bits in its mantissa to
8770   // accurately represent all values of X.  For example, do not do this with
8771   // i64->float->i64.  This is also safe for sitofp case, because any negative
8772   // 'X' value would cause an undefined result for the fptoui. 
8773   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8774       OpI->getOperand(0)->getType() == FI.getType() &&
8775       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8776                     OpI->getType()->getFPMantissaWidth())
8777     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8778
8779   return commonCastTransforms(FI);
8780 }
8781
8782 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8783   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8784   if (OpI == 0)
8785     return commonCastTransforms(FI);
8786   
8787   // fptosi(sitofp(X)) --> X
8788   // fptosi(uitofp(X)) --> X
8789   // This is safe if the intermediate type has enough bits in its mantissa to
8790   // accurately represent all values of X.  For example, do not do this with
8791   // i64->float->i64.  This is also safe for sitofp case, because any negative
8792   // 'X' value would cause an undefined result for the fptoui. 
8793   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8794       OpI->getOperand(0)->getType() == FI.getType() &&
8795       (int)FI.getType()->getScalarSizeInBits() <=
8796                     OpI->getType()->getFPMantissaWidth())
8797     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8798   
8799   return commonCastTransforms(FI);
8800 }
8801
8802 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8803   return commonCastTransforms(CI);
8804 }
8805
8806 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8807   return commonCastTransforms(CI);
8808 }
8809
8810 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8811   // If the destination integer type is smaller than the intptr_t type for
8812   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8813   // trunc to be exposed to other transforms.  Don't do this for extending
8814   // ptrtoint's, because we don't know if the target sign or zero extends its
8815   // pointers.
8816   if (TD &&
8817       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8818     Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8819                                        TD->getIntPtrType(CI.getContext()),
8820                                        "tmp");
8821     return new TruncInst(P, CI.getType());
8822   }
8823   
8824   return commonPointerCastTransforms(CI);
8825 }
8826
8827 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8828   // If the source integer type is larger than the intptr_t type for
8829   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8830   // allows the trunc to be exposed to other transforms.  Don't do this for
8831   // extending inttoptr's, because we don't know if the target sign or zero
8832   // extends to pointers.
8833   if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
8834       TD->getPointerSizeInBits()) {
8835     Value *P = Builder->CreateTrunc(CI.getOperand(0),
8836                                     TD->getIntPtrType(CI.getContext()), "tmp");
8837     return new IntToPtrInst(P, CI.getType());
8838   }
8839   
8840   if (Instruction *I = commonCastTransforms(CI))
8841     return I;
8842
8843   return 0;
8844 }
8845
8846 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8847   // If the operands are integer typed then apply the integer transforms,
8848   // otherwise just apply the common ones.
8849   Value *Src = CI.getOperand(0);
8850   const Type *SrcTy = Src->getType();
8851   const Type *DestTy = CI.getType();
8852
8853   if (isa<PointerType>(SrcTy)) {
8854     if (Instruction *I = commonPointerCastTransforms(CI))
8855       return I;
8856   } else {
8857     if (Instruction *Result = commonCastTransforms(CI))
8858       return Result;
8859   }
8860
8861
8862   // Get rid of casts from one type to the same type. These are useless and can
8863   // be replaced by the operand.
8864   if (DestTy == Src->getType())
8865     return ReplaceInstUsesWith(CI, Src);
8866
8867   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8868     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8869     const Type *DstElTy = DstPTy->getElementType();
8870     const Type *SrcElTy = SrcPTy->getElementType();
8871     
8872     // If the address spaces don't match, don't eliminate the bitcast, which is
8873     // required for changing types.
8874     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8875       return 0;
8876     
8877     // If we are casting a alloca to a pointer to a type of the same
8878     // size, rewrite the allocation instruction to allocate the "right" type.
8879     // There is no need to modify malloc calls because it is their bitcast that
8880     // needs to be cleaned up.
8881     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8882       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8883         return V;
8884     
8885     // If the source and destination are pointers, and this cast is equivalent
8886     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8887     // This can enhance SROA and other transforms that want type-safe pointers.
8888     Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
8889     unsigned NumZeros = 0;
8890     while (SrcElTy != DstElTy && 
8891            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8892            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8893       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8894       ++NumZeros;
8895     }
8896
8897     // If we found a path from the src to dest, create the getelementptr now.
8898     if (SrcElTy == DstElTy) {
8899       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8900       return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8901                                                ((Instruction*) NULL));
8902     }
8903   }
8904
8905   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8906     if (DestVTy->getNumElements() == 1) {
8907       if (!isa<VectorType>(SrcTy)) {
8908         Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
8909         return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
8910                             Constant::getNullValue(Type::getInt32Ty(*Context)));
8911       }
8912       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8913     }
8914   }
8915
8916   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8917     if (SrcVTy->getNumElements() == 1) {
8918       if (!isa<VectorType>(DestTy)) {
8919         Value *Elem = 
8920           Builder->CreateExtractElement(Src,
8921                             Constant::getNullValue(Type::getInt32Ty(*Context)));
8922         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8923       }
8924     }
8925   }
8926
8927   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8928     if (SVI->hasOneUse()) {
8929       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8930       // a bitconvert to a vector with the same # elts.
8931       if (isa<VectorType>(DestTy) && 
8932           cast<VectorType>(DestTy)->getNumElements() ==
8933                 SVI->getType()->getNumElements() &&
8934           SVI->getType()->getNumElements() ==
8935             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8936         CastInst *Tmp;
8937         // If either of the operands is a cast from CI.getType(), then
8938         // evaluating the shuffle in the casted destination's type will allow
8939         // us to eliminate at least one cast.
8940         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8941              Tmp->getOperand(0)->getType() == DestTy) ||
8942             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8943              Tmp->getOperand(0)->getType() == DestTy)) {
8944           Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8945           Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
8946           // Return a new shuffle vector.  Use the same element ID's, as we
8947           // know the vector types match #elts.
8948           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8949         }
8950       }
8951     }
8952   }
8953   return 0;
8954 }
8955
8956 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8957 ///   %C = or %A, %B
8958 ///   %D = select %cond, %C, %A
8959 /// into:
8960 ///   %C = select %cond, %B, 0
8961 ///   %D = or %A, %C
8962 ///
8963 /// Assuming that the specified instruction is an operand to the select, return
8964 /// a bitmask indicating which operands of this instruction are foldable if they
8965 /// equal the other incoming value of the select.
8966 ///
8967 static unsigned GetSelectFoldableOperands(Instruction *I) {
8968   switch (I->getOpcode()) {
8969   case Instruction::Add:
8970   case Instruction::Mul:
8971   case Instruction::And:
8972   case Instruction::Or:
8973   case Instruction::Xor:
8974     return 3;              // Can fold through either operand.
8975   case Instruction::Sub:   // Can only fold on the amount subtracted.
8976   case Instruction::Shl:   // Can only fold on the shift amount.
8977   case Instruction::LShr:
8978   case Instruction::AShr:
8979     return 1;
8980   default:
8981     return 0;              // Cannot fold
8982   }
8983 }
8984
8985 /// GetSelectFoldableConstant - For the same transformation as the previous
8986 /// function, return the identity constant that goes into the select.
8987 static Constant *GetSelectFoldableConstant(Instruction *I,
8988                                            LLVMContext *Context) {
8989   switch (I->getOpcode()) {
8990   default: llvm_unreachable("This cannot happen!");
8991   case Instruction::Add:
8992   case Instruction::Sub:
8993   case Instruction::Or:
8994   case Instruction::Xor:
8995   case Instruction::Shl:
8996   case Instruction::LShr:
8997   case Instruction::AShr:
8998     return Constant::getNullValue(I->getType());
8999   case Instruction::And:
9000     return Constant::getAllOnesValue(I->getType());
9001   case Instruction::Mul:
9002     return ConstantInt::get(I->getType(), 1);
9003   }
9004 }
9005
9006 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9007 /// have the same opcode and only one use each.  Try to simplify this.
9008 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9009                                           Instruction *FI) {
9010   if (TI->getNumOperands() == 1) {
9011     // If this is a non-volatile load or a cast from the same type,
9012     // merge.
9013     if (TI->isCast()) {
9014       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9015         return 0;
9016     } else {
9017       return 0;  // unknown unary op.
9018     }
9019
9020     // Fold this by inserting a select from the input values.
9021     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9022                                           FI->getOperand(0), SI.getName()+".v");
9023     InsertNewInstBefore(NewSI, SI);
9024     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9025                             TI->getType());
9026   }
9027
9028   // Only handle binary operators here.
9029   if (!isa<BinaryOperator>(TI))
9030     return 0;
9031
9032   // Figure out if the operations have any operands in common.
9033   Value *MatchOp, *OtherOpT, *OtherOpF;
9034   bool MatchIsOpZero;
9035   if (TI->getOperand(0) == FI->getOperand(0)) {
9036     MatchOp  = TI->getOperand(0);
9037     OtherOpT = TI->getOperand(1);
9038     OtherOpF = FI->getOperand(1);
9039     MatchIsOpZero = true;
9040   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9041     MatchOp  = TI->getOperand(1);
9042     OtherOpT = TI->getOperand(0);
9043     OtherOpF = FI->getOperand(0);
9044     MatchIsOpZero = false;
9045   } else if (!TI->isCommutative()) {
9046     return 0;
9047   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9048     MatchOp  = TI->getOperand(0);
9049     OtherOpT = TI->getOperand(1);
9050     OtherOpF = FI->getOperand(0);
9051     MatchIsOpZero = true;
9052   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9053     MatchOp  = TI->getOperand(1);
9054     OtherOpT = TI->getOperand(0);
9055     OtherOpF = FI->getOperand(1);
9056     MatchIsOpZero = true;
9057   } else {
9058     return 0;
9059   }
9060
9061   // If we reach here, they do have operations in common.
9062   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9063                                          OtherOpF, SI.getName()+".v");
9064   InsertNewInstBefore(NewSI, SI);
9065
9066   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9067     if (MatchIsOpZero)
9068       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9069     else
9070       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9071   }
9072   llvm_unreachable("Shouldn't get here");
9073   return 0;
9074 }
9075
9076 static bool isSelect01(Constant *C1, Constant *C2) {
9077   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9078   if (!C1I)
9079     return false;
9080   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9081   if (!C2I)
9082     return false;
9083   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9084 }
9085
9086 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9087 /// facilitate further optimization.
9088 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9089                                             Value *FalseVal) {
9090   // See the comment above GetSelectFoldableOperands for a description of the
9091   // transformation we are doing here.
9092   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9093     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9094         !isa<Constant>(FalseVal)) {
9095       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9096         unsigned OpToFold = 0;
9097         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9098           OpToFold = 1;
9099         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9100           OpToFold = 2;
9101         }
9102
9103         if (OpToFold) {
9104           Constant *C = GetSelectFoldableConstant(TVI, Context);
9105           Value *OOp = TVI->getOperand(2-OpToFold);
9106           // Avoid creating select between 2 constants unless it's selecting
9107           // between 0 and 1.
9108           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9109             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9110             InsertNewInstBefore(NewSel, SI);
9111             NewSel->takeName(TVI);
9112             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9113               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9114             llvm_unreachable("Unknown instruction!!");
9115           }
9116         }
9117       }
9118     }
9119   }
9120
9121   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9122     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9123         !isa<Constant>(TrueVal)) {
9124       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9125         unsigned OpToFold = 0;
9126         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9127           OpToFold = 1;
9128         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9129           OpToFold = 2;
9130         }
9131
9132         if (OpToFold) {
9133           Constant *C = GetSelectFoldableConstant(FVI, Context);
9134           Value *OOp = FVI->getOperand(2-OpToFold);
9135           // Avoid creating select between 2 constants unless it's selecting
9136           // between 0 and 1.
9137           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9138             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9139             InsertNewInstBefore(NewSel, SI);
9140             NewSel->takeName(FVI);
9141             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9142               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9143             llvm_unreachable("Unknown instruction!!");
9144           }
9145         }
9146       }
9147     }
9148   }
9149
9150   return 0;
9151 }
9152
9153 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9154 /// ICmpInst as its first operand.
9155 ///
9156 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9157                                                    ICmpInst *ICI) {
9158   bool Changed = false;
9159   ICmpInst::Predicate Pred = ICI->getPredicate();
9160   Value *CmpLHS = ICI->getOperand(0);
9161   Value *CmpRHS = ICI->getOperand(1);
9162   Value *TrueVal = SI.getTrueValue();
9163   Value *FalseVal = SI.getFalseValue();
9164
9165   // Check cases where the comparison is with a constant that
9166   // can be adjusted to fit the min/max idiom. We may edit ICI in
9167   // place here, so make sure the select is the only user.
9168   if (ICI->hasOneUse())
9169     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9170       switch (Pred) {
9171       default: break;
9172       case ICmpInst::ICMP_ULT:
9173       case ICmpInst::ICMP_SLT: {
9174         // X < MIN ? T : F  -->  F
9175         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9176           return ReplaceInstUsesWith(SI, FalseVal);
9177         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9178         Constant *AdjustedRHS = SubOne(CI);
9179         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9180             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9181           Pred = ICmpInst::getSwappedPredicate(Pred);
9182           CmpRHS = AdjustedRHS;
9183           std::swap(FalseVal, TrueVal);
9184           ICI->setPredicate(Pred);
9185           ICI->setOperand(1, CmpRHS);
9186           SI.setOperand(1, TrueVal);
9187           SI.setOperand(2, FalseVal);
9188           Changed = true;
9189         }
9190         break;
9191       }
9192       case ICmpInst::ICMP_UGT:
9193       case ICmpInst::ICMP_SGT: {
9194         // X > MAX ? T : F  -->  F
9195         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9196           return ReplaceInstUsesWith(SI, FalseVal);
9197         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9198         Constant *AdjustedRHS = AddOne(CI);
9199         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9200             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9201           Pred = ICmpInst::getSwappedPredicate(Pred);
9202           CmpRHS = AdjustedRHS;
9203           std::swap(FalseVal, TrueVal);
9204           ICI->setPredicate(Pred);
9205           ICI->setOperand(1, CmpRHS);
9206           SI.setOperand(1, TrueVal);
9207           SI.setOperand(2, FalseVal);
9208           Changed = true;
9209         }
9210         break;
9211       }
9212       }
9213
9214       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9215       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9216       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9217       if (match(TrueVal, m_ConstantInt<-1>()) &&
9218           match(FalseVal, m_ConstantInt<0>()))
9219         Pred = ICI->getPredicate();
9220       else if (match(TrueVal, m_ConstantInt<0>()) &&
9221                match(FalseVal, m_ConstantInt<-1>()))
9222         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9223       
9224       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9225         // If we are just checking for a icmp eq of a single bit and zext'ing it
9226         // to an integer, then shift the bit to the appropriate place and then
9227         // cast to integer to avoid the comparison.
9228         const APInt &Op1CV = CI->getValue();
9229     
9230         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9231         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9232         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9233             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9234           Value *In = ICI->getOperand(0);
9235           Value *Sh = ConstantInt::get(In->getType(),
9236                                        In->getType()->getScalarSizeInBits()-1);
9237           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9238                                                         In->getName()+".lobit"),
9239                                    *ICI);
9240           if (In->getType() != SI.getType())
9241             In = CastInst::CreateIntegerCast(In, SI.getType(),
9242                                              true/*SExt*/, "tmp", ICI);
9243     
9244           if (Pred == ICmpInst::ICMP_SGT)
9245             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9246                                        In->getName()+".not"), *ICI);
9247     
9248           return ReplaceInstUsesWith(SI, In);
9249         }
9250       }
9251     }
9252
9253   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9254     // Transform (X == Y) ? X : Y  -> Y
9255     if (Pred == ICmpInst::ICMP_EQ)
9256       return ReplaceInstUsesWith(SI, FalseVal);
9257     // Transform (X != Y) ? X : Y  -> X
9258     if (Pred == ICmpInst::ICMP_NE)
9259       return ReplaceInstUsesWith(SI, TrueVal);
9260     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9261
9262   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9263     // Transform (X == Y) ? Y : X  -> X
9264     if (Pred == ICmpInst::ICMP_EQ)
9265       return ReplaceInstUsesWith(SI, FalseVal);
9266     // Transform (X != Y) ? Y : X  -> Y
9267     if (Pred == ICmpInst::ICMP_NE)
9268       return ReplaceInstUsesWith(SI, TrueVal);
9269     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9270   }
9271
9272   /// NOTE: if we wanted to, this is where to detect integer ABS
9273
9274   return Changed ? &SI : 0;
9275 }
9276
9277
9278 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9279 /// PHI node (but the two may be in different blocks).  See if the true/false
9280 /// values (V) are live in all of the predecessor blocks of the PHI.  For
9281 /// example, cases like this cannot be mapped:
9282 ///
9283 ///   X = phi [ C1, BB1], [C2, BB2]
9284 ///   Y = add
9285 ///   Z = select X, Y, 0
9286 ///
9287 /// because Y is not live in BB1/BB2.
9288 ///
9289 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9290                                                    const SelectInst &SI) {
9291   // If the value is a non-instruction value like a constant or argument, it
9292   // can always be mapped.
9293   const Instruction *I = dyn_cast<Instruction>(V);
9294   if (I == 0) return true;
9295   
9296   // If V is a PHI node defined in the same block as the condition PHI, we can
9297   // map the arguments.
9298   const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9299   
9300   if (const PHINode *VP = dyn_cast<PHINode>(I))
9301     if (VP->getParent() == CondPHI->getParent())
9302       return true;
9303   
9304   // Otherwise, if the PHI and select are defined in the same block and if V is
9305   // defined in a different block, then we can transform it.
9306   if (SI.getParent() == CondPHI->getParent() &&
9307       I->getParent() != CondPHI->getParent())
9308     return true;
9309   
9310   // Otherwise we have a 'hard' case and we can't tell without doing more
9311   // detailed dominator based analysis, punt.
9312   return false;
9313 }
9314
9315 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9316   Value *CondVal = SI.getCondition();
9317   Value *TrueVal = SI.getTrueValue();
9318   Value *FalseVal = SI.getFalseValue();
9319
9320   // select true, X, Y  -> X
9321   // select false, X, Y -> Y
9322   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9323     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9324
9325   // select C, X, X -> X
9326   if (TrueVal == FalseVal)
9327     return ReplaceInstUsesWith(SI, TrueVal);
9328
9329   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9330     return ReplaceInstUsesWith(SI, FalseVal);
9331   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9332     return ReplaceInstUsesWith(SI, TrueVal);
9333   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9334     if (isa<Constant>(TrueVal))
9335       return ReplaceInstUsesWith(SI, TrueVal);
9336     else
9337       return ReplaceInstUsesWith(SI, FalseVal);
9338   }
9339
9340   if (SI.getType() == Type::getInt1Ty(*Context)) {
9341     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9342       if (C->getZExtValue()) {
9343         // Change: A = select B, true, C --> A = or B, C
9344         return BinaryOperator::CreateOr(CondVal, FalseVal);
9345       } else {
9346         // Change: A = select B, false, C --> A = and !B, C
9347         Value *NotCond =
9348           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9349                                              "not."+CondVal->getName()), SI);
9350         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9351       }
9352     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9353       if (C->getZExtValue() == false) {
9354         // Change: A = select B, C, false --> A = and B, C
9355         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9356       } else {
9357         // Change: A = select B, C, true --> A = or !B, C
9358         Value *NotCond =
9359           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9360                                              "not."+CondVal->getName()), SI);
9361         return BinaryOperator::CreateOr(NotCond, TrueVal);
9362       }
9363     }
9364     
9365     // select a, b, a  -> a&b
9366     // select a, a, b  -> a|b
9367     if (CondVal == TrueVal)
9368       return BinaryOperator::CreateOr(CondVal, FalseVal);
9369     else if (CondVal == FalseVal)
9370       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9371   }
9372
9373   // Selecting between two integer constants?
9374   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9375     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9376       // select C, 1, 0 -> zext C to int
9377       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9378         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9379       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9380         // select C, 0, 1 -> zext !C to int
9381         Value *NotCond =
9382           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9383                                                "not."+CondVal->getName()), SI);
9384         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9385       }
9386
9387       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9388         // If one of the constants is zero (we know they can't both be) and we
9389         // have an icmp instruction with zero, and we have an 'and' with the
9390         // non-constant value, eliminate this whole mess.  This corresponds to
9391         // cases like this: ((X & 27) ? 27 : 0)
9392         if (TrueValC->isZero() || FalseValC->isZero())
9393           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9394               cast<Constant>(IC->getOperand(1))->isNullValue())
9395             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9396               if (ICA->getOpcode() == Instruction::And &&
9397                   isa<ConstantInt>(ICA->getOperand(1)) &&
9398                   (ICA->getOperand(1) == TrueValC ||
9399                    ICA->getOperand(1) == FalseValC) &&
9400                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9401                 // Okay, now we know that everything is set up, we just don't
9402                 // know whether we have a icmp_ne or icmp_eq and whether the 
9403                 // true or false val is the zero.
9404                 bool ShouldNotVal = !TrueValC->isZero();
9405                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9406                 Value *V = ICA;
9407                 if (ShouldNotVal)
9408                   V = InsertNewInstBefore(BinaryOperator::Create(
9409                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9410                 return ReplaceInstUsesWith(SI, V);
9411               }
9412       }
9413     }
9414
9415   // See if we are selecting two values based on a comparison of the two values.
9416   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9417     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9418       // Transform (X == Y) ? X : Y  -> Y
9419       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9420         // This is not safe in general for floating point:  
9421         // consider X== -0, Y== +0.
9422         // It becomes safe if either operand is a nonzero constant.
9423         ConstantFP *CFPt, *CFPf;
9424         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9425               !CFPt->getValueAPF().isZero()) ||
9426             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9427              !CFPf->getValueAPF().isZero()))
9428         return ReplaceInstUsesWith(SI, FalseVal);
9429       }
9430       // Transform (X != Y) ? X : Y  -> X
9431       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9432         return ReplaceInstUsesWith(SI, TrueVal);
9433       // NOTE: if we wanted to, this is where to detect MIN/MAX
9434
9435     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9436       // Transform (X == Y) ? Y : X  -> X
9437       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9438         // This is not safe in general for floating point:  
9439         // consider X== -0, Y== +0.
9440         // It becomes safe if either operand is a nonzero constant.
9441         ConstantFP *CFPt, *CFPf;
9442         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9443               !CFPt->getValueAPF().isZero()) ||
9444             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9445              !CFPf->getValueAPF().isZero()))
9446           return ReplaceInstUsesWith(SI, FalseVal);
9447       }
9448       // Transform (X != Y) ? Y : X  -> Y
9449       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9450         return ReplaceInstUsesWith(SI, TrueVal);
9451       // NOTE: if we wanted to, this is where to detect MIN/MAX
9452     }
9453     // NOTE: if we wanted to, this is where to detect ABS
9454   }
9455
9456   // See if we are selecting two values based on a comparison of the two values.
9457   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9458     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9459       return Result;
9460
9461   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9462     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9463       if (TI->hasOneUse() && FI->hasOneUse()) {
9464         Instruction *AddOp = 0, *SubOp = 0;
9465
9466         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9467         if (TI->getOpcode() == FI->getOpcode())
9468           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9469             return IV;
9470
9471         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9472         // even legal for FP.
9473         if ((TI->getOpcode() == Instruction::Sub &&
9474              FI->getOpcode() == Instruction::Add) ||
9475             (TI->getOpcode() == Instruction::FSub &&
9476              FI->getOpcode() == Instruction::FAdd)) {
9477           AddOp = FI; SubOp = TI;
9478         } else if ((FI->getOpcode() == Instruction::Sub &&
9479                     TI->getOpcode() == Instruction::Add) ||
9480                    (FI->getOpcode() == Instruction::FSub &&
9481                     TI->getOpcode() == Instruction::FAdd)) {
9482           AddOp = TI; SubOp = FI;
9483         }
9484
9485         if (AddOp) {
9486           Value *OtherAddOp = 0;
9487           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9488             OtherAddOp = AddOp->getOperand(1);
9489           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9490             OtherAddOp = AddOp->getOperand(0);
9491           }
9492
9493           if (OtherAddOp) {
9494             // So at this point we know we have (Y -> OtherAddOp):
9495             //        select C, (add X, Y), (sub X, Z)
9496             Value *NegVal;  // Compute -Z
9497             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9498               NegVal = ConstantExpr::getNeg(C);
9499             } else {
9500               NegVal = InsertNewInstBefore(
9501                     BinaryOperator::CreateNeg(SubOp->getOperand(1),
9502                                               "tmp"), SI);
9503             }
9504
9505             Value *NewTrueOp = OtherAddOp;
9506             Value *NewFalseOp = NegVal;
9507             if (AddOp != TI)
9508               std::swap(NewTrueOp, NewFalseOp);
9509             Instruction *NewSel =
9510               SelectInst::Create(CondVal, NewTrueOp,
9511                                  NewFalseOp, SI.getName() + ".p");
9512
9513             NewSel = InsertNewInstBefore(NewSel, SI);
9514             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9515           }
9516         }
9517       }
9518
9519   // See if we can fold the select into one of our operands.
9520   if (SI.getType()->isInteger()) {
9521     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9522     if (FoldI)
9523       return FoldI;
9524   }
9525
9526   // See if we can fold the select into a phi node if the condition is a select.
9527   if (isa<PHINode>(SI.getCondition())) 
9528     // The true/false values have to be live in the PHI predecessor's blocks.
9529     if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
9530         CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
9531       if (Instruction *NV = FoldOpIntoPhi(SI))
9532         return NV;
9533
9534   if (BinaryOperator::isNot(CondVal)) {
9535     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9536     SI.setOperand(1, FalseVal);
9537     SI.setOperand(2, TrueVal);
9538     return &SI;
9539   }
9540
9541   return 0;
9542 }
9543
9544 /// EnforceKnownAlignment - If the specified pointer points to an object that
9545 /// we control, modify the object's alignment to PrefAlign. This isn't
9546 /// often possible though. If alignment is important, a more reliable approach
9547 /// is to simply align all global variables and allocation instructions to
9548 /// their preferred alignment from the beginning.
9549 ///
9550 static unsigned EnforceKnownAlignment(Value *V,
9551                                       unsigned Align, unsigned PrefAlign) {
9552
9553   User *U = dyn_cast<User>(V);
9554   if (!U) return Align;
9555
9556   switch (Operator::getOpcode(U)) {
9557   default: break;
9558   case Instruction::BitCast:
9559     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9560   case Instruction::GetElementPtr: {
9561     // If all indexes are zero, it is just the alignment of the base pointer.
9562     bool AllZeroOperands = true;
9563     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9564       if (!isa<Constant>(*i) ||
9565           !cast<Constant>(*i)->isNullValue()) {
9566         AllZeroOperands = false;
9567         break;
9568       }
9569
9570     if (AllZeroOperands) {
9571       // Treat this like a bitcast.
9572       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9573     }
9574     break;
9575   }
9576   }
9577
9578   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9579     // If there is a large requested alignment and we can, bump up the alignment
9580     // of the global.
9581     if (!GV->isDeclaration()) {
9582       if (GV->getAlignment() >= PrefAlign)
9583         Align = GV->getAlignment();
9584       else {
9585         GV->setAlignment(PrefAlign);
9586         Align = PrefAlign;
9587       }
9588     }
9589   } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9590     // If there is a requested alignment and if this is an alloca, round up.
9591     if (AI->getAlignment() >= PrefAlign)
9592       Align = AI->getAlignment();
9593     else {
9594       AI->setAlignment(PrefAlign);
9595       Align = PrefAlign;
9596     }
9597   }
9598
9599   return Align;
9600 }
9601
9602 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9603 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9604 /// and it is more than the alignment of the ultimate object, see if we can
9605 /// increase the alignment of the ultimate object, making this check succeed.
9606 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9607                                                   unsigned PrefAlign) {
9608   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9609                       sizeof(PrefAlign) * CHAR_BIT;
9610   APInt Mask = APInt::getAllOnesValue(BitWidth);
9611   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9612   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9613   unsigned TrailZ = KnownZero.countTrailingOnes();
9614   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9615
9616   if (PrefAlign > Align)
9617     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9618   
9619     // We don't need to make any adjustment.
9620   return Align;
9621 }
9622
9623 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9624   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9625   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9626   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9627   unsigned CopyAlign = MI->getAlignment();
9628
9629   if (CopyAlign < MinAlign) {
9630     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 
9631                                              MinAlign, false));
9632     return MI;
9633   }
9634   
9635   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9636   // load/store.
9637   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9638   if (MemOpLength == 0) return 0;
9639   
9640   // Source and destination pointer types are always "i8*" for intrinsic.  See
9641   // if the size is something we can handle with a single primitive load/store.
9642   // A single load+store correctly handles overlapping memory in the memmove
9643   // case.
9644   unsigned Size = MemOpLength->getZExtValue();
9645   if (Size == 0) return MI;  // Delete this mem transfer.
9646   
9647   if (Size > 8 || (Size&(Size-1)))
9648     return 0;  // If not 1/2/4/8 bytes, exit.
9649   
9650   // Use an integer load+store unless we can find something better.
9651   Type *NewPtrTy =
9652                 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
9653   
9654   // Memcpy forces the use of i8* for the source and destination.  That means
9655   // that if you're using memcpy to move one double around, you'll get a cast
9656   // from double* to i8*.  We'd much rather use a double load+store rather than
9657   // an i64 load+store, here because this improves the odds that the source or
9658   // dest address will be promotable.  See if we can find a better type than the
9659   // integer datatype.
9660   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9661     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9662     if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9663       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9664       // down through these levels if so.
9665       while (!SrcETy->isSingleValueType()) {
9666         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9667           if (STy->getNumElements() == 1)
9668             SrcETy = STy->getElementType(0);
9669           else
9670             break;
9671         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9672           if (ATy->getNumElements() == 1)
9673             SrcETy = ATy->getElementType();
9674           else
9675             break;
9676         } else
9677           break;
9678       }
9679       
9680       if (SrcETy->isSingleValueType())
9681         NewPtrTy = PointerType::getUnqual(SrcETy);
9682     }
9683   }
9684   
9685   
9686   // If the memcpy/memmove provides better alignment info than we can
9687   // infer, use it.
9688   SrcAlign = std::max(SrcAlign, CopyAlign);
9689   DstAlign = std::max(DstAlign, CopyAlign);
9690   
9691   Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9692   Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
9693   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9694   InsertNewInstBefore(L, *MI);
9695   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9696
9697   // Set the size of the copy to 0, it will be deleted on the next iteration.
9698   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9699   return MI;
9700 }
9701
9702 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9703   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9704   if (MI->getAlignment() < Alignment) {
9705     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9706                                              Alignment, false));
9707     return MI;
9708   }
9709   
9710   // Extract the length and alignment and fill if they are constant.
9711   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9712   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9713   if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
9714     return 0;
9715   uint64_t Len = LenC->getZExtValue();
9716   Alignment = MI->getAlignment();
9717   
9718   // If the length is zero, this is a no-op
9719   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9720   
9721   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9722   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9723     const Type *ITy = IntegerType::get(*Context, Len*8);  // n=1 -> i8.
9724     
9725     Value *Dest = MI->getDest();
9726     Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
9727
9728     // Alignment 0 is identity for alignment 1 for memset, but not store.
9729     if (Alignment == 0) Alignment = 1;
9730     
9731     // Extract the fill value and store.
9732     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9733     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9734                                       Dest, false, Alignment), *MI);
9735     
9736     // Set the size of the copy to 0, it will be deleted on the next iteration.
9737     MI->setLength(Constant::getNullValue(LenC->getType()));
9738     return MI;
9739   }
9740
9741   return 0;
9742 }
9743
9744
9745 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9746 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9747 /// the heavy lifting.
9748 ///
9749 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9750   // If the caller function is nounwind, mark the call as nounwind, even if the
9751   // callee isn't.
9752   if (CI.getParent()->getParent()->doesNotThrow() &&
9753       !CI.doesNotThrow()) {
9754     CI.setDoesNotThrow();
9755     return &CI;
9756   }
9757   
9758   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9759   if (!II) return visitCallSite(&CI);
9760   
9761   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9762   // visitCallSite.
9763   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9764     bool Changed = false;
9765
9766     // memmove/cpy/set of zero bytes is a noop.
9767     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9768       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9769
9770       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9771         if (CI->getZExtValue() == 1) {
9772           // Replace the instruction with just byte operations.  We would
9773           // transform other cases to loads/stores, but we don't know if
9774           // alignment is sufficient.
9775         }
9776     }
9777
9778     // If we have a memmove and the source operation is a constant global,
9779     // then the source and dest pointers can't alias, so we can change this
9780     // into a call to memcpy.
9781     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9782       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9783         if (GVSrc->isConstant()) {
9784           Module *M = CI.getParent()->getParent()->getParent();
9785           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9786           const Type *Tys[1];
9787           Tys[0] = CI.getOperand(3)->getType();
9788           CI.setOperand(0, 
9789                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9790           Changed = true;
9791         }
9792
9793       // memmove(x,x,size) -> noop.
9794       if (MMI->getSource() == MMI->getDest())
9795         return EraseInstFromFunction(CI);
9796     }
9797
9798     // If we can determine a pointer alignment that is bigger than currently
9799     // set, update the alignment.
9800     if (isa<MemTransferInst>(MI)) {
9801       if (Instruction *I = SimplifyMemTransfer(MI))
9802         return I;
9803     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9804       if (Instruction *I = SimplifyMemSet(MSI))
9805         return I;
9806     }
9807           
9808     if (Changed) return II;
9809   }
9810   
9811   switch (II->getIntrinsicID()) {
9812   default: break;
9813   case Intrinsic::bswap:
9814     // bswap(bswap(x)) -> x
9815     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9816       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9817         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9818     break;
9819   case Intrinsic::ppc_altivec_lvx:
9820   case Intrinsic::ppc_altivec_lvxl:
9821   case Intrinsic::x86_sse_loadu_ps:
9822   case Intrinsic::x86_sse2_loadu_pd:
9823   case Intrinsic::x86_sse2_loadu_dq:
9824     // Turn PPC lvx     -> load if the pointer is known aligned.
9825     // Turn X86 loadups -> load if the pointer is known aligned.
9826     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9827       Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9828                                          PointerType::getUnqual(II->getType()));
9829       return new LoadInst(Ptr);
9830     }
9831     break;
9832   case Intrinsic::ppc_altivec_stvx:
9833   case Intrinsic::ppc_altivec_stvxl:
9834     // Turn stvx -> store if the pointer is known aligned.
9835     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9836       const Type *OpPtrTy = 
9837         PointerType::getUnqual(II->getOperand(1)->getType());
9838       Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
9839       return new StoreInst(II->getOperand(1), Ptr);
9840     }
9841     break;
9842   case Intrinsic::x86_sse_storeu_ps:
9843   case Intrinsic::x86_sse2_storeu_pd:
9844   case Intrinsic::x86_sse2_storeu_dq:
9845     // Turn X86 storeu -> store if the pointer is known aligned.
9846     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9847       const Type *OpPtrTy = 
9848         PointerType::getUnqual(II->getOperand(2)->getType());
9849       Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
9850       return new StoreInst(II->getOperand(2), Ptr);
9851     }
9852     break;
9853     
9854   case Intrinsic::x86_sse_cvttss2si: {
9855     // These intrinsics only demands the 0th element of its input vector.  If
9856     // we can simplify the input based on that, do so now.
9857     unsigned VWidth =
9858       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9859     APInt DemandedElts(VWidth, 1);
9860     APInt UndefElts(VWidth, 0);
9861     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9862                                               UndefElts)) {
9863       II->setOperand(1, V);
9864       return II;
9865     }
9866     break;
9867   }
9868     
9869   case Intrinsic::ppc_altivec_vperm:
9870     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9871     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9872       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9873       
9874       // Check that all of the elements are integer constants or undefs.
9875       bool AllEltsOk = true;
9876       for (unsigned i = 0; i != 16; ++i) {
9877         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9878             !isa<UndefValue>(Mask->getOperand(i))) {
9879           AllEltsOk = false;
9880           break;
9881         }
9882       }
9883       
9884       if (AllEltsOk) {
9885         // Cast the input vectors to byte vectors.
9886         Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9887         Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
9888         Value *Result = UndefValue::get(Op0->getType());
9889         
9890         // Only extract each element once.
9891         Value *ExtractedElts[32];
9892         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9893         
9894         for (unsigned i = 0; i != 16; ++i) {
9895           if (isa<UndefValue>(Mask->getOperand(i)))
9896             continue;
9897           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9898           Idx &= 31;  // Match the hardware behavior.
9899           
9900           if (ExtractedElts[Idx] == 0) {
9901             ExtractedElts[Idx] = 
9902               Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1, 
9903                   ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9904                                             "tmp");
9905           }
9906         
9907           // Insert this value into the result vector.
9908           Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9909                          ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9910                                                 "tmp");
9911         }
9912         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9913       }
9914     }
9915     break;
9916
9917   case Intrinsic::stackrestore: {
9918     // If the save is right next to the restore, remove the restore.  This can
9919     // happen when variable allocas are DCE'd.
9920     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9921       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9922         BasicBlock::iterator BI = SS;
9923         if (&*++BI == II)
9924           return EraseInstFromFunction(CI);
9925       }
9926     }
9927     
9928     // Scan down this block to see if there is another stack restore in the
9929     // same block without an intervening call/alloca.
9930     BasicBlock::iterator BI = II;
9931     TerminatorInst *TI = II->getParent()->getTerminator();
9932     bool CannotRemove = false;
9933     for (++BI; &*BI != TI; ++BI) {
9934       if (isa<AllocaInst>(BI) || isMalloc(BI)) {
9935         CannotRemove = true;
9936         break;
9937       }
9938       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9939         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9940           // If there is a stackrestore below this one, remove this one.
9941           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9942             return EraseInstFromFunction(CI);
9943           // Otherwise, ignore the intrinsic.
9944         } else {
9945           // If we found a non-intrinsic call, we can't remove the stack
9946           // restore.
9947           CannotRemove = true;
9948           break;
9949         }
9950       }
9951     }
9952     
9953     // If the stack restore is in a return/unwind block and if there are no
9954     // allocas or calls between the restore and the return, nuke the restore.
9955     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9956       return EraseInstFromFunction(CI);
9957     break;
9958   }
9959   }
9960
9961   return visitCallSite(II);
9962 }
9963
9964 // InvokeInst simplification
9965 //
9966 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9967   return visitCallSite(&II);
9968 }
9969
9970 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9971 /// passed through the varargs area, we can eliminate the use of the cast.
9972 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9973                                          const CastInst * const CI,
9974                                          const TargetData * const TD,
9975                                          const int ix) {
9976   if (!CI->isLosslessCast())
9977     return false;
9978
9979   // The size of ByVal arguments is derived from the type, so we
9980   // can't change to a type with a different size.  If the size were
9981   // passed explicitly we could avoid this check.
9982   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9983     return true;
9984
9985   const Type* SrcTy = 
9986             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9987   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9988   if (!SrcTy->isSized() || !DstTy->isSized())
9989     return false;
9990   if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
9991     return false;
9992   return true;
9993 }
9994
9995 // visitCallSite - Improvements for call and invoke instructions.
9996 //
9997 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9998   bool Changed = false;
9999
10000   // If the callee is a constexpr cast of a function, attempt to move the cast
10001   // to the arguments of the call/invoke.
10002   if (transformConstExprCastCall(CS)) return 0;
10003
10004   Value *Callee = CS.getCalledValue();
10005
10006   if (Function *CalleeF = dyn_cast<Function>(Callee))
10007     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10008       Instruction *OldCall = CS.getInstruction();
10009       // If the call and callee calling conventions don't match, this call must
10010       // be unreachable, as the call is undefined.
10011       new StoreInst(ConstantInt::getTrue(*Context),
10012                 UndefValue::get(Type::getInt1PtrTy(*Context)), 
10013                                   OldCall);
10014       // If OldCall dues not return void then replaceAllUsesWith undef.
10015       // This allows ValueHandlers and custom metadata to adjust itself.
10016       if (!OldCall->getType()->isVoidTy())
10017         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
10018       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10019         return EraseInstFromFunction(*OldCall);
10020       return 0;
10021     }
10022
10023   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10024     // This instruction is not reachable, just remove it.  We insert a store to
10025     // undef so that we know that this code is not reachable, despite the fact
10026     // that we can't modify the CFG here.
10027     new StoreInst(ConstantInt::getTrue(*Context),
10028                UndefValue::get(Type::getInt1PtrTy(*Context)),
10029                   CS.getInstruction());
10030
10031     // If CS dues not return void then replaceAllUsesWith undef.
10032     // This allows ValueHandlers and custom metadata to adjust itself.
10033     if (!CS.getInstruction()->getType()->isVoidTy())
10034       CS.getInstruction()->
10035         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
10036
10037     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10038       // Don't break the CFG, insert a dummy cond branch.
10039       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10040                          ConstantInt::getTrue(*Context), II);
10041     }
10042     return EraseInstFromFunction(*CS.getInstruction());
10043   }
10044
10045   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10046     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10047       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10048         return transformCallThroughTrampoline(CS);
10049
10050   const PointerType *PTy = cast<PointerType>(Callee->getType());
10051   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10052   if (FTy->isVarArg()) {
10053     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10054     // See if we can optimize any arguments passed through the varargs area of
10055     // the call.
10056     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10057            E = CS.arg_end(); I != E; ++I, ++ix) {
10058       CastInst *CI = dyn_cast<CastInst>(*I);
10059       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10060         *I = CI->getOperand(0);
10061         Changed = true;
10062       }
10063     }
10064   }
10065
10066   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10067     // Inline asm calls cannot throw - mark them 'nounwind'.
10068     CS.setDoesNotThrow();
10069     Changed = true;
10070   }
10071
10072   return Changed ? CS.getInstruction() : 0;
10073 }
10074
10075 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10076 // attempt to move the cast to the arguments of the call/invoke.
10077 //
10078 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10079   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10080   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10081   if (CE->getOpcode() != Instruction::BitCast || 
10082       !isa<Function>(CE->getOperand(0)))
10083     return false;
10084   Function *Callee = cast<Function>(CE->getOperand(0));
10085   Instruction *Caller = CS.getInstruction();
10086   const AttrListPtr &CallerPAL = CS.getAttributes();
10087
10088   // Okay, this is a cast from a function to a different type.  Unless doing so
10089   // would cause a type conversion of one of our arguments, change this call to
10090   // be a direct call with arguments casted to the appropriate types.
10091   //
10092   const FunctionType *FT = Callee->getFunctionType();
10093   const Type *OldRetTy = Caller->getType();
10094   const Type *NewRetTy = FT->getReturnType();
10095
10096   if (isa<StructType>(NewRetTy))
10097     return false; // TODO: Handle multiple return values.
10098
10099   // Check to see if we are changing the return type...
10100   if (OldRetTy != NewRetTy) {
10101     if (Callee->isDeclaration() &&
10102         // Conversion is ok if changing from one pointer type to another or from
10103         // a pointer to an integer of the same size.
10104         !((isa<PointerType>(OldRetTy) || !TD ||
10105            OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
10106           (isa<PointerType>(NewRetTy) || !TD ||
10107            NewRetTy == TD->getIntPtrType(Caller->getContext()))))
10108       return false;   // Cannot transform this return value.
10109
10110     if (!Caller->use_empty() &&
10111         // void -> non-void is handled specially
10112         !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
10113       return false;   // Cannot transform this return value.
10114
10115     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10116       Attributes RAttrs = CallerPAL.getRetAttributes();
10117       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10118         return false;   // Attribute not compatible with transformed value.
10119     }
10120
10121     // If the callsite is an invoke instruction, and the return value is used by
10122     // a PHI node in a successor, we cannot change the return type of the call
10123     // because there is no place to put the cast instruction (without breaking
10124     // the critical edge).  Bail out in this case.
10125     if (!Caller->use_empty())
10126       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10127         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10128              UI != E; ++UI)
10129           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10130             if (PN->getParent() == II->getNormalDest() ||
10131                 PN->getParent() == II->getUnwindDest())
10132               return false;
10133   }
10134
10135   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10136   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10137
10138   CallSite::arg_iterator AI = CS.arg_begin();
10139   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10140     const Type *ParamTy = FT->getParamType(i);
10141     const Type *ActTy = (*AI)->getType();
10142
10143     if (!CastInst::isCastable(ActTy, ParamTy))
10144       return false;   // Cannot transform this parameter value.
10145
10146     if (CallerPAL.getParamAttributes(i + 1) 
10147         & Attribute::typeIncompatible(ParamTy))
10148       return false;   // Attribute not compatible with transformed value.
10149
10150     // Converting from one pointer type to another or between a pointer and an
10151     // integer of the same size is safe even if we do not have a body.
10152     bool isConvertible = ActTy == ParamTy ||
10153       (TD && ((isa<PointerType>(ParamTy) ||
10154       ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10155               (isa<PointerType>(ActTy) ||
10156               ActTy == TD->getIntPtrType(Caller->getContext()))));
10157     if (Callee->isDeclaration() && !isConvertible) return false;
10158   }
10159
10160   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10161       Callee->isDeclaration())
10162     return false;   // Do not delete arguments unless we have a function body.
10163
10164   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10165       !CallerPAL.isEmpty())
10166     // In this case we have more arguments than the new function type, but we
10167     // won't be dropping them.  Check that these extra arguments have attributes
10168     // that are compatible with being a vararg call argument.
10169     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10170       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10171         break;
10172       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10173       if (PAttrs & Attribute::VarArgsIncompatible)
10174         return false;
10175     }
10176
10177   // Okay, we decided that this is a safe thing to do: go ahead and start
10178   // inserting cast instructions as necessary...
10179   std::vector<Value*> Args;
10180   Args.reserve(NumActualArgs);
10181   SmallVector<AttributeWithIndex, 8> attrVec;
10182   attrVec.reserve(NumCommonArgs);
10183
10184   // Get any return attributes.
10185   Attributes RAttrs = CallerPAL.getRetAttributes();
10186
10187   // If the return value is not being used, the type may not be compatible
10188   // with the existing attributes.  Wipe out any problematic attributes.
10189   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10190
10191   // Add the new return attributes.
10192   if (RAttrs)
10193     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10194
10195   AI = CS.arg_begin();
10196   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10197     const Type *ParamTy = FT->getParamType(i);
10198     if ((*AI)->getType() == ParamTy) {
10199       Args.push_back(*AI);
10200     } else {
10201       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10202           false, ParamTy, false);
10203       Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
10204     }
10205
10206     // Add any parameter attributes.
10207     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10208       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10209   }
10210
10211   // If the function takes more arguments than the call was taking, add them
10212   // now.
10213   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10214     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10215
10216   // If we are removing arguments to the function, emit an obnoxious warning.
10217   if (FT->getNumParams() < NumActualArgs) {
10218     if (!FT->isVarArg()) {
10219       errs() << "WARNING: While resolving call to function '"
10220              << Callee->getName() << "' arguments were dropped!\n";
10221     } else {
10222       // Add all of the arguments in their promoted form to the arg list.
10223       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10224         const Type *PTy = getPromotedType((*AI)->getType());
10225         if (PTy != (*AI)->getType()) {
10226           // Must promote to pass through va_arg area!
10227           Instruction::CastOps opcode =
10228             CastInst::getCastOpcode(*AI, false, PTy, false);
10229           Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
10230         } else {
10231           Args.push_back(*AI);
10232         }
10233
10234         // Add any parameter attributes.
10235         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10236           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10237       }
10238     }
10239   }
10240
10241   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10242     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10243
10244   if (NewRetTy->isVoidTy())
10245     Caller->setName("");   // Void type should not have a name.
10246
10247   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10248                                                      attrVec.end());
10249
10250   Instruction *NC;
10251   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10252     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10253                             Args.begin(), Args.end(),
10254                             Caller->getName(), Caller);
10255     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10256     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10257   } else {
10258     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10259                           Caller->getName(), Caller);
10260     CallInst *CI = cast<CallInst>(Caller);
10261     if (CI->isTailCall())
10262       cast<CallInst>(NC)->setTailCall();
10263     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10264     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10265   }
10266
10267   // Insert a cast of the return type as necessary.
10268   Value *NV = NC;
10269   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10270     if (!NV->getType()->isVoidTy()) {
10271       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10272                                                             OldRetTy, false);
10273       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10274
10275       // If this is an invoke instruction, we should insert it after the first
10276       // non-phi, instruction in the normal successor block.
10277       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10278         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10279         InsertNewInstBefore(NC, *I);
10280       } else {
10281         // Otherwise, it's a call, just insert cast right after the call instr
10282         InsertNewInstBefore(NC, *Caller);
10283       }
10284       Worklist.AddUsersToWorkList(*Caller);
10285     } else {
10286       NV = UndefValue::get(Caller->getType());
10287     }
10288   }
10289
10290
10291   if (!Caller->use_empty())
10292     Caller->replaceAllUsesWith(NV);
10293   
10294   EraseInstFromFunction(*Caller);
10295   return true;
10296 }
10297
10298 // transformCallThroughTrampoline - Turn a call to a function created by the
10299 // init_trampoline intrinsic into a direct call to the underlying function.
10300 //
10301 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10302   Value *Callee = CS.getCalledValue();
10303   const PointerType *PTy = cast<PointerType>(Callee->getType());
10304   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10305   const AttrListPtr &Attrs = CS.getAttributes();
10306
10307   // If the call already has the 'nest' attribute somewhere then give up -
10308   // otherwise 'nest' would occur twice after splicing in the chain.
10309   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10310     return 0;
10311
10312   IntrinsicInst *Tramp =
10313     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10314
10315   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10316   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10317   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10318
10319   const AttrListPtr &NestAttrs = NestF->getAttributes();
10320   if (!NestAttrs.isEmpty()) {
10321     unsigned NestIdx = 1;
10322     const Type *NestTy = 0;
10323     Attributes NestAttr = Attribute::None;
10324
10325     // Look for a parameter marked with the 'nest' attribute.
10326     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10327          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10328       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10329         // Record the parameter type and any other attributes.
10330         NestTy = *I;
10331         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10332         break;
10333       }
10334
10335     if (NestTy) {
10336       Instruction *Caller = CS.getInstruction();
10337       std::vector<Value*> NewArgs;
10338       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10339
10340       SmallVector<AttributeWithIndex, 8> NewAttrs;
10341       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10342
10343       // Insert the nest argument into the call argument list, which may
10344       // mean appending it.  Likewise for attributes.
10345
10346       // Add any result attributes.
10347       if (Attributes Attr = Attrs.getRetAttributes())
10348         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10349
10350       {
10351         unsigned Idx = 1;
10352         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10353         do {
10354           if (Idx == NestIdx) {
10355             // Add the chain argument and attributes.
10356             Value *NestVal = Tramp->getOperand(3);
10357             if (NestVal->getType() != NestTy)
10358               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10359             NewArgs.push_back(NestVal);
10360             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10361           }
10362
10363           if (I == E)
10364             break;
10365
10366           // Add the original argument and attributes.
10367           NewArgs.push_back(*I);
10368           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10369             NewAttrs.push_back
10370               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10371
10372           ++Idx, ++I;
10373         } while (1);
10374       }
10375
10376       // Add any function attributes.
10377       if (Attributes Attr = Attrs.getFnAttributes())
10378         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10379
10380       // The trampoline may have been bitcast to a bogus type (FTy).
10381       // Handle this by synthesizing a new function type, equal to FTy
10382       // with the chain parameter inserted.
10383
10384       std::vector<const Type*> NewTypes;
10385       NewTypes.reserve(FTy->getNumParams()+1);
10386
10387       // Insert the chain's type into the list of parameter types, which may
10388       // mean appending it.
10389       {
10390         unsigned Idx = 1;
10391         FunctionType::param_iterator I = FTy->param_begin(),
10392           E = FTy->param_end();
10393
10394         do {
10395           if (Idx == NestIdx)
10396             // Add the chain's type.
10397             NewTypes.push_back(NestTy);
10398
10399           if (I == E)
10400             break;
10401
10402           // Add the original type.
10403           NewTypes.push_back(*I);
10404
10405           ++Idx, ++I;
10406         } while (1);
10407       }
10408
10409       // Replace the trampoline call with a direct call.  Let the generic
10410       // code sort out any function type mismatches.
10411       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 
10412                                                 FTy->isVarArg());
10413       Constant *NewCallee =
10414         NestF->getType() == PointerType::getUnqual(NewFTy) ?
10415         NestF : ConstantExpr::getBitCast(NestF, 
10416                                          PointerType::getUnqual(NewFTy));
10417       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10418                                                    NewAttrs.end());
10419
10420       Instruction *NewCaller;
10421       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10422         NewCaller = InvokeInst::Create(NewCallee,
10423                                        II->getNormalDest(), II->getUnwindDest(),
10424                                        NewArgs.begin(), NewArgs.end(),
10425                                        Caller->getName(), Caller);
10426         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10427         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10428       } else {
10429         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10430                                      Caller->getName(), Caller);
10431         if (cast<CallInst>(Caller)->isTailCall())
10432           cast<CallInst>(NewCaller)->setTailCall();
10433         cast<CallInst>(NewCaller)->
10434           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10435         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10436       }
10437       if (!Caller->getType()->isVoidTy())
10438         Caller->replaceAllUsesWith(NewCaller);
10439       Caller->eraseFromParent();
10440       Worklist.Remove(Caller);
10441       return 0;
10442     }
10443   }
10444
10445   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10446   // parameter, there is no need to adjust the argument list.  Let the generic
10447   // code sort out any function type mismatches.
10448   Constant *NewCallee =
10449     NestF->getType() == PTy ? NestF : 
10450                               ConstantExpr::getBitCast(NestF, PTy);
10451   CS.setCalledFunction(NewCallee);
10452   return CS.getInstruction();
10453 }
10454
10455 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10456 /// and if a/b/c and the add's all have a single use, turn this into a phi
10457 /// and a single binop.
10458 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10459   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10460   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10461   unsigned Opc = FirstInst->getOpcode();
10462   Value *LHSVal = FirstInst->getOperand(0);
10463   Value *RHSVal = FirstInst->getOperand(1);
10464     
10465   const Type *LHSType = LHSVal->getType();
10466   const Type *RHSType = RHSVal->getType();
10467   
10468   // Scan to see if all operands are the same opcode, and all have one use.
10469   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10470     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10471     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10472         // Verify type of the LHS matches so we don't fold cmp's of different
10473         // types or GEP's with different index types.
10474         I->getOperand(0)->getType() != LHSType ||
10475         I->getOperand(1)->getType() != RHSType)
10476       return 0;
10477
10478     // If they are CmpInst instructions, check their predicates
10479     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10480       if (cast<CmpInst>(I)->getPredicate() !=
10481           cast<CmpInst>(FirstInst)->getPredicate())
10482         return 0;
10483     
10484     // Keep track of which operand needs a phi node.
10485     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10486     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10487   }
10488
10489   // If both LHS and RHS would need a PHI, don't do this transformation,
10490   // because it would increase the number of PHIs entering the block,
10491   // which leads to higher register pressure. This is especially
10492   // bad when the PHIs are in the header of a loop.
10493   if (!LHSVal && !RHSVal)
10494     return 0;
10495   
10496   // Otherwise, this is safe to transform!
10497   
10498   Value *InLHS = FirstInst->getOperand(0);
10499   Value *InRHS = FirstInst->getOperand(1);
10500   PHINode *NewLHS = 0, *NewRHS = 0;
10501   if (LHSVal == 0) {
10502     NewLHS = PHINode::Create(LHSType,
10503                              FirstInst->getOperand(0)->getName() + ".pn");
10504     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10505     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10506     InsertNewInstBefore(NewLHS, PN);
10507     LHSVal = NewLHS;
10508   }
10509   
10510   if (RHSVal == 0) {
10511     NewRHS = PHINode::Create(RHSType,
10512                              FirstInst->getOperand(1)->getName() + ".pn");
10513     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10514     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10515     InsertNewInstBefore(NewRHS, PN);
10516     RHSVal = NewRHS;
10517   }
10518   
10519   // Add all operands to the new PHIs.
10520   if (NewLHS || NewRHS) {
10521     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10522       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10523       if (NewLHS) {
10524         Value *NewInLHS = InInst->getOperand(0);
10525         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10526       }
10527       if (NewRHS) {
10528         Value *NewInRHS = InInst->getOperand(1);
10529         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10530       }
10531     }
10532   }
10533     
10534   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10535     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10536   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10537   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10538                          LHSVal, RHSVal);
10539 }
10540
10541 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10542   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10543   
10544   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10545                                         FirstInst->op_end());
10546   // This is true if all GEP bases are allocas and if all indices into them are
10547   // constants.
10548   bool AllBasePointersAreAllocas = true;
10549
10550   // We don't want to replace this phi if the replacement would require
10551   // more than one phi, which leads to higher register pressure. This is
10552   // especially bad when the PHIs are in the header of a loop.
10553   bool NeededPhi = false;
10554   
10555   // Scan to see if all operands are the same opcode, and all have one use.
10556   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10557     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10558     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10559       GEP->getNumOperands() != FirstInst->getNumOperands())
10560       return 0;
10561
10562     // Keep track of whether or not all GEPs are of alloca pointers.
10563     if (AllBasePointersAreAllocas &&
10564         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10565          !GEP->hasAllConstantIndices()))
10566       AllBasePointersAreAllocas = false;
10567     
10568     // Compare the operand lists.
10569     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10570       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10571         continue;
10572       
10573       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10574       // if one of the PHIs has a constant for the index.  The index may be
10575       // substantially cheaper to compute for the constants, so making it a
10576       // variable index could pessimize the path.  This also handles the case
10577       // for struct indices, which must always be constant.
10578       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10579           isa<ConstantInt>(GEP->getOperand(op)))
10580         return 0;
10581       
10582       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10583         return 0;
10584
10585       // If we already needed a PHI for an earlier operand, and another operand
10586       // also requires a PHI, we'd be introducing more PHIs than we're
10587       // eliminating, which increases register pressure on entry to the PHI's
10588       // block.
10589       if (NeededPhi)
10590         return 0;
10591
10592       FixedOperands[op] = 0;  // Needs a PHI.
10593       NeededPhi = true;
10594     }
10595   }
10596   
10597   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10598   // bother doing this transformation.  At best, this will just save a bit of
10599   // offset calculation, but all the predecessors will have to materialize the
10600   // stack address into a register anyway.  We'd actually rather *clone* the
10601   // load up into the predecessors so that we have a load of a gep of an alloca,
10602   // which can usually all be folded into the load.
10603   if (AllBasePointersAreAllocas)
10604     return 0;
10605   
10606   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10607   // that is variable.
10608   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10609   
10610   bool HasAnyPHIs = false;
10611   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10612     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10613     Value *FirstOp = FirstInst->getOperand(i);
10614     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10615                                      FirstOp->getName()+".pn");
10616     InsertNewInstBefore(NewPN, PN);
10617     
10618     NewPN->reserveOperandSpace(e);
10619     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10620     OperandPhis[i] = NewPN;
10621     FixedOperands[i] = NewPN;
10622     HasAnyPHIs = true;
10623   }
10624
10625   
10626   // Add all operands to the new PHIs.
10627   if (HasAnyPHIs) {
10628     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10629       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10630       BasicBlock *InBB = PN.getIncomingBlock(i);
10631       
10632       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10633         if (PHINode *OpPhi = OperandPhis[op])
10634           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10635     }
10636   }
10637   
10638   Value *Base = FixedOperands[0];
10639   return cast<GEPOperator>(FirstInst)->isInBounds() ?
10640     GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10641                                       FixedOperands.end()) :
10642     GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10643                               FixedOperands.end());
10644 }
10645
10646
10647 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10648 /// sink the load out of the block that defines it.  This means that it must be
10649 /// obvious the value of the load is not changed from the point of the load to
10650 /// the end of the block it is in.
10651 ///
10652 /// Finally, it is safe, but not profitable, to sink a load targetting a
10653 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10654 /// to a register.
10655 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10656   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10657   
10658   for (++BBI; BBI != E; ++BBI)
10659     if (BBI->mayWriteToMemory())
10660       return false;
10661   
10662   // Check for non-address taken alloca.  If not address-taken already, it isn't
10663   // profitable to do this xform.
10664   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10665     bool isAddressTaken = false;
10666     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10667          UI != E; ++UI) {
10668       if (isa<LoadInst>(UI)) continue;
10669       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10670         // If storing TO the alloca, then the address isn't taken.
10671         if (SI->getOperand(1) == AI) continue;
10672       }
10673       isAddressTaken = true;
10674       break;
10675     }
10676     
10677     if (!isAddressTaken && AI->isStaticAlloca())
10678       return false;
10679   }
10680   
10681   // If this load is a load from a GEP with a constant offset from an alloca,
10682   // then we don't want to sink it.  In its present form, it will be
10683   // load [constant stack offset].  Sinking it will cause us to have to
10684   // materialize the stack addresses in each predecessor in a register only to
10685   // do a shared load from register in the successor.
10686   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10687     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10688       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10689         return false;
10690   
10691   return true;
10692 }
10693
10694
10695 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10696 // operator and they all are only used by the PHI, PHI together their
10697 // inputs, and do the operation once, to the result of the PHI.
10698 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10699   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10700
10701   // Scan the instruction, looking for input operations that can be folded away.
10702   // If all input operands to the phi are the same instruction (e.g. a cast from
10703   // the same type or "+42") we can pull the operation through the PHI, reducing
10704   // code size and simplifying code.
10705   Constant *ConstantOp = 0;
10706   const Type *CastSrcTy = 0;
10707   bool isVolatile = false;
10708   if (isa<CastInst>(FirstInst)) {
10709     CastSrcTy = FirstInst->getOperand(0)->getType();
10710   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10711     // Can fold binop, compare or shift here if the RHS is a constant, 
10712     // otherwise call FoldPHIArgBinOpIntoPHI.
10713     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10714     if (ConstantOp == 0)
10715       return FoldPHIArgBinOpIntoPHI(PN);
10716   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10717     isVolatile = LI->isVolatile();
10718     // We can't sink the load if the loaded value could be modified between the
10719     // load and the PHI.
10720     if (LI->getParent() != PN.getIncomingBlock(0) ||
10721         !isSafeAndProfitableToSinkLoad(LI))
10722       return 0;
10723     
10724     // If the PHI is of volatile loads and the load block has multiple
10725     // successors, sinking it would remove a load of the volatile value from
10726     // the path through the other successor.
10727     if (isVolatile &&
10728         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10729       return 0;
10730     
10731   } else if (isa<GetElementPtrInst>(FirstInst)) {
10732     return FoldPHIArgGEPIntoPHI(PN);
10733   } else {
10734     return 0;  // Cannot fold this operation.
10735   }
10736
10737   // Check to see if all arguments are the same operation.
10738   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10739     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10740     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10741     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10742       return 0;
10743     if (CastSrcTy) {
10744       if (I->getOperand(0)->getType() != CastSrcTy)
10745         return 0;  // Cast operation must match.
10746     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10747       // We can't sink the load if the loaded value could be modified between 
10748       // the load and the PHI.
10749       if (LI->isVolatile() != isVolatile ||
10750           LI->getParent() != PN.getIncomingBlock(i) ||
10751           !isSafeAndProfitableToSinkLoad(LI))
10752         return 0;
10753       
10754       // If the PHI is of volatile loads and the load block has multiple
10755       // successors, sinking it would remove a load of the volatile value from
10756       // the path through the other successor.
10757       if (isVolatile &&
10758           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10759         return 0;
10760       
10761     } else if (I->getOperand(1) != ConstantOp) {
10762       return 0;
10763     }
10764   }
10765
10766   // Okay, they are all the same operation.  Create a new PHI node of the
10767   // correct type, and PHI together all of the LHS's of the instructions.
10768   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10769                                    PN.getName()+".in");
10770   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10771
10772   Value *InVal = FirstInst->getOperand(0);
10773   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10774
10775   // Add all operands to the new PHI.
10776   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10777     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10778     if (NewInVal != InVal)
10779       InVal = 0;
10780     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10781   }
10782
10783   Value *PhiVal;
10784   if (InVal) {
10785     // The new PHI unions all of the same values together.  This is really
10786     // common, so we handle it intelligently here for compile-time speed.
10787     PhiVal = InVal;
10788     delete NewPN;
10789   } else {
10790     InsertNewInstBefore(NewPN, PN);
10791     PhiVal = NewPN;
10792   }
10793
10794   // Insert and return the new operation.
10795   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10796     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10797   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10798     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10799   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10800     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10801                            PhiVal, ConstantOp);
10802   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10803   
10804   // If this was a volatile load that we are merging, make sure to loop through
10805   // and mark all the input loads as non-volatile.  If we don't do this, we will
10806   // insert a new volatile load and the old ones will not be deletable.
10807   if (isVolatile)
10808     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10809       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10810   
10811   return new LoadInst(PhiVal, "", isVolatile);
10812 }
10813
10814 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10815 /// that is dead.
10816 static bool DeadPHICycle(PHINode *PN,
10817                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10818   if (PN->use_empty()) return true;
10819   if (!PN->hasOneUse()) return false;
10820
10821   // Remember this node, and if we find the cycle, return.
10822   if (!PotentiallyDeadPHIs.insert(PN))
10823     return true;
10824   
10825   // Don't scan crazily complex things.
10826   if (PotentiallyDeadPHIs.size() == 16)
10827     return false;
10828
10829   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10830     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10831
10832   return false;
10833 }
10834
10835 /// PHIsEqualValue - Return true if this phi node is always equal to
10836 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10837 ///   z = some value; x = phi (y, z); y = phi (x, z)
10838 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10839                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10840   // See if we already saw this PHI node.
10841   if (!ValueEqualPHIs.insert(PN))
10842     return true;
10843   
10844   // Don't scan crazily complex things.
10845   if (ValueEqualPHIs.size() == 16)
10846     return false;
10847  
10848   // Scan the operands to see if they are either phi nodes or are equal to
10849   // the value.
10850   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10851     Value *Op = PN->getIncomingValue(i);
10852     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10853       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10854         return false;
10855     } else if (Op != NonPhiInVal)
10856       return false;
10857   }
10858   
10859   return true;
10860 }
10861
10862
10863 // PHINode simplification
10864 //
10865 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10866   // If LCSSA is around, don't mess with Phi nodes
10867   if (MustPreserveLCSSA) return 0;
10868   
10869   if (Value *V = PN.hasConstantValue())
10870     return ReplaceInstUsesWith(PN, V);
10871
10872   // If all PHI operands are the same operation, pull them through the PHI,
10873   // reducing code size.
10874   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10875       isa<Instruction>(PN.getIncomingValue(1)) &&
10876       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10877       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10878       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10879       // than themselves more than once.
10880       PN.getIncomingValue(0)->hasOneUse())
10881     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10882       return Result;
10883
10884   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10885   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10886   // PHI)... break the cycle.
10887   if (PN.hasOneUse()) {
10888     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10889     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10890       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10891       PotentiallyDeadPHIs.insert(&PN);
10892       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10893         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10894     }
10895    
10896     // If this phi has a single use, and if that use just computes a value for
10897     // the next iteration of a loop, delete the phi.  This occurs with unused
10898     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10899     // common case here is good because the only other things that catch this
10900     // are induction variable analysis (sometimes) and ADCE, which is only run
10901     // late.
10902     if (PHIUser->hasOneUse() &&
10903         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10904         PHIUser->use_back() == &PN) {
10905       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10906     }
10907   }
10908
10909   // We sometimes end up with phi cycles that non-obviously end up being the
10910   // same value, for example:
10911   //   z = some value; x = phi (y, z); y = phi (x, z)
10912   // where the phi nodes don't necessarily need to be in the same block.  Do a
10913   // quick check to see if the PHI node only contains a single non-phi value, if
10914   // so, scan to see if the phi cycle is actually equal to that value.
10915   {
10916     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10917     // Scan for the first non-phi operand.
10918     while (InValNo != NumOperandVals && 
10919            isa<PHINode>(PN.getIncomingValue(InValNo)))
10920       ++InValNo;
10921
10922     if (InValNo != NumOperandVals) {
10923       Value *NonPhiInVal = PN.getOperand(InValNo);
10924       
10925       // Scan the rest of the operands to see if there are any conflicts, if so
10926       // there is no need to recursively scan other phis.
10927       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10928         Value *OpVal = PN.getIncomingValue(InValNo);
10929         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10930           break;
10931       }
10932       
10933       // If we scanned over all operands, then we have one unique value plus
10934       // phi values.  Scan PHI nodes to see if they all merge in each other or
10935       // the value.
10936       if (InValNo == NumOperandVals) {
10937         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10938         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10939           return ReplaceInstUsesWith(PN, NonPhiInVal);
10940       }
10941     }
10942   }
10943   return 0;
10944 }
10945
10946 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10947   Value *PtrOp = GEP.getOperand(0);
10948   // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
10949   if (GEP.getNumOperands() == 1)
10950     return ReplaceInstUsesWith(GEP, PtrOp);
10951
10952   if (isa<UndefValue>(GEP.getOperand(0)))
10953     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10954
10955   bool HasZeroPointerIndex = false;
10956   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10957     HasZeroPointerIndex = C->isNullValue();
10958
10959   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10960     return ReplaceInstUsesWith(GEP, PtrOp);
10961
10962   // Eliminate unneeded casts for indices.
10963   if (TD) {
10964     bool MadeChange = false;
10965     unsigned PtrSize = TD->getPointerSizeInBits();
10966     
10967     gep_type_iterator GTI = gep_type_begin(GEP);
10968     for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10969          I != E; ++I, ++GTI) {
10970       if (!isa<SequentialType>(*GTI)) continue;
10971       
10972       // If we are using a wider index than needed for this platform, shrink it
10973       // to what we need.  If narrower, sign-extend it to what we need.  This
10974       // explicit cast can make subsequent optimizations more obvious.
10975       unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
10976       if (OpBits == PtrSize)
10977         continue;
10978       
10979       *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
10980       MadeChange = true;
10981     }
10982     if (MadeChange) return &GEP;
10983   }
10984
10985   // Combine Indices - If the source pointer to this getelementptr instruction
10986   // is a getelementptr instruction, combine the indices of the two
10987   // getelementptr instructions into a single instruction.
10988   //
10989   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
10990     // Note that if our source is a gep chain itself that we wait for that
10991     // chain to be resolved before we perform this transformation.  This
10992     // avoids us creating a TON of code in some cases.
10993     //
10994     if (GetElementPtrInst *SrcGEP =
10995           dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10996       if (SrcGEP->getNumOperands() == 2)
10997         return 0;   // Wait until our source is folded to completion.
10998
10999     SmallVector<Value*, 8> Indices;
11000
11001     // Find out whether the last index in the source GEP is a sequential idx.
11002     bool EndsWithSequential = false;
11003     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11004          I != E; ++I)
11005       EndsWithSequential = !isa<StructType>(*I);
11006
11007     // Can we combine the two pointer arithmetics offsets?
11008     if (EndsWithSequential) {
11009       // Replace: gep (gep %P, long B), long A, ...
11010       // With:    T = long A+B; gep %P, T, ...
11011       //
11012       Value *Sum;
11013       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11014       Value *GO1 = GEP.getOperand(1);
11015       if (SO1 == Constant::getNullValue(SO1->getType())) {
11016         Sum = GO1;
11017       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
11018         Sum = SO1;
11019       } else {
11020         // If they aren't the same type, then the input hasn't been processed
11021         // by the loop above yet (which canonicalizes sequential index types to
11022         // intptr_t).  Just avoid transforming this until the input has been
11023         // normalized.
11024         if (SO1->getType() != GO1->getType())
11025           return 0;
11026         Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11027       }
11028
11029       // Update the GEP in place if possible.
11030       if (Src->getNumOperands() == 2) {
11031         GEP.setOperand(0, Src->getOperand(0));
11032         GEP.setOperand(1, Sum);
11033         return &GEP;
11034       }
11035       Indices.append(Src->op_begin()+1, Src->op_end()-1);
11036       Indices.push_back(Sum);
11037       Indices.append(GEP.op_begin()+2, GEP.op_end());
11038     } else if (isa<Constant>(*GEP.idx_begin()) &&
11039                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11040                Src->getNumOperands() != 1) {
11041       // Otherwise we can do the fold if the first index of the GEP is a zero
11042       Indices.append(Src->op_begin()+1, Src->op_end());
11043       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
11044     }
11045
11046     if (!Indices.empty())
11047       return (cast<GEPOperator>(&GEP)->isInBounds() &&
11048               Src->isInBounds()) ?
11049         GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11050                                           Indices.end(), GEP.getName()) :
11051         GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
11052                                   Indices.end(), GEP.getName());
11053   }
11054   
11055   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11056   if (Value *X = getBitCastOperand(PtrOp)) {
11057     assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
11058
11059     // If the input bitcast is actually "bitcast(bitcast(x))", then we don't 
11060     // want to change the gep until the bitcasts are eliminated.
11061     if (getBitCastOperand(X)) {
11062       Worklist.AddValue(PtrOp);
11063       return 0;
11064     }
11065     
11066     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11067     // into     : GEP [10 x i8]* X, i32 0, ...
11068     //
11069     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11070     //           into     : GEP i8* X, ...
11071     // 
11072     // This occurs when the program declares an array extern like "int X[];"
11073     if (HasZeroPointerIndex) {
11074       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11075       const PointerType *XTy = cast<PointerType>(X->getType());
11076       if (const ArrayType *CATy =
11077           dyn_cast<ArrayType>(CPTy->getElementType())) {
11078         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11079         if (CATy->getElementType() == XTy->getElementType()) {
11080           // -> GEP i8* X, ...
11081           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11082           return cast<GEPOperator>(&GEP)->isInBounds() ?
11083             GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11084                                               GEP.getName()) :
11085             GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11086                                       GEP.getName());
11087         }
11088         
11089         if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
11090           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11091           if (CATy->getElementType() == XATy->getElementType()) {
11092             // -> GEP [10 x i8]* X, i32 0, ...
11093             // At this point, we know that the cast source type is a pointer
11094             // to an array of the same type as the destination pointer
11095             // array.  Because the array type is never stepped over (there
11096             // is a leading zero) we can fold the cast into this GEP.
11097             GEP.setOperand(0, X);
11098             return &GEP;
11099           }
11100         }
11101       }
11102     } else if (GEP.getNumOperands() == 2) {
11103       // Transform things like:
11104       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11105       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11106       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11107       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11108       if (TD && isa<ArrayType>(SrcElTy) &&
11109           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11110           TD->getTypeAllocSize(ResElTy)) {
11111         Value *Idx[2];
11112         Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11113         Idx[1] = GEP.getOperand(1);
11114         Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11115           Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11116           Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11117         // V and GEP are both pointer types --> BitCast
11118         return new BitCastInst(NewGEP, GEP.getType());
11119       }
11120       
11121       // Transform things like:
11122       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11123       //   (where tmp = 8*tmp2) into:
11124       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11125       
11126       if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
11127         uint64_t ArrayEltSize =
11128             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11129         
11130         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11131         // allow either a mul, shift, or constant here.
11132         Value *NewIdx = 0;
11133         ConstantInt *Scale = 0;
11134         if (ArrayEltSize == 1) {
11135           NewIdx = GEP.getOperand(1);
11136           Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11137         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11138           NewIdx = ConstantInt::get(CI->getType(), 1);
11139           Scale = CI;
11140         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11141           if (Inst->getOpcode() == Instruction::Shl &&
11142               isa<ConstantInt>(Inst->getOperand(1))) {
11143             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11144             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11145             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11146                                      1ULL << ShAmtVal);
11147             NewIdx = Inst->getOperand(0);
11148           } else if (Inst->getOpcode() == Instruction::Mul &&
11149                      isa<ConstantInt>(Inst->getOperand(1))) {
11150             Scale = cast<ConstantInt>(Inst->getOperand(1));
11151             NewIdx = Inst->getOperand(0);
11152           }
11153         }
11154         
11155         // If the index will be to exactly the right offset with the scale taken
11156         // out, perform the transformation. Note, we don't know whether Scale is
11157         // signed or not. We'll use unsigned version of division/modulo
11158         // operation after making sure Scale doesn't have the sign bit set.
11159         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11160             Scale->getZExtValue() % ArrayEltSize == 0) {
11161           Scale = ConstantInt::get(Scale->getType(),
11162                                    Scale->getZExtValue() / ArrayEltSize);
11163           if (Scale->getZExtValue() != 1) {
11164             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11165                                                        false /*ZExt*/);
11166             NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
11167           }
11168
11169           // Insert the new GEP instruction.
11170           Value *Idx[2];
11171           Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11172           Idx[1] = NewIdx;
11173           Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11174             Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11175             Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11176           // The NewGEP must be pointer typed, so must the old one -> BitCast
11177           return new BitCastInst(NewGEP, GEP.getType());
11178         }
11179       }
11180     }
11181   }
11182   
11183   /// See if we can simplify:
11184   ///   X = bitcast A* to B*
11185   ///   Y = gep X, <...constant indices...>
11186   /// into a gep of the original struct.  This is important for SROA and alias
11187   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11188   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11189     if (TD &&
11190         !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11191       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11192       // a constant back from EmitGEPOffset.
11193       ConstantInt *OffsetV =
11194                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11195       int64_t Offset = OffsetV->getSExtValue();
11196       
11197       // If this GEP instruction doesn't move the pointer, just replace the GEP
11198       // with a bitcast of the real input to the dest type.
11199       if (Offset == 0) {
11200         // If the bitcast is of an allocation, and the allocation will be
11201         // converted to match the type of the cast, don't touch this.
11202         if (isa<AllocationInst>(BCI->getOperand(0)) ||
11203             isMalloc(BCI->getOperand(0))) {
11204           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11205           if (Instruction *I = visitBitCast(*BCI)) {
11206             if (I != BCI) {
11207               I->takeName(BCI);
11208               BCI->getParent()->getInstList().insert(BCI, I);
11209               ReplaceInstUsesWith(*BCI, I);
11210             }
11211             return &GEP;
11212           }
11213         }
11214         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11215       }
11216       
11217       // Otherwise, if the offset is non-zero, we need to find out if there is a
11218       // field at Offset in 'A's type.  If so, we can pull the cast through the
11219       // GEP.
11220       SmallVector<Value*, 8> NewIndices;
11221       const Type *InTy =
11222         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11223       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11224         Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11225           Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11226                                      NewIndices.end()) :
11227           Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11228                              NewIndices.end());
11229         
11230         if (NGEP->getType() == GEP.getType())
11231           return ReplaceInstUsesWith(GEP, NGEP);
11232         NGEP->takeName(&GEP);
11233         return new BitCastInst(NGEP, GEP.getType());
11234       }
11235     }
11236   }    
11237     
11238   return 0;
11239 }
11240
11241 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11242   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11243   if (AI.isArrayAllocation()) {  // Check C != 1
11244     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11245       const Type *NewTy = 
11246         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11247       assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11248       AllocationInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
11249       New->setAlignment(AI.getAlignment());
11250
11251       // Scan to the end of the allocation instructions, to skip over a block of
11252       // allocas if possible...also skip interleaved debug info
11253       //
11254       BasicBlock::iterator It = New;
11255       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11256
11257       // Now that I is pointing to the first non-allocation-inst in the block,
11258       // insert our getelementptr instruction...
11259       //
11260       Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
11261       Value *Idx[2];
11262       Idx[0] = NullIdx;
11263       Idx[1] = NullIdx;
11264       Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11265                                                    New->getName()+".sub", It);
11266
11267       // Now make everything use the getelementptr instead of the original
11268       // allocation.
11269       return ReplaceInstUsesWith(AI, V);
11270     } else if (isa<UndefValue>(AI.getArraySize())) {
11271       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11272     }
11273   }
11274
11275   if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11276     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11277     // Note that we only do this for alloca's, because malloc should allocate
11278     // and return a unique pointer, even for a zero byte allocation.
11279     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11280       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11281
11282     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11283     if (AI.getAlignment() == 0)
11284       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11285   }
11286
11287   return 0;
11288 }
11289
11290 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11291   Value *Op = FI.getOperand(0);
11292
11293   // free undef -> unreachable.
11294   if (isa<UndefValue>(Op)) {
11295     // Insert a new store to null because we cannot modify the CFG here.
11296     new StoreInst(ConstantInt::getTrue(*Context),
11297            UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
11298     return EraseInstFromFunction(FI);
11299   }
11300   
11301   // If we have 'free null' delete the instruction.  This can happen in stl code
11302   // when lots of inlining happens.
11303   if (isa<ConstantPointerNull>(Op))
11304     return EraseInstFromFunction(FI);
11305   
11306   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11307   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11308     FI.setOperand(0, CI->getOperand(0));
11309     return &FI;
11310   }
11311   
11312   // Change free (gep X, 0,0,0,0) into free(X)
11313   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11314     if (GEPI->hasAllZeroIndices()) {
11315       Worklist.Add(GEPI);
11316       FI.setOperand(0, GEPI->getOperand(0));
11317       return &FI;
11318     }
11319   }
11320   
11321   if (isMalloc(Op)) {
11322     if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11323       if (Op->hasOneUse() && CI->hasOneUse()) {
11324         EraseInstFromFunction(FI);
11325         EraseInstFromFunction(*CI);
11326         return EraseInstFromFunction(*cast<Instruction>(Op));
11327       }
11328     } else {
11329       // Op is a call to malloc
11330       if (Op->hasOneUse()) {
11331         EraseInstFromFunction(FI);
11332         return EraseInstFromFunction(*cast<Instruction>(Op));
11333       }
11334     }
11335   }
11336
11337   return 0;
11338 }
11339
11340
11341 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11342 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11343                                         const TargetData *TD) {
11344   User *CI = cast<User>(LI.getOperand(0));
11345   Value *CastOp = CI->getOperand(0);
11346   LLVMContext *Context = IC.getContext();
11347
11348   if (TD) {
11349     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11350       // Instead of loading constant c string, use corresponding integer value
11351       // directly if string length is small enough.
11352       std::string Str;
11353       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11354         unsigned len = Str.length();
11355         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11356         unsigned numBits = Ty->getPrimitiveSizeInBits();
11357         // Replace LI with immediate integer store.
11358         if ((numBits >> 3) == len + 1) {
11359           APInt StrVal(numBits, 0);
11360           APInt SingleChar(numBits, 0);
11361           if (TD->isLittleEndian()) {
11362             for (signed i = len-1; i >= 0; i--) {
11363               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11364               StrVal = (StrVal << 8) | SingleChar;
11365             }
11366           } else {
11367             for (unsigned i = 0; i < len; i++) {
11368               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11369               StrVal = (StrVal << 8) | SingleChar;
11370             }
11371             // Append NULL at the end.
11372             SingleChar = 0;
11373             StrVal = (StrVal << 8) | SingleChar;
11374           }
11375           Value *NL = ConstantInt::get(*Context, StrVal);
11376           return IC.ReplaceInstUsesWith(LI, NL);
11377         }
11378       }
11379     }
11380   }
11381
11382   const PointerType *DestTy = cast<PointerType>(CI->getType());
11383   const Type *DestPTy = DestTy->getElementType();
11384   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11385
11386     // If the address spaces don't match, don't eliminate the cast.
11387     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11388       return 0;
11389
11390     const Type *SrcPTy = SrcTy->getElementType();
11391
11392     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11393          isa<VectorType>(DestPTy)) {
11394       // If the source is an array, the code below will not succeed.  Check to
11395       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11396       // constants.
11397       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11398         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11399           if (ASrcTy->getNumElements() != 0) {
11400             Value *Idxs[2];
11401             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
11402             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11403             SrcTy = cast<PointerType>(CastOp->getType());
11404             SrcPTy = SrcTy->getElementType();
11405           }
11406
11407       if (IC.getTargetData() &&
11408           (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11409             isa<VectorType>(SrcPTy)) &&
11410           // Do not allow turning this into a load of an integer, which is then
11411           // casted to a pointer, this pessimizes pointer analysis a lot.
11412           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11413           IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11414                IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11415
11416         // Okay, we are casting from one integer or pointer type to another of
11417         // the same size.  Instead of casting the pointer before the load, cast
11418         // the result of the loaded value.
11419         Value *NewLoad = 
11420           IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
11421         // Now cast the result of the load.
11422         return new BitCastInst(NewLoad, LI.getType());
11423       }
11424     }
11425   }
11426   return 0;
11427 }
11428
11429 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11430   Value *Op = LI.getOperand(0);
11431
11432   // Attempt to improve the alignment.
11433   if (TD) {
11434     unsigned KnownAlign =
11435       GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11436     if (KnownAlign >
11437         (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11438                                   LI.getAlignment()))
11439       LI.setAlignment(KnownAlign);
11440   }
11441
11442   // load (cast X) --> cast (load X) iff safe.
11443   if (isa<CastInst>(Op))
11444     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11445       return Res;
11446
11447   // None of the following transforms are legal for volatile loads.
11448   if (LI.isVolatile()) return 0;
11449   
11450   // Do really simple store-to-load forwarding and load CSE, to catch cases
11451   // where there are several consequtive memory accesses to the same location,
11452   // separated by a few arithmetic operations.
11453   BasicBlock::iterator BBI = &LI;
11454   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11455     return ReplaceInstUsesWith(LI, AvailableVal);
11456
11457   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11458     const Value *GEPI0 = GEPI->getOperand(0);
11459     // TODO: Consider a target hook for valid address spaces for this xform.
11460     if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
11461       // Insert a new store to null instruction before the load to indicate
11462       // that this code is not reachable.  We do this instead of inserting
11463       // an unreachable instruction directly because we cannot modify the
11464       // CFG.
11465       new StoreInst(UndefValue::get(LI.getType()),
11466                     Constant::getNullValue(Op->getType()), &LI);
11467       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11468     }
11469   } 
11470
11471   if (Constant *C = dyn_cast<Constant>(Op)) {
11472     // load null/undef -> undef
11473     // TODO: Consider a target hook for valid address spaces for this xform.
11474     if (isa<UndefValue>(C) ||
11475         (C->isNullValue() && LI.getPointerAddressSpace() == 0)) {
11476       // Insert a new store to null instruction before the load to indicate that
11477       // this code is not reachable.  We do this instead of inserting an
11478       // unreachable instruction directly because we cannot modify the CFG.
11479       new StoreInst(UndefValue::get(LI.getType()),
11480                     Constant::getNullValue(Op->getType()), &LI);
11481       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11482     }
11483
11484     // Instcombine load (constant global) into the value loaded.
11485     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11486       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11487         return ReplaceInstUsesWith(LI, GV->getInitializer());
11488
11489     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11490     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11491       if (CE->getOpcode() == Instruction::GetElementPtr) {
11492         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11493           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11494             if (Constant *V = 
11495                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
11496               return ReplaceInstUsesWith(LI, V);
11497         if (CE->getOperand(0)->isNullValue()) {
11498           // Insert a new store to null instruction before the load to indicate
11499           // that this code is not reachable.  We do this instead of inserting
11500           // an unreachable instruction directly because we cannot modify the
11501           // CFG.
11502           new StoreInst(UndefValue::get(LI.getType()),
11503                         Constant::getNullValue(Op->getType()), &LI);
11504           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11505         }
11506
11507       } else if (CE->isCast()) {
11508         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11509           return Res;
11510       }
11511     }
11512   }
11513     
11514   // If this load comes from anywhere in a constant global, and if the global
11515   // is all undef or zero, we know what it loads.
11516   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11517     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11518       if (GV->getInitializer()->isNullValue())
11519         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11520       else if (isa<UndefValue>(GV->getInitializer()))
11521         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11522     }
11523   }
11524
11525   if (Op->hasOneUse()) {
11526     // Change select and PHI nodes to select values instead of addresses: this
11527     // helps alias analysis out a lot, allows many others simplifications, and
11528     // exposes redundancy in the code.
11529     //
11530     // Note that we cannot do the transformation unless we know that the
11531     // introduced loads cannot trap!  Something like this is valid as long as
11532     // the condition is always false: load (select bool %C, int* null, int* %G),
11533     // but it would not be valid if we transformed it to load from null
11534     // unconditionally.
11535     //
11536     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11537       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11538       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11539           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11540         Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11541                                         SI->getOperand(1)->getName()+".val");
11542         Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11543                                         SI->getOperand(2)->getName()+".val");
11544         return SelectInst::Create(SI->getCondition(), V1, V2);
11545       }
11546
11547       // load (select (cond, null, P)) -> load P
11548       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11549         if (C->isNullValue()) {
11550           LI.setOperand(0, SI->getOperand(2));
11551           return &LI;
11552         }
11553
11554       // load (select (cond, P, null)) -> load P
11555       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11556         if (C->isNullValue()) {
11557           LI.setOperand(0, SI->getOperand(1));
11558           return &LI;
11559         }
11560     }
11561   }
11562   return 0;
11563 }
11564
11565 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11566 /// when possible.  This makes it generally easy to do alias analysis and/or
11567 /// SROA/mem2reg of the memory object.
11568 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11569   User *CI = cast<User>(SI.getOperand(1));
11570   Value *CastOp = CI->getOperand(0);
11571
11572   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11573   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11574   if (SrcTy == 0) return 0;
11575   
11576   const Type *SrcPTy = SrcTy->getElementType();
11577
11578   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11579     return 0;
11580   
11581   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11582   /// to its first element.  This allows us to handle things like:
11583   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11584   /// on 32-bit hosts.
11585   SmallVector<Value*, 4> NewGEPIndices;
11586   
11587   // If the source is an array, the code below will not succeed.  Check to
11588   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11589   // constants.
11590   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11591     // Index through pointer.
11592     Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
11593     NewGEPIndices.push_back(Zero);
11594     
11595     while (1) {
11596       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11597         if (!STy->getNumElements()) /* Struct can be empty {} */
11598           break;
11599         NewGEPIndices.push_back(Zero);
11600         SrcPTy = STy->getElementType(0);
11601       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11602         NewGEPIndices.push_back(Zero);
11603         SrcPTy = ATy->getElementType();
11604       } else {
11605         break;
11606       }
11607     }
11608     
11609     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11610   }
11611
11612   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11613     return 0;
11614   
11615   // If the pointers point into different address spaces or if they point to
11616   // values with different sizes, we can't do the transformation.
11617   if (!IC.getTargetData() ||
11618       SrcTy->getAddressSpace() != 
11619         cast<PointerType>(CI->getType())->getAddressSpace() ||
11620       IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11621       IC.getTargetData()->getTypeSizeInBits(DestPTy))
11622     return 0;
11623
11624   // Okay, we are casting from one integer or pointer type to another of
11625   // the same size.  Instead of casting the pointer before 
11626   // the store, cast the value to be stored.
11627   Value *NewCast;
11628   Value *SIOp0 = SI.getOperand(0);
11629   Instruction::CastOps opcode = Instruction::BitCast;
11630   const Type* CastSrcTy = SIOp0->getType();
11631   const Type* CastDstTy = SrcPTy;
11632   if (isa<PointerType>(CastDstTy)) {
11633     if (CastSrcTy->isInteger())
11634       opcode = Instruction::IntToPtr;
11635   } else if (isa<IntegerType>(CastDstTy)) {
11636     if (isa<PointerType>(SIOp0->getType()))
11637       opcode = Instruction::PtrToInt;
11638   }
11639   
11640   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11641   // emit a GEP to index into its first field.
11642   if (!NewGEPIndices.empty())
11643     CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11644                                            NewGEPIndices.end());
11645   
11646   NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11647                                    SIOp0->getName()+".c");
11648   return new StoreInst(NewCast, CastOp);
11649 }
11650
11651 /// equivalentAddressValues - Test if A and B will obviously have the same
11652 /// value. This includes recognizing that %t0 and %t1 will have the same
11653 /// value in code like this:
11654 ///   %t0 = getelementptr \@a, 0, 3
11655 ///   store i32 0, i32* %t0
11656 ///   %t1 = getelementptr \@a, 0, 3
11657 ///   %t2 = load i32* %t1
11658 ///
11659 static bool equivalentAddressValues(Value *A, Value *B) {
11660   // Test if the values are trivially equivalent.
11661   if (A == B) return true;
11662   
11663   // Test if the values come form identical arithmetic instructions.
11664   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11665   // its only used to compare two uses within the same basic block, which
11666   // means that they'll always either have the same value or one of them
11667   // will have an undefined value.
11668   if (isa<BinaryOperator>(A) ||
11669       isa<CastInst>(A) ||
11670       isa<PHINode>(A) ||
11671       isa<GetElementPtrInst>(A))
11672     if (Instruction *BI = dyn_cast<Instruction>(B))
11673       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
11674         return true;
11675   
11676   // Otherwise they may not be equivalent.
11677   return false;
11678 }
11679
11680 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11681 // return the llvm.dbg.declare.
11682 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11683   if (!V->hasNUses(2))
11684     return 0;
11685   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11686        UI != E; ++UI) {
11687     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11688       return DI;
11689     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11690       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11691         return DI;
11692       }
11693   }
11694   return 0;
11695 }
11696
11697 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11698   Value *Val = SI.getOperand(0);
11699   Value *Ptr = SI.getOperand(1);
11700
11701   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11702     EraseInstFromFunction(SI);
11703     ++NumCombined;
11704     return 0;
11705   }
11706   
11707   // If the RHS is an alloca with a single use, zapify the store, making the
11708   // alloca dead.
11709   // If the RHS is an alloca with a two uses, the other one being a 
11710   // llvm.dbg.declare, zapify the store and the declare, making the
11711   // alloca dead.  We must do this to prevent declare's from affecting
11712   // codegen.
11713   if (!SI.isVolatile()) {
11714     if (Ptr->hasOneUse()) {
11715       if (isa<AllocaInst>(Ptr)) {
11716         EraseInstFromFunction(SI);
11717         ++NumCombined;
11718         return 0;
11719       }
11720       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11721         if (isa<AllocaInst>(GEP->getOperand(0))) {
11722           if (GEP->getOperand(0)->hasOneUse()) {
11723             EraseInstFromFunction(SI);
11724             ++NumCombined;
11725             return 0;
11726           }
11727           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11728             EraseInstFromFunction(*DI);
11729             EraseInstFromFunction(SI);
11730             ++NumCombined;
11731             return 0;
11732           }
11733         }
11734       }
11735     }
11736     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11737       EraseInstFromFunction(*DI);
11738       EraseInstFromFunction(SI);
11739       ++NumCombined;
11740       return 0;
11741     }
11742   }
11743
11744   // Attempt to improve the alignment.
11745   if (TD) {
11746     unsigned KnownAlign =
11747       GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11748     if (KnownAlign >
11749         (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11750                                   SI.getAlignment()))
11751       SI.setAlignment(KnownAlign);
11752   }
11753
11754   // Do really simple DSE, to catch cases where there are several consecutive
11755   // stores to the same location, separated by a few arithmetic operations. This
11756   // situation often occurs with bitfield accesses.
11757   BasicBlock::iterator BBI = &SI;
11758   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11759        --ScanInsts) {
11760     --BBI;
11761     // Don't count debug info directives, lest they affect codegen,
11762     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11763     // It is necessary for correctness to skip those that feed into a
11764     // llvm.dbg.declare, as these are not present when debugging is off.
11765     if (isa<DbgInfoIntrinsic>(BBI) ||
11766         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11767       ScanInsts++;
11768       continue;
11769     }    
11770     
11771     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11772       // Prev store isn't volatile, and stores to the same location?
11773       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11774                                                           SI.getOperand(1))) {
11775         ++NumDeadStore;
11776         ++BBI;
11777         EraseInstFromFunction(*PrevSI);
11778         continue;
11779       }
11780       break;
11781     }
11782     
11783     // If this is a load, we have to stop.  However, if the loaded value is from
11784     // the pointer we're loading and is producing the pointer we're storing,
11785     // then *this* store is dead (X = load P; store X -> P).
11786     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11787       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11788           !SI.isVolatile()) {
11789         EraseInstFromFunction(SI);
11790         ++NumCombined;
11791         return 0;
11792       }
11793       // Otherwise, this is a load from some other location.  Stores before it
11794       // may not be dead.
11795       break;
11796     }
11797     
11798     // Don't skip over loads or things that can modify memory.
11799     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11800       break;
11801   }
11802   
11803   
11804   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11805
11806   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11807   if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
11808     if (!isa<UndefValue>(Val)) {
11809       SI.setOperand(0, UndefValue::get(Val->getType()));
11810       if (Instruction *U = dyn_cast<Instruction>(Val))
11811         Worklist.Add(U);  // Dropped a use.
11812       ++NumCombined;
11813     }
11814     return 0;  // Do not modify these!
11815   }
11816
11817   // store undef, Ptr -> noop
11818   if (isa<UndefValue>(Val)) {
11819     EraseInstFromFunction(SI);
11820     ++NumCombined;
11821     return 0;
11822   }
11823
11824   // If the pointer destination is a cast, see if we can fold the cast into the
11825   // source instead.
11826   if (isa<CastInst>(Ptr))
11827     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11828       return Res;
11829   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11830     if (CE->isCast())
11831       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11832         return Res;
11833
11834   
11835   // If this store is the last instruction in the basic block (possibly
11836   // excepting debug info instructions and the pointer bitcasts that feed
11837   // into them), and if the block ends with an unconditional branch, try
11838   // to move it to the successor block.
11839   BBI = &SI; 
11840   do {
11841     ++BBI;
11842   } while (isa<DbgInfoIntrinsic>(BBI) ||
11843            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11844   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11845     if (BI->isUnconditional())
11846       if (SimplifyStoreAtEndOfBlock(SI))
11847         return 0;  // xform done!
11848   
11849   return 0;
11850 }
11851
11852 /// SimplifyStoreAtEndOfBlock - Turn things like:
11853 ///   if () { *P = v1; } else { *P = v2 }
11854 /// into a phi node with a store in the successor.
11855 ///
11856 /// Simplify things like:
11857 ///   *P = v1; if () { *P = v2; }
11858 /// into a phi node with a store in the successor.
11859 ///
11860 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11861   BasicBlock *StoreBB = SI.getParent();
11862   
11863   // Check to see if the successor block has exactly two incoming edges.  If
11864   // so, see if the other predecessor contains a store to the same location.
11865   // if so, insert a PHI node (if needed) and move the stores down.
11866   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11867   
11868   // Determine whether Dest has exactly two predecessors and, if so, compute
11869   // the other predecessor.
11870   pred_iterator PI = pred_begin(DestBB);
11871   BasicBlock *OtherBB = 0;
11872   if (*PI != StoreBB)
11873     OtherBB = *PI;
11874   ++PI;
11875   if (PI == pred_end(DestBB))
11876     return false;
11877   
11878   if (*PI != StoreBB) {
11879     if (OtherBB)
11880       return false;
11881     OtherBB = *PI;
11882   }
11883   if (++PI != pred_end(DestBB))
11884     return false;
11885
11886   // Bail out if all the relevant blocks aren't distinct (this can happen,
11887   // for example, if SI is in an infinite loop)
11888   if (StoreBB == DestBB || OtherBB == DestBB)
11889     return false;
11890
11891   // Verify that the other block ends in a branch and is not otherwise empty.
11892   BasicBlock::iterator BBI = OtherBB->getTerminator();
11893   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11894   if (!OtherBr || BBI == OtherBB->begin())
11895     return false;
11896   
11897   // If the other block ends in an unconditional branch, check for the 'if then
11898   // else' case.  there is an instruction before the branch.
11899   StoreInst *OtherStore = 0;
11900   if (OtherBr->isUnconditional()) {
11901     --BBI;
11902     // Skip over debugging info.
11903     while (isa<DbgInfoIntrinsic>(BBI) ||
11904            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11905       if (BBI==OtherBB->begin())
11906         return false;
11907       --BBI;
11908     }
11909     // If this isn't a store, or isn't a store to the same location, bail out.
11910     OtherStore = dyn_cast<StoreInst>(BBI);
11911     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11912       return false;
11913   } else {
11914     // Otherwise, the other block ended with a conditional branch. If one of the
11915     // destinations is StoreBB, then we have the if/then case.
11916     if (OtherBr->getSuccessor(0) != StoreBB && 
11917         OtherBr->getSuccessor(1) != StoreBB)
11918       return false;
11919     
11920     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11921     // if/then triangle.  See if there is a store to the same ptr as SI that
11922     // lives in OtherBB.
11923     for (;; --BBI) {
11924       // Check to see if we find the matching store.
11925       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11926         if (OtherStore->getOperand(1) != SI.getOperand(1))
11927           return false;
11928         break;
11929       }
11930       // If we find something that may be using or overwriting the stored
11931       // value, or if we run out of instructions, we can't do the xform.
11932       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11933           BBI == OtherBB->begin())
11934         return false;
11935     }
11936     
11937     // In order to eliminate the store in OtherBr, we have to
11938     // make sure nothing reads or overwrites the stored value in
11939     // StoreBB.
11940     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11941       // FIXME: This should really be AA driven.
11942       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11943         return false;
11944     }
11945   }
11946   
11947   // Insert a PHI node now if we need it.
11948   Value *MergedVal = OtherStore->getOperand(0);
11949   if (MergedVal != SI.getOperand(0)) {
11950     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11951     PN->reserveOperandSpace(2);
11952     PN->addIncoming(SI.getOperand(0), SI.getParent());
11953     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11954     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11955   }
11956   
11957   // Advance to a place where it is safe to insert the new store and
11958   // insert it.
11959   BBI = DestBB->getFirstNonPHI();
11960   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11961                                     OtherStore->isVolatile()), *BBI);
11962   
11963   // Nuke the old stores.
11964   EraseInstFromFunction(SI);
11965   EraseInstFromFunction(*OtherStore);
11966   ++NumCombined;
11967   return true;
11968 }
11969
11970
11971 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11972   // Change br (not X), label True, label False to: br X, label False, True
11973   Value *X = 0;
11974   BasicBlock *TrueDest;
11975   BasicBlock *FalseDest;
11976   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11977       !isa<Constant>(X)) {
11978     // Swap Destinations and condition...
11979     BI.setCondition(X);
11980     BI.setSuccessor(0, FalseDest);
11981     BI.setSuccessor(1, TrueDest);
11982     return &BI;
11983   }
11984
11985   // Cannonicalize fcmp_one -> fcmp_oeq
11986   FCmpInst::Predicate FPred; Value *Y;
11987   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11988                              TrueDest, FalseDest)) &&
11989       BI.getCondition()->hasOneUse())
11990     if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11991         FPred == FCmpInst::FCMP_OGE) {
11992       FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11993       Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11994       
11995       // Swap Destinations and condition.
11996       BI.setSuccessor(0, FalseDest);
11997       BI.setSuccessor(1, TrueDest);
11998       Worklist.Add(Cond);
11999       return &BI;
12000     }
12001
12002   // Cannonicalize icmp_ne -> icmp_eq
12003   ICmpInst::Predicate IPred;
12004   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12005                       TrueDest, FalseDest)) &&
12006       BI.getCondition()->hasOneUse())
12007     if (IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12008         IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12009         IPred == ICmpInst::ICMP_SGE) {
12010       ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12011       Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12012       // Swap Destinations and condition.
12013       BI.setSuccessor(0, FalseDest);
12014       BI.setSuccessor(1, TrueDest);
12015       Worklist.Add(Cond);
12016       return &BI;
12017     }
12018
12019   return 0;
12020 }
12021
12022 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12023   Value *Cond = SI.getCondition();
12024   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12025     if (I->getOpcode() == Instruction::Add)
12026       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12027         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12028         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12029           SI.setOperand(i,
12030                    ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
12031                                                 AddRHS));
12032         SI.setOperand(0, I->getOperand(0));
12033         Worklist.Add(I);
12034         return &SI;
12035       }
12036   }
12037   return 0;
12038 }
12039
12040 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12041   Value *Agg = EV.getAggregateOperand();
12042
12043   if (!EV.hasIndices())
12044     return ReplaceInstUsesWith(EV, Agg);
12045
12046   if (Constant *C = dyn_cast<Constant>(Agg)) {
12047     if (isa<UndefValue>(C))
12048       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12049       
12050     if (isa<ConstantAggregateZero>(C))
12051       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12052
12053     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12054       // Extract the element indexed by the first index out of the constant
12055       Value *V = C->getOperand(*EV.idx_begin());
12056       if (EV.getNumIndices() > 1)
12057         // Extract the remaining indices out of the constant indexed by the
12058         // first index
12059         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12060       else
12061         return ReplaceInstUsesWith(EV, V);
12062     }
12063     return 0; // Can't handle other constants
12064   } 
12065   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12066     // We're extracting from an insertvalue instruction, compare the indices
12067     const unsigned *exti, *exte, *insi, *inse;
12068     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12069          exte = EV.idx_end(), inse = IV->idx_end();
12070          exti != exte && insi != inse;
12071          ++exti, ++insi) {
12072       if (*insi != *exti)
12073         // The insert and extract both reference distinctly different elements.
12074         // This means the extract is not influenced by the insert, and we can
12075         // replace the aggregate operand of the extract with the aggregate
12076         // operand of the insert. i.e., replace
12077         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12078         // %E = extractvalue { i32, { i32 } } %I, 0
12079         // with
12080         // %E = extractvalue { i32, { i32 } } %A, 0
12081         return ExtractValueInst::Create(IV->getAggregateOperand(),
12082                                         EV.idx_begin(), EV.idx_end());
12083     }
12084     if (exti == exte && insi == inse)
12085       // Both iterators are at the end: Index lists are identical. Replace
12086       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12087       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12088       // with "i32 42"
12089       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12090     if (exti == exte) {
12091       // The extract list is a prefix of the insert list. i.e. replace
12092       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12093       // %E = extractvalue { i32, { i32 } } %I, 1
12094       // with
12095       // %X = extractvalue { i32, { i32 } } %A, 1
12096       // %E = insertvalue { i32 } %X, i32 42, 0
12097       // by switching the order of the insert and extract (though the
12098       // insertvalue should be left in, since it may have other uses).
12099       Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12100                                                  EV.idx_begin(), EV.idx_end());
12101       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12102                                      insi, inse);
12103     }
12104     if (insi == inse)
12105       // The insert list is a prefix of the extract list
12106       // We can simply remove the common indices from the extract and make it
12107       // operate on the inserted value instead of the insertvalue result.
12108       // i.e., replace
12109       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12110       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12111       // with
12112       // %E extractvalue { i32 } { i32 42 }, 0
12113       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12114                                       exti, exte);
12115   }
12116   // Can't simplify extracts from other values. Note that nested extracts are
12117   // already simplified implicitely by the above (extract ( extract (insert) )
12118   // will be translated into extract ( insert ( extract ) ) first and then just
12119   // the value inserted, if appropriate).
12120   return 0;
12121 }
12122
12123 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12124 /// is to leave as a vector operation.
12125 static bool CheapToScalarize(Value *V, bool isConstant) {
12126   if (isa<ConstantAggregateZero>(V)) 
12127     return true;
12128   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12129     if (isConstant) return true;
12130     // If all elts are the same, we can extract.
12131     Constant *Op0 = C->getOperand(0);
12132     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12133       if (C->getOperand(i) != Op0)
12134         return false;
12135     return true;
12136   }
12137   Instruction *I = dyn_cast<Instruction>(V);
12138   if (!I) return false;
12139   
12140   // Insert element gets simplified to the inserted element or is deleted if
12141   // this is constant idx extract element and its a constant idx insertelt.
12142   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12143       isa<ConstantInt>(I->getOperand(2)))
12144     return true;
12145   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12146     return true;
12147   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12148     if (BO->hasOneUse() &&
12149         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12150          CheapToScalarize(BO->getOperand(1), isConstant)))
12151       return true;
12152   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12153     if (CI->hasOneUse() &&
12154         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12155          CheapToScalarize(CI->getOperand(1), isConstant)))
12156       return true;
12157   
12158   return false;
12159 }
12160
12161 /// Read and decode a shufflevector mask.
12162 ///
12163 /// It turns undef elements into values that are larger than the number of
12164 /// elements in the input.
12165 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12166   unsigned NElts = SVI->getType()->getNumElements();
12167   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12168     return std::vector<unsigned>(NElts, 0);
12169   if (isa<UndefValue>(SVI->getOperand(2)))
12170     return std::vector<unsigned>(NElts, 2*NElts);
12171
12172   std::vector<unsigned> Result;
12173   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12174   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12175     if (isa<UndefValue>(*i))
12176       Result.push_back(NElts*2);  // undef -> 8
12177     else
12178       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12179   return Result;
12180 }
12181
12182 /// FindScalarElement - Given a vector and an element number, see if the scalar
12183 /// value is already around as a register, for example if it were inserted then
12184 /// extracted from the vector.
12185 static Value *FindScalarElement(Value *V, unsigned EltNo,
12186                                 LLVMContext *Context) {
12187   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12188   const VectorType *PTy = cast<VectorType>(V->getType());
12189   unsigned Width = PTy->getNumElements();
12190   if (EltNo >= Width)  // Out of range access.
12191     return UndefValue::get(PTy->getElementType());
12192   
12193   if (isa<UndefValue>(V))
12194     return UndefValue::get(PTy->getElementType());
12195   else if (isa<ConstantAggregateZero>(V))
12196     return Constant::getNullValue(PTy->getElementType());
12197   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12198     return CP->getOperand(EltNo);
12199   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12200     // If this is an insert to a variable element, we don't know what it is.
12201     if (!isa<ConstantInt>(III->getOperand(2))) 
12202       return 0;
12203     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12204     
12205     // If this is an insert to the element we are looking for, return the
12206     // inserted value.
12207     if (EltNo == IIElt) 
12208       return III->getOperand(1);
12209     
12210     // Otherwise, the insertelement doesn't modify the value, recurse on its
12211     // vector input.
12212     return FindScalarElement(III->getOperand(0), EltNo, Context);
12213   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12214     unsigned LHSWidth =
12215       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12216     unsigned InEl = getShuffleMask(SVI)[EltNo];
12217     if (InEl < LHSWidth)
12218       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12219     else if (InEl < LHSWidth*2)
12220       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12221     else
12222       return UndefValue::get(PTy->getElementType());
12223   }
12224   
12225   // Otherwise, we don't know.
12226   return 0;
12227 }
12228
12229 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12230   // If vector val is undef, replace extract with scalar undef.
12231   if (isa<UndefValue>(EI.getOperand(0)))
12232     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12233
12234   // If vector val is constant 0, replace extract with scalar 0.
12235   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12236     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12237   
12238   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12239     // If vector val is constant with all elements the same, replace EI with
12240     // that element. When the elements are not identical, we cannot replace yet
12241     // (we do that below, but only when the index is constant).
12242     Constant *op0 = C->getOperand(0);
12243     for (unsigned i = 1; i != C->getNumOperands(); ++i)
12244       if (C->getOperand(i) != op0) {
12245         op0 = 0; 
12246         break;
12247       }
12248     if (op0)
12249       return ReplaceInstUsesWith(EI, op0);
12250   }
12251   
12252   // If extracting a specified index from the vector, see if we can recursively
12253   // find a previously computed scalar that was inserted into the vector.
12254   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12255     unsigned IndexVal = IdxC->getZExtValue();
12256     unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
12257       
12258     // If this is extracting an invalid index, turn this into undef, to avoid
12259     // crashing the code below.
12260     if (IndexVal >= VectorWidth)
12261       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12262     
12263     // This instruction only demands the single element from the input vector.
12264     // If the input vector has a single use, simplify it based on this use
12265     // property.
12266     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12267       APInt UndefElts(VectorWidth, 0);
12268       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12269       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12270                                                 DemandedMask, UndefElts)) {
12271         EI.setOperand(0, V);
12272         return &EI;
12273       }
12274     }
12275     
12276     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12277       return ReplaceInstUsesWith(EI, Elt);
12278     
12279     // If the this extractelement is directly using a bitcast from a vector of
12280     // the same number of elements, see if we can find the source element from
12281     // it.  In this case, we will end up needing to bitcast the scalars.
12282     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12283       if (const VectorType *VT = 
12284               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12285         if (VT->getNumElements() == VectorWidth)
12286           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12287                                              IndexVal, Context))
12288             return new BitCastInst(Elt, EI.getType());
12289     }
12290   }
12291   
12292   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12293     // Push extractelement into predecessor operation if legal and
12294     // profitable to do so
12295     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12296       if (I->hasOneUse() &&
12297           CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12298         Value *newEI0 =
12299           Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12300                                         EI.getName()+".lhs");
12301         Value *newEI1 =
12302           Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12303                                         EI.getName()+".rhs");
12304         return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12305       }
12306     } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12307       // Extracting the inserted element?
12308       if (IE->getOperand(2) == EI.getOperand(1))
12309         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12310       // If the inserted and extracted elements are constants, they must not
12311       // be the same value, extract from the pre-inserted value instead.
12312       if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
12313         Worklist.AddValue(EI.getOperand(0));
12314         EI.setOperand(0, IE->getOperand(0));
12315         return &EI;
12316       }
12317     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12318       // If this is extracting an element from a shufflevector, figure out where
12319       // it came from and extract from the appropriate input element instead.
12320       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12321         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12322         Value *Src;
12323         unsigned LHSWidth =
12324           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12325
12326         if (SrcIdx < LHSWidth)
12327           Src = SVI->getOperand(0);
12328         else if (SrcIdx < LHSWidth*2) {
12329           SrcIdx -= LHSWidth;
12330           Src = SVI->getOperand(1);
12331         } else {
12332           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12333         }
12334         return ExtractElementInst::Create(Src,
12335                          ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12336                                           false));
12337       }
12338     }
12339     // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12340   }
12341   return 0;
12342 }
12343
12344 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12345 /// elements from either LHS or RHS, return the shuffle mask and true. 
12346 /// Otherwise, return false.
12347 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12348                                          std::vector<Constant*> &Mask,
12349                                          LLVMContext *Context) {
12350   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12351          "Invalid CollectSingleShuffleElements");
12352   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12353
12354   if (isa<UndefValue>(V)) {
12355     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12356     return true;
12357   } else if (V == LHS) {
12358     for (unsigned i = 0; i != NumElts; ++i)
12359       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12360     return true;
12361   } else if (V == RHS) {
12362     for (unsigned i = 0; i != NumElts; ++i)
12363       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
12364     return true;
12365   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12366     // If this is an insert of an extract from some other vector, include it.
12367     Value *VecOp    = IEI->getOperand(0);
12368     Value *ScalarOp = IEI->getOperand(1);
12369     Value *IdxOp    = IEI->getOperand(2);
12370     
12371     if (!isa<ConstantInt>(IdxOp))
12372       return false;
12373     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12374     
12375     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12376       // Okay, we can handle this if the vector we are insertinting into is
12377       // transitively ok.
12378       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12379         // If so, update the mask to reflect the inserted undef.
12380         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
12381         return true;
12382       }      
12383     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12384       if (isa<ConstantInt>(EI->getOperand(1)) &&
12385           EI->getOperand(0)->getType() == V->getType()) {
12386         unsigned ExtractedIdx =
12387           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12388         
12389         // This must be extracting from either LHS or RHS.
12390         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12391           // Okay, we can handle this if the vector we are insertinting into is
12392           // transitively ok.
12393           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12394             // If so, update the mask to reflect the inserted value.
12395             if (EI->getOperand(0) == LHS) {
12396               Mask[InsertedIdx % NumElts] = 
12397                  ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12398             } else {
12399               assert(EI->getOperand(0) == RHS);
12400               Mask[InsertedIdx % NumElts] = 
12401                 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
12402               
12403             }
12404             return true;
12405           }
12406         }
12407       }
12408     }
12409   }
12410   // TODO: Handle shufflevector here!
12411   
12412   return false;
12413 }
12414
12415 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12416 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12417 /// that computes V and the LHS value of the shuffle.
12418 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12419                                      Value *&RHS, LLVMContext *Context) {
12420   assert(isa<VectorType>(V->getType()) && 
12421          (RHS == 0 || V->getType() == RHS->getType()) &&
12422          "Invalid shuffle!");
12423   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12424
12425   if (isa<UndefValue>(V)) {
12426     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12427     return V;
12428   } else if (isa<ConstantAggregateZero>(V)) {
12429     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
12430     return V;
12431   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12432     // If this is an insert of an extract from some other vector, include it.
12433     Value *VecOp    = IEI->getOperand(0);
12434     Value *ScalarOp = IEI->getOperand(1);
12435     Value *IdxOp    = IEI->getOperand(2);
12436     
12437     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12438       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12439           EI->getOperand(0)->getType() == V->getType()) {
12440         unsigned ExtractedIdx =
12441           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12442         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12443         
12444         // Either the extracted from or inserted into vector must be RHSVec,
12445         // otherwise we'd end up with a shuffle of three inputs.
12446         if (EI->getOperand(0) == RHS || RHS == 0) {
12447           RHS = EI->getOperand(0);
12448           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12449           Mask[InsertedIdx % NumElts] = 
12450             ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
12451           return V;
12452         }
12453         
12454         if (VecOp == RHS) {
12455           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12456                                             RHS, Context);
12457           // Everything but the extracted element is replaced with the RHS.
12458           for (unsigned i = 0; i != NumElts; ++i) {
12459             if (i != InsertedIdx)
12460               Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
12461           }
12462           return V;
12463         }
12464         
12465         // If this insertelement is a chain that comes from exactly these two
12466         // vectors, return the vector and the effective shuffle.
12467         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12468                                          Context))
12469           return EI->getOperand(0);
12470         
12471       }
12472     }
12473   }
12474   // TODO: Handle shufflevector here!
12475   
12476   // Otherwise, can't do anything fancy.  Return an identity vector.
12477   for (unsigned i = 0; i != NumElts; ++i)
12478     Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12479   return V;
12480 }
12481
12482 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12483   Value *VecOp    = IE.getOperand(0);
12484   Value *ScalarOp = IE.getOperand(1);
12485   Value *IdxOp    = IE.getOperand(2);
12486   
12487   // Inserting an undef or into an undefined place, remove this.
12488   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12489     ReplaceInstUsesWith(IE, VecOp);
12490   
12491   // If the inserted element was extracted from some other vector, and if the 
12492   // indexes are constant, try to turn this into a shufflevector operation.
12493   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12494     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12495         EI->getOperand(0)->getType() == IE.getType()) {
12496       unsigned NumVectorElts = IE.getType()->getNumElements();
12497       unsigned ExtractedIdx =
12498         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12499       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12500       
12501       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12502         return ReplaceInstUsesWith(IE, VecOp);
12503       
12504       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12505         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12506       
12507       // If we are extracting a value from a vector, then inserting it right
12508       // back into the same place, just use the input vector.
12509       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12510         return ReplaceInstUsesWith(IE, VecOp);      
12511       
12512       // If this insertelement isn't used by some other insertelement, turn it
12513       // (and any insertelements it points to), into one big shuffle.
12514       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12515         std::vector<Constant*> Mask;
12516         Value *RHS = 0;
12517         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12518         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12519         // We now have a shuffle of LHS, RHS, Mask.
12520         return new ShuffleVectorInst(LHS, RHS,
12521                                      ConstantVector::get(Mask));
12522       }
12523     }
12524   }
12525
12526   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12527   APInt UndefElts(VWidth, 0);
12528   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12529   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12530     return &IE;
12531
12532   return 0;
12533 }
12534
12535
12536 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12537   Value *LHS = SVI.getOperand(0);
12538   Value *RHS = SVI.getOperand(1);
12539   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12540
12541   bool MadeChange = false;
12542
12543   // Undefined shuffle mask -> undefined value.
12544   if (isa<UndefValue>(SVI.getOperand(2)))
12545     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12546
12547   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12548
12549   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12550     return 0;
12551
12552   APInt UndefElts(VWidth, 0);
12553   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12554   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12555     LHS = SVI.getOperand(0);
12556     RHS = SVI.getOperand(1);
12557     MadeChange = true;
12558   }
12559   
12560   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12561   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12562   if (LHS == RHS || isa<UndefValue>(LHS)) {
12563     if (isa<UndefValue>(LHS) && LHS == RHS) {
12564       // shuffle(undef,undef,mask) -> undef.
12565       return ReplaceInstUsesWith(SVI, LHS);
12566     }
12567     
12568     // Remap any references to RHS to use LHS.
12569     std::vector<Constant*> Elts;
12570     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12571       if (Mask[i] >= 2*e)
12572         Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12573       else {
12574         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12575             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12576           Mask[i] = 2*e;     // Turn into undef.
12577           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12578         } else {
12579           Mask[i] = Mask[i] % e;  // Force to LHS.
12580           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
12581         }
12582       }
12583     }
12584     SVI.setOperand(0, SVI.getOperand(1));
12585     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12586     SVI.setOperand(2, ConstantVector::get(Elts));
12587     LHS = SVI.getOperand(0);
12588     RHS = SVI.getOperand(1);
12589     MadeChange = true;
12590   }
12591   
12592   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12593   bool isLHSID = true, isRHSID = true;
12594     
12595   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12596     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12597     // Is this an identity shuffle of the LHS value?
12598     isLHSID &= (Mask[i] == i);
12599       
12600     // Is this an identity shuffle of the RHS value?
12601     isRHSID &= (Mask[i]-e == i);
12602   }
12603
12604   // Eliminate identity shuffles.
12605   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12606   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12607   
12608   // If the LHS is a shufflevector itself, see if we can combine it with this
12609   // one without producing an unusual shuffle.  Here we are really conservative:
12610   // we are absolutely afraid of producing a shuffle mask not in the input
12611   // program, because the code gen may not be smart enough to turn a merged
12612   // shuffle into two specific shuffles: it may produce worse code.  As such,
12613   // we only merge two shuffles if the result is one of the two input shuffle
12614   // masks.  In this case, merging the shuffles just removes one instruction,
12615   // which we know is safe.  This is good for things like turning:
12616   // (splat(splat)) -> splat.
12617   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12618     if (isa<UndefValue>(RHS)) {
12619       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12620
12621       std::vector<unsigned> NewMask;
12622       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12623         if (Mask[i] >= 2*e)
12624           NewMask.push_back(2*e);
12625         else
12626           NewMask.push_back(LHSMask[Mask[i]]);
12627       
12628       // If the result mask is equal to the src shuffle or this shuffle mask, do
12629       // the replacement.
12630       if (NewMask == LHSMask || NewMask == Mask) {
12631         unsigned LHSInNElts =
12632           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12633         std::vector<Constant*> Elts;
12634         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12635           if (NewMask[i] >= LHSInNElts*2) {
12636             Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12637           } else {
12638             Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
12639           }
12640         }
12641         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12642                                      LHSSVI->getOperand(1),
12643                                      ConstantVector::get(Elts));
12644       }
12645     }
12646   }
12647
12648   return MadeChange ? &SVI : 0;
12649 }
12650
12651
12652
12653
12654 /// TryToSinkInstruction - Try to move the specified instruction from its
12655 /// current block into the beginning of DestBlock, which can only happen if it's
12656 /// safe to move the instruction past all of the instructions between it and the
12657 /// end of its block.
12658 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12659   assert(I->hasOneUse() && "Invariants didn't hold!");
12660
12661   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12662   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12663     return false;
12664
12665   // Do not sink alloca instructions out of the entry block.
12666   if (isa<AllocaInst>(I) && I->getParent() ==
12667         &DestBlock->getParent()->getEntryBlock())
12668     return false;
12669
12670   // We can only sink load instructions if there is nothing between the load and
12671   // the end of block that could change the value.
12672   if (I->mayReadFromMemory()) {
12673     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12674          Scan != E; ++Scan)
12675       if (Scan->mayWriteToMemory())
12676         return false;
12677   }
12678
12679   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12680
12681   CopyPrecedingStopPoint(I, InsertPos);
12682   I->moveBefore(InsertPos);
12683   ++NumSunkInst;
12684   return true;
12685 }
12686
12687
12688 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12689 /// all reachable code to the worklist.
12690 ///
12691 /// This has a couple of tricks to make the code faster and more powerful.  In
12692 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12693 /// them to the worklist (this significantly speeds up instcombine on code where
12694 /// many instructions are dead or constant).  Additionally, if we find a branch
12695 /// whose condition is a known constant, we only visit the reachable successors.
12696 ///
12697 static bool AddReachableCodeToWorklist(BasicBlock *BB, 
12698                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12699                                        InstCombiner &IC,
12700                                        const TargetData *TD) {
12701   bool MadeIRChange = false;
12702   SmallVector<BasicBlock*, 256> Worklist;
12703   Worklist.push_back(BB);
12704   
12705   std::vector<Instruction*> InstrsForInstCombineWorklist;
12706   InstrsForInstCombineWorklist.reserve(128);
12707
12708   SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
12709   
12710   while (!Worklist.empty()) {
12711     BB = Worklist.back();
12712     Worklist.pop_back();
12713     
12714     // We have now visited this block!  If we've already been here, ignore it.
12715     if (!Visited.insert(BB)) continue;
12716
12717     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12718       Instruction *Inst = BBI++;
12719       
12720       // DCE instruction if trivially dead.
12721       if (isInstructionTriviallyDead(Inst)) {
12722         ++NumDeadInst;
12723         DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
12724         Inst->eraseFromParent();
12725         continue;
12726       }
12727       
12728       // ConstantProp instruction if trivially constant.
12729       if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
12730         if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12731           DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12732                        << *Inst << '\n');
12733           Inst->replaceAllUsesWith(C);
12734           ++NumConstProp;
12735           Inst->eraseFromParent();
12736           continue;
12737         }
12738       
12739       
12740       
12741       if (TD) {
12742         // See if we can constant fold its operands.
12743         for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
12744              i != e; ++i) {
12745           ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
12746           if (CE == 0) continue;
12747           
12748           // If we already folded this constant, don't try again.
12749           if (!FoldedConstants.insert(CE))
12750             continue;
12751           
12752           Constant *NewC =
12753             ConstantFoldConstantExpression(CE, BB->getContext(), TD);
12754           if (NewC && NewC != CE) {
12755             *i = NewC;
12756             MadeIRChange = true;
12757           }
12758         }
12759       }
12760       
12761
12762       InstrsForInstCombineWorklist.push_back(Inst);
12763     }
12764
12765     // Recursively visit successors.  If this is a branch or switch on a
12766     // constant, only visit the reachable successor.
12767     TerminatorInst *TI = BB->getTerminator();
12768     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12769       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12770         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12771         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12772         Worklist.push_back(ReachableBB);
12773         continue;
12774       }
12775     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12776       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12777         // See if this is an explicit destination.
12778         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12779           if (SI->getCaseValue(i) == Cond) {
12780             BasicBlock *ReachableBB = SI->getSuccessor(i);
12781             Worklist.push_back(ReachableBB);
12782             continue;
12783           }
12784         
12785         // Otherwise it is the default destination.
12786         Worklist.push_back(SI->getSuccessor(0));
12787         continue;
12788       }
12789     }
12790     
12791     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12792       Worklist.push_back(TI->getSuccessor(i));
12793   }
12794   
12795   // Once we've found all of the instructions to add to instcombine's worklist,
12796   // add them in reverse order.  This way instcombine will visit from the top
12797   // of the function down.  This jives well with the way that it adds all uses
12798   // of instructions to the worklist after doing a transformation, thus avoiding
12799   // some N^2 behavior in pathological cases.
12800   IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
12801                               InstrsForInstCombineWorklist.size());
12802   
12803   return MadeIRChange;
12804 }
12805
12806 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12807   MadeIRChange = false;
12808   
12809   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12810         << F.getNameStr() << "\n");
12811
12812   {
12813     // Do a depth-first traversal of the function, populate the worklist with
12814     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12815     // track of which blocks we visit.
12816     SmallPtrSet<BasicBlock*, 64> Visited;
12817     MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12818
12819     // Do a quick scan over the function.  If we find any blocks that are
12820     // unreachable, remove any instructions inside of them.  This prevents
12821     // the instcombine code from having to deal with some bad special cases.
12822     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12823       if (!Visited.count(BB)) {
12824         Instruction *Term = BB->getTerminator();
12825         while (Term != BB->begin()) {   // Remove instrs bottom-up
12826           BasicBlock::iterator I = Term; --I;
12827
12828           DEBUG(errs() << "IC: DCE: " << *I << '\n');
12829           // A debug intrinsic shouldn't force another iteration if we weren't
12830           // going to do one without it.
12831           if (!isa<DbgInfoIntrinsic>(I)) {
12832             ++NumDeadInst;
12833             MadeIRChange = true;
12834           }
12835
12836           // If I is not void type then replaceAllUsesWith undef.
12837           // This allows ValueHandlers and custom metadata to adjust itself.
12838           if (!I->getType()->isVoidTy())
12839             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12840           I->eraseFromParent();
12841         }
12842       }
12843   }
12844
12845   while (!Worklist.isEmpty()) {
12846     Instruction *I = Worklist.RemoveOne();
12847     if (I == 0) continue;  // skip null values.
12848
12849     // Check to see if we can DCE the instruction.
12850     if (isInstructionTriviallyDead(I)) {
12851       DEBUG(errs() << "IC: DCE: " << *I << '\n');
12852       EraseInstFromFunction(*I);
12853       ++NumDeadInst;
12854       MadeIRChange = true;
12855       continue;
12856     }
12857
12858     // Instruction isn't dead, see if we can constant propagate it.
12859     if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
12860       if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12861         DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
12862
12863         // Add operands to the worklist.
12864         ReplaceInstUsesWith(*I, C);
12865         ++NumConstProp;
12866         EraseInstFromFunction(*I);
12867         MadeIRChange = true;
12868         continue;
12869       }
12870
12871     // See if we can trivially sink this instruction to a successor basic block.
12872     if (I->hasOneUse()) {
12873       BasicBlock *BB = I->getParent();
12874       Instruction *UserInst = cast<Instruction>(I->use_back());
12875       BasicBlock *UserParent;
12876       
12877       // Get the block the use occurs in.
12878       if (PHINode *PN = dyn_cast<PHINode>(UserInst))
12879         UserParent = PN->getIncomingBlock(I->use_begin().getUse());
12880       else
12881         UserParent = UserInst->getParent();
12882       
12883       if (UserParent != BB) {
12884         bool UserIsSuccessor = false;
12885         // See if the user is one of our successors.
12886         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12887           if (*SI == UserParent) {
12888             UserIsSuccessor = true;
12889             break;
12890           }
12891
12892         // If the user is one of our immediate successors, and if that successor
12893         // only has us as a predecessors (we'd have to split the critical edge
12894         // otherwise), we can keep going.
12895         if (UserIsSuccessor && UserParent->getSinglePredecessor())
12896           // Okay, the CFG is simple enough, try to sink this instruction.
12897           MadeIRChange |= TryToSinkInstruction(I, UserParent);
12898       }
12899     }
12900
12901     // Now that we have an instruction, try combining it to simplify it.
12902     Builder->SetInsertPoint(I->getParent(), I);
12903     
12904 #ifndef NDEBUG
12905     std::string OrigI;
12906 #endif
12907     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
12908     DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
12909
12910     if (Instruction *Result = visit(*I)) {
12911       ++NumCombined;
12912       // Should we replace the old instruction with a new one?
12913       if (Result != I) {
12914         DEBUG(errs() << "IC: Old = " << *I << '\n'
12915                      << "    New = " << *Result << '\n');
12916
12917         // Everything uses the new instruction now.
12918         I->replaceAllUsesWith(Result);
12919
12920         // Push the new instruction and any users onto the worklist.
12921         Worklist.Add(Result);
12922         Worklist.AddUsersToWorkList(*Result);
12923
12924         // Move the name to the new instruction first.
12925         Result->takeName(I);
12926
12927         // Insert the new instruction into the basic block...
12928         BasicBlock *InstParent = I->getParent();
12929         BasicBlock::iterator InsertPos = I;
12930
12931         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12932           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12933             ++InsertPos;
12934
12935         InstParent->getInstList().insert(InsertPos, Result);
12936
12937         EraseInstFromFunction(*I);
12938       } else {
12939 #ifndef NDEBUG
12940         DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12941                      << "    New = " << *I << '\n');
12942 #endif
12943
12944         // If the instruction was modified, it's possible that it is now dead.
12945         // if so, remove it.
12946         if (isInstructionTriviallyDead(I)) {
12947           EraseInstFromFunction(*I);
12948         } else {
12949           Worklist.Add(I);
12950           Worklist.AddUsersToWorkList(*I);
12951         }
12952       }
12953       MadeIRChange = true;
12954     }
12955   }
12956
12957   Worklist.Zap();
12958   return MadeIRChange;
12959 }
12960
12961
12962 bool InstCombiner::runOnFunction(Function &F) {
12963   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12964   Context = &F.getContext();
12965   TD = getAnalysisIfAvailable<TargetData>();
12966
12967   
12968   /// Builder - This is an IRBuilder that automatically inserts new
12969   /// instructions into the worklist when they are created.
12970   IRBuilder<true, TargetFolder, InstCombineIRInserter> 
12971     TheBuilder(F.getContext(), TargetFolder(TD, F.getContext()),
12972                InstCombineIRInserter(Worklist));
12973   Builder = &TheBuilder;
12974   
12975   bool EverMadeChange = false;
12976
12977   // Iterate while there is work to do.
12978   unsigned Iteration = 0;
12979   while (DoOneIteration(F, Iteration++))
12980     EverMadeChange = true;
12981   
12982   Builder = 0;
12983   return EverMadeChange;
12984 }
12985
12986 FunctionPass *llvm::createInstructionCombiningPass() {
12987   return new InstCombiner();
12988 }