remove the IndMemRemPass, which only made sense for when malloc/free were intrinsic
[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           Worklist.Add(LHSI);
6309           return ReplaceInstUsesWith(I,
6310                                      ConstantInt::get(Type::getInt1Ty(*Context),
6311                                                       !I.isTrueWhenEqual()));
6312         }
6313         break;
6314       }
6315   }
6316
6317   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6318   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6319     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6320       return NI;
6321   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6322     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6323                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6324       return NI;
6325
6326   // Test to see if the operands of the icmp are casted versions of other
6327   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6328   // now.
6329   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6330     if (isa<PointerType>(Op0->getType()) && 
6331         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6332       // We keep moving the cast from the left operand over to the right
6333       // operand, where it can often be eliminated completely.
6334       Op0 = CI->getOperand(0);
6335
6336       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6337       // so eliminate it as well.
6338       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6339         Op1 = CI2->getOperand(0);
6340
6341       // If Op1 is a constant, we can fold the cast into the constant.
6342       if (Op0->getType() != Op1->getType()) {
6343         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6344           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6345         } else {
6346           // Otherwise, cast the RHS right before the icmp
6347           Op1 = Builder->CreateBitCast(Op1, Op0->getType());
6348         }
6349       }
6350       return new ICmpInst(I.getPredicate(), Op0, Op1);
6351     }
6352   }
6353   
6354   if (isa<CastInst>(Op0)) {
6355     // Handle the special case of: icmp (cast bool to X), <cst>
6356     // This comes up when you have code like
6357     //   int X = A < B;
6358     //   if (X) ...
6359     // For generality, we handle any zero-extension of any operand comparison
6360     // with a constant or another cast from the same type.
6361     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6362       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6363         return R;
6364   }
6365   
6366   // See if it's the same type of instruction on the left and right.
6367   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6368     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6369       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6370           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6371         switch (Op0I->getOpcode()) {
6372         default: break;
6373         case Instruction::Add:
6374         case Instruction::Sub:
6375         case Instruction::Xor:
6376           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6377             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6378                                 Op1I->getOperand(0));
6379           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6380           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6381             if (CI->getValue().isSignBit()) {
6382               ICmpInst::Predicate Pred = I.isSignedPredicate()
6383                                              ? I.getUnsignedPredicate()
6384                                              : I.getSignedPredicate();
6385               return new ICmpInst(Pred, Op0I->getOperand(0),
6386                                   Op1I->getOperand(0));
6387             }
6388             
6389             if (CI->getValue().isMaxSignedValue()) {
6390               ICmpInst::Predicate Pred = I.isSignedPredicate()
6391                                              ? I.getUnsignedPredicate()
6392                                              : I.getSignedPredicate();
6393               Pred = I.getSwappedPredicate(Pred);
6394               return new ICmpInst(Pred, Op0I->getOperand(0),
6395                                   Op1I->getOperand(0));
6396             }
6397           }
6398           break;
6399         case Instruction::Mul:
6400           if (!I.isEquality())
6401             break;
6402
6403           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6404             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6405             // Mask = -1 >> count-trailing-zeros(Cst).
6406             if (!CI->isZero() && !CI->isOne()) {
6407               const APInt &AP = CI->getValue();
6408               ConstantInt *Mask = ConstantInt::get(*Context, 
6409                                       APInt::getLowBitsSet(AP.getBitWidth(),
6410                                                            AP.getBitWidth() -
6411                                                       AP.countTrailingZeros()));
6412               Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6413               Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
6414               return new ICmpInst(I.getPredicate(), And1, And2);
6415             }
6416           }
6417           break;
6418         }
6419       }
6420     }
6421   }
6422   
6423   // ~x < ~y --> y < x
6424   { Value *A, *B;
6425     if (match(Op0, m_Not(m_Value(A))) &&
6426         match(Op1, m_Not(m_Value(B))))
6427       return new ICmpInst(I.getPredicate(), B, A);
6428   }
6429   
6430   if (I.isEquality()) {
6431     Value *A, *B, *C, *D;
6432     
6433     // -x == -y --> x == y
6434     if (match(Op0, m_Neg(m_Value(A))) &&
6435         match(Op1, m_Neg(m_Value(B))))
6436       return new ICmpInst(I.getPredicate(), A, B);
6437     
6438     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6439       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6440         Value *OtherVal = A == Op1 ? B : A;
6441         return new ICmpInst(I.getPredicate(), OtherVal,
6442                             Constant::getNullValue(A->getType()));
6443       }
6444
6445       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6446         // A^c1 == C^c2 --> A == C^(c1^c2)
6447         ConstantInt *C1, *C2;
6448         if (match(B, m_ConstantInt(C1)) &&
6449             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6450           Constant *NC = 
6451                    ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6452           Value *Xor = Builder->CreateXor(C, NC, "tmp");
6453           return new ICmpInst(I.getPredicate(), A, Xor);
6454         }
6455         
6456         // A^B == A^D -> B == D
6457         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6458         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6459         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6460         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6461       }
6462     }
6463     
6464     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6465         (A == Op0 || B == Op0)) {
6466       // A == (A^B)  ->  B == 0
6467       Value *OtherVal = A == Op0 ? B : A;
6468       return new ICmpInst(I.getPredicate(), OtherVal,
6469                           Constant::getNullValue(A->getType()));
6470     }
6471
6472     // (A-B) == A  ->  B == 0
6473     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6474       return new ICmpInst(I.getPredicate(), B, 
6475                           Constant::getNullValue(B->getType()));
6476
6477     // A == (A-B)  ->  B == 0
6478     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6479       return new ICmpInst(I.getPredicate(), B,
6480                           Constant::getNullValue(B->getType()));
6481     
6482     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6483     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6484         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6485         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6486       Value *X = 0, *Y = 0, *Z = 0;
6487       
6488       if (A == C) {
6489         X = B; Y = D; Z = A;
6490       } else if (A == D) {
6491         X = B; Y = C; Z = A;
6492       } else if (B == C) {
6493         X = A; Y = D; Z = B;
6494       } else if (B == D) {
6495         X = A; Y = C; Z = B;
6496       }
6497       
6498       if (X) {   // Build (X^Y) & Z
6499         Op1 = Builder->CreateXor(X, Y, "tmp");
6500         Op1 = Builder->CreateAnd(Op1, Z, "tmp");
6501         I.setOperand(0, Op1);
6502         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6503         return &I;
6504       }
6505     }
6506   }
6507   return Changed ? &I : 0;
6508 }
6509
6510
6511 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6512 /// and CmpRHS are both known to be integer constants.
6513 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6514                                           ConstantInt *DivRHS) {
6515   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6516   const APInt &CmpRHSV = CmpRHS->getValue();
6517   
6518   // FIXME: If the operand types don't match the type of the divide 
6519   // then don't attempt this transform. The code below doesn't have the
6520   // logic to deal with a signed divide and an unsigned compare (and
6521   // vice versa). This is because (x /s C1) <s C2  produces different 
6522   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6523   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6524   // work. :(  The if statement below tests that condition and bails 
6525   // if it finds it. 
6526   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6527   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6528     return 0;
6529   if (DivRHS->isZero())
6530     return 0; // The ProdOV computation fails on divide by zero.
6531   if (DivIsSigned && DivRHS->isAllOnesValue())
6532     return 0; // The overflow computation also screws up here
6533   if (DivRHS->isOne())
6534     return 0; // Not worth bothering, and eliminates some funny cases
6535               // with INT_MIN.
6536
6537   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6538   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6539   // C2 (CI). By solving for X we can turn this into a range check 
6540   // instead of computing a divide. 
6541   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6542
6543   // Determine if the product overflows by seeing if the product is
6544   // not equal to the divide. Make sure we do the same kind of divide
6545   // as in the LHS instruction that we're folding. 
6546   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6547                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6548
6549   // Get the ICmp opcode
6550   ICmpInst::Predicate Pred = ICI.getPredicate();
6551
6552   // Figure out the interval that is being checked.  For example, a comparison
6553   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6554   // Compute this interval based on the constants involved and the signedness of
6555   // the compare/divide.  This computes a half-open interval, keeping track of
6556   // whether either value in the interval overflows.  After analysis each
6557   // overflow variable is set to 0 if it's corresponding bound variable is valid
6558   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6559   int LoOverflow = 0, HiOverflow = 0;
6560   Constant *LoBound = 0, *HiBound = 0;
6561   
6562   if (!DivIsSigned) {  // udiv
6563     // e.g. X/5 op 3  --> [15, 20)
6564     LoBound = Prod;
6565     HiOverflow = LoOverflow = ProdOV;
6566     if (!HiOverflow)
6567       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6568   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6569     if (CmpRHSV == 0) {       // (X / pos) op 0
6570       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6571       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6572       HiBound = DivRHS;
6573     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6574       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6575       HiOverflow = LoOverflow = ProdOV;
6576       if (!HiOverflow)
6577         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6578     } else {                       // (X / pos) op neg
6579       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6580       HiBound = AddOne(Prod);
6581       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6582       if (!LoOverflow) {
6583         ConstantInt* DivNeg =
6584                          cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6585         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6586                                      true) ? -1 : 0;
6587        }
6588     }
6589   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6590     if (CmpRHSV == 0) {       // (X / neg) op 0
6591       // e.g. X/-5 op 0  --> [-4, 5)
6592       LoBound = AddOne(DivRHS);
6593       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6594       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6595         HiOverflow = 1;            // [INTMIN+1, overflow)
6596         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6597       }
6598     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6599       // e.g. X/-5 op 3  --> [-19, -14)
6600       HiBound = AddOne(Prod);
6601       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6602       if (!LoOverflow)
6603         LoOverflow = AddWithOverflow(LoBound, HiBound,
6604                                      DivRHS, Context, true) ? -1 : 0;
6605     } else {                       // (X / neg) op neg
6606       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6607       LoOverflow = HiOverflow = ProdOV;
6608       if (!HiOverflow)
6609         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6610     }
6611     
6612     // Dividing by a negative swaps the condition.  LT <-> GT
6613     Pred = ICmpInst::getSwappedPredicate(Pred);
6614   }
6615
6616   Value *X = DivI->getOperand(0);
6617   switch (Pred) {
6618   default: llvm_unreachable("Unhandled icmp opcode!");
6619   case ICmpInst::ICMP_EQ:
6620     if (LoOverflow && HiOverflow)
6621       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6622     else if (HiOverflow)
6623       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6624                           ICmpInst::ICMP_UGE, X, LoBound);
6625     else if (LoOverflow)
6626       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6627                           ICmpInst::ICMP_ULT, X, HiBound);
6628     else
6629       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6630   case ICmpInst::ICMP_NE:
6631     if (LoOverflow && HiOverflow)
6632       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6633     else if (HiOverflow)
6634       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6635                           ICmpInst::ICMP_ULT, X, LoBound);
6636     else if (LoOverflow)
6637       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6638                           ICmpInst::ICMP_UGE, X, HiBound);
6639     else
6640       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6641   case ICmpInst::ICMP_ULT:
6642   case ICmpInst::ICMP_SLT:
6643     if (LoOverflow == +1)   // Low bound is greater than input range.
6644       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6645     if (LoOverflow == -1)   // Low bound is less than input range.
6646       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6647     return new ICmpInst(Pred, X, LoBound);
6648   case ICmpInst::ICMP_UGT:
6649   case ICmpInst::ICMP_SGT:
6650     if (HiOverflow == +1)       // High bound greater than input range.
6651       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6652     else if (HiOverflow == -1)  // High bound less than input range.
6653       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6654     if (Pred == ICmpInst::ICMP_UGT)
6655       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6656     else
6657       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6658   }
6659 }
6660
6661
6662 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6663 ///
6664 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6665                                                           Instruction *LHSI,
6666                                                           ConstantInt *RHS) {
6667   const APInt &RHSV = RHS->getValue();
6668   
6669   switch (LHSI->getOpcode()) {
6670   case Instruction::Trunc:
6671     if (ICI.isEquality() && LHSI->hasOneUse()) {
6672       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6673       // of the high bits truncated out of x are known.
6674       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6675              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6676       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6677       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6678       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6679       
6680       // If all the high bits are known, we can do this xform.
6681       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6682         // Pull in the high bits from known-ones set.
6683         APInt NewRHS(RHS->getValue());
6684         NewRHS.zext(SrcBits);
6685         NewRHS |= KnownOne;
6686         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6687                             ConstantInt::get(*Context, NewRHS));
6688       }
6689     }
6690     break;
6691       
6692   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6693     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6694       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6695       // fold the xor.
6696       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6697           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6698         Value *CompareVal = LHSI->getOperand(0);
6699         
6700         // If the sign bit of the XorCST is not set, there is no change to
6701         // the operation, just stop using the Xor.
6702         if (!XorCST->getValue().isNegative()) {
6703           ICI.setOperand(0, CompareVal);
6704           Worklist.Add(LHSI);
6705           return &ICI;
6706         }
6707         
6708         // Was the old condition true if the operand is positive?
6709         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6710         
6711         // If so, the new one isn't.
6712         isTrueIfPositive ^= true;
6713         
6714         if (isTrueIfPositive)
6715           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
6716                               SubOne(RHS));
6717         else
6718           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
6719                               AddOne(RHS));
6720       }
6721
6722       if (LHSI->hasOneUse()) {
6723         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6724         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6725           const APInt &SignBit = XorCST->getValue();
6726           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6727                                          ? ICI.getUnsignedPredicate()
6728                                          : ICI.getSignedPredicate();
6729           return new ICmpInst(Pred, LHSI->getOperand(0),
6730                               ConstantInt::get(*Context, RHSV ^ SignBit));
6731         }
6732
6733         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6734         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6735           const APInt &NotSignBit = XorCST->getValue();
6736           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6737                                          ? ICI.getUnsignedPredicate()
6738                                          : ICI.getSignedPredicate();
6739           Pred = ICI.getSwappedPredicate(Pred);
6740           return new ICmpInst(Pred, LHSI->getOperand(0),
6741                               ConstantInt::get(*Context, RHSV ^ NotSignBit));
6742         }
6743       }
6744     }
6745     break;
6746   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6747     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6748         LHSI->getOperand(0)->hasOneUse()) {
6749       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6750       
6751       // If the LHS is an AND of a truncating cast, we can widen the
6752       // and/compare to be the input width without changing the value
6753       // produced, eliminating a cast.
6754       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6755         // We can do this transformation if either the AND constant does not
6756         // have its sign bit set or if it is an equality comparison. 
6757         // Extending a relational comparison when we're checking the sign
6758         // bit would not work.
6759         if (Cast->hasOneUse() &&
6760             (ICI.isEquality() ||
6761              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6762           uint32_t BitWidth = 
6763             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6764           APInt NewCST = AndCST->getValue();
6765           NewCST.zext(BitWidth);
6766           APInt NewCI = RHSV;
6767           NewCI.zext(BitWidth);
6768           Value *NewAnd = 
6769             Builder->CreateAnd(Cast->getOperand(0),
6770                            ConstantInt::get(*Context, NewCST), LHSI->getName());
6771           return new ICmpInst(ICI.getPredicate(), NewAnd,
6772                               ConstantInt::get(*Context, NewCI));
6773         }
6774       }
6775       
6776       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6777       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6778       // happens a LOT in code produced by the C front-end, for bitfield
6779       // access.
6780       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6781       if (Shift && !Shift->isShift())
6782         Shift = 0;
6783       
6784       ConstantInt *ShAmt;
6785       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6786       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6787       const Type *AndTy = AndCST->getType();          // Type of the and.
6788       
6789       // We can fold this as long as we can't shift unknown bits
6790       // into the mask.  This can only happen with signed shift
6791       // rights, as they sign-extend.
6792       if (ShAmt) {
6793         bool CanFold = Shift->isLogicalShift();
6794         if (!CanFold) {
6795           // To test for the bad case of the signed shr, see if any
6796           // of the bits shifted in could be tested after the mask.
6797           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6798           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6799           
6800           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6801           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6802                AndCST->getValue()) == 0)
6803             CanFold = true;
6804         }
6805         
6806         if (CanFold) {
6807           Constant *NewCst;
6808           if (Shift->getOpcode() == Instruction::Shl)
6809             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6810           else
6811             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6812           
6813           // Check to see if we are shifting out any of the bits being
6814           // compared.
6815           if (ConstantExpr::get(Shift->getOpcode(),
6816                                        NewCst, ShAmt) != RHS) {
6817             // If we shifted bits out, the fold is not going to work out.
6818             // As a special case, check to see if this means that the
6819             // result is always true or false now.
6820             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6821               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6822             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6823               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6824           } else {
6825             ICI.setOperand(1, NewCst);
6826             Constant *NewAndCST;
6827             if (Shift->getOpcode() == Instruction::Shl)
6828               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6829             else
6830               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6831             LHSI->setOperand(1, NewAndCST);
6832             LHSI->setOperand(0, Shift->getOperand(0));
6833             Worklist.Add(Shift); // Shift is dead.
6834             return &ICI;
6835           }
6836         }
6837       }
6838       
6839       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6840       // preferable because it allows the C<<Y expression to be hoisted out
6841       // of a loop if Y is invariant and X is not.
6842       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6843           ICI.isEquality() && !Shift->isArithmeticShift() &&
6844           !isa<Constant>(Shift->getOperand(0))) {
6845         // Compute C << Y.
6846         Value *NS;
6847         if (Shift->getOpcode() == Instruction::LShr) {
6848           NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
6849         } else {
6850           // Insert a logical shift.
6851           NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
6852         }
6853         
6854         // Compute X & (C << Y).
6855         Value *NewAnd = 
6856           Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6857         
6858         ICI.setOperand(0, NewAnd);
6859         return &ICI;
6860       }
6861     }
6862     break;
6863     
6864   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6865     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6866     if (!ShAmt) break;
6867     
6868     uint32_t TypeBits = RHSV.getBitWidth();
6869     
6870     // Check that the shift amount is in range.  If not, don't perform
6871     // undefined shifts.  When the shift is visited it will be
6872     // simplified.
6873     if (ShAmt->uge(TypeBits))
6874       break;
6875     
6876     if (ICI.isEquality()) {
6877       // If we are comparing against bits always shifted out, the
6878       // comparison cannot succeed.
6879       Constant *Comp =
6880         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
6881                                                                  ShAmt);
6882       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6883         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6884         Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6885         return ReplaceInstUsesWith(ICI, Cst);
6886       }
6887       
6888       if (LHSI->hasOneUse()) {
6889         // Otherwise strength reduce the shift into an and.
6890         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6891         Constant *Mask =
6892           ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits, 
6893                                                        TypeBits-ShAmtVal));
6894         
6895         Value *And =
6896           Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
6897         return new ICmpInst(ICI.getPredicate(), And,
6898                             ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
6899       }
6900     }
6901     
6902     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6903     bool TrueIfSigned = false;
6904     if (LHSI->hasOneUse() &&
6905         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6906       // (X << 31) <s 0  --> (X&1) != 0
6907       Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
6908                                            (TypeBits-ShAmt->getZExtValue()-1));
6909       Value *And =
6910         Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
6911       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6912                           And, Constant::getNullValue(And->getType()));
6913     }
6914     break;
6915   }
6916     
6917   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6918   case Instruction::AShr: {
6919     // Only handle equality comparisons of shift-by-constant.
6920     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6921     if (!ShAmt || !ICI.isEquality()) break;
6922
6923     // Check that the shift amount is in range.  If not, don't perform
6924     // undefined shifts.  When the shift is visited it will be
6925     // simplified.
6926     uint32_t TypeBits = RHSV.getBitWidth();
6927     if (ShAmt->uge(TypeBits))
6928       break;
6929     
6930     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6931       
6932     // If we are comparing against bits always shifted out, the
6933     // comparison cannot succeed.
6934     APInt Comp = RHSV << ShAmtVal;
6935     if (LHSI->getOpcode() == Instruction::LShr)
6936       Comp = Comp.lshr(ShAmtVal);
6937     else
6938       Comp = Comp.ashr(ShAmtVal);
6939     
6940     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6941       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6942       Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6943       return ReplaceInstUsesWith(ICI, Cst);
6944     }
6945     
6946     // Otherwise, check to see if the bits shifted out are known to be zero.
6947     // If so, we can compare against the unshifted value:
6948     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6949     if (LHSI->hasOneUse() &&
6950         MaskedValueIsZero(LHSI->getOperand(0), 
6951                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6952       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6953                           ConstantExpr::getShl(RHS, ShAmt));
6954     }
6955       
6956     if (LHSI->hasOneUse()) {
6957       // Otherwise strength reduce the shift into an and.
6958       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6959       Constant *Mask = ConstantInt::get(*Context, Val);
6960       
6961       Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6962                                       Mask, LHSI->getName()+".mask");
6963       return new ICmpInst(ICI.getPredicate(), And,
6964                           ConstantExpr::getShl(RHS, ShAmt));
6965     }
6966     break;
6967   }
6968     
6969   case Instruction::SDiv:
6970   case Instruction::UDiv:
6971     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6972     // Fold this div into the comparison, producing a range check. 
6973     // Determine, based on the divide type, what the range is being 
6974     // checked.  If there is an overflow on the low or high side, remember 
6975     // it, otherwise compute the range [low, hi) bounding the new value.
6976     // See: InsertRangeTest above for the kinds of replacements possible.
6977     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6978       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6979                                           DivRHS))
6980         return R;
6981     break;
6982
6983   case Instruction::Add:
6984     // Fold: icmp pred (add, X, C1), C2
6985
6986     if (!ICI.isEquality()) {
6987       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6988       if (!LHSC) break;
6989       const APInt &LHSV = LHSC->getValue();
6990
6991       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6992                             .subtract(LHSV);
6993
6994       if (ICI.isSignedPredicate()) {
6995         if (CR.getLower().isSignBit()) {
6996           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6997                               ConstantInt::get(*Context, CR.getUpper()));
6998         } else if (CR.getUpper().isSignBit()) {
6999           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7000                               ConstantInt::get(*Context, CR.getLower()));
7001         }
7002       } else {
7003         if (CR.getLower().isMinValue()) {
7004           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7005                               ConstantInt::get(*Context, CR.getUpper()));
7006         } else if (CR.getUpper().isMinValue()) {
7007           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7008                               ConstantInt::get(*Context, CR.getLower()));
7009         }
7010       }
7011     }
7012     break;
7013   }
7014   
7015   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7016   if (ICI.isEquality()) {
7017     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7018     
7019     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7020     // the second operand is a constant, simplify a bit.
7021     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7022       switch (BO->getOpcode()) {
7023       case Instruction::SRem:
7024         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7025         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7026           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7027           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7028             Value *NewRem =
7029               Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7030                                   BO->getName());
7031             return new ICmpInst(ICI.getPredicate(), NewRem,
7032                                 Constant::getNullValue(BO->getType()));
7033           }
7034         }
7035         break;
7036       case Instruction::Add:
7037         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7038         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7039           if (BO->hasOneUse())
7040             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7041                                 ConstantExpr::getSub(RHS, BOp1C));
7042         } else if (RHSV == 0) {
7043           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7044           // efficiently invertible, or if the add has just this one use.
7045           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7046           
7047           if (Value *NegVal = dyn_castNegVal(BOp1))
7048             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
7049           else if (Value *NegVal = dyn_castNegVal(BOp0))
7050             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
7051           else if (BO->hasOneUse()) {
7052             Value *Neg = Builder->CreateNeg(BOp1);
7053             Neg->takeName(BO);
7054             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
7055           }
7056         }
7057         break;
7058       case Instruction::Xor:
7059         // For the xor case, we can xor two constants together, eliminating
7060         // the explicit xor.
7061         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7062           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
7063                               ConstantExpr::getXor(RHS, BOC));
7064         
7065         // FALLTHROUGH
7066       case Instruction::Sub:
7067         // Replace (([sub|xor] A, B) != 0) with (A != B)
7068         if (RHSV == 0)
7069           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7070                               BO->getOperand(1));
7071         break;
7072         
7073       case Instruction::Or:
7074         // If bits are being or'd in that are not present in the constant we
7075         // are comparing against, then the comparison could never succeed!
7076         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7077           Constant *NotCI = ConstantExpr::getNot(RHS);
7078           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7079             return ReplaceInstUsesWith(ICI,
7080                                        ConstantInt::get(Type::getInt1Ty(*Context), 
7081                                        isICMP_NE));
7082         }
7083         break;
7084         
7085       case Instruction::And:
7086         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7087           // If bits are being compared against that are and'd out, then the
7088           // comparison can never succeed!
7089           if ((RHSV & ~BOC->getValue()) != 0)
7090             return ReplaceInstUsesWith(ICI,
7091                                        ConstantInt::get(Type::getInt1Ty(*Context),
7092                                        isICMP_NE));
7093           
7094           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7095           if (RHS == BOC && RHSV.isPowerOf2())
7096             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7097                                 ICmpInst::ICMP_NE, LHSI,
7098                                 Constant::getNullValue(RHS->getType()));
7099           
7100           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7101           if (BOC->getValue().isSignBit()) {
7102             Value *X = BO->getOperand(0);
7103             Constant *Zero = Constant::getNullValue(X->getType());
7104             ICmpInst::Predicate pred = isICMP_NE ? 
7105               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7106             return new ICmpInst(pred, X, Zero);
7107           }
7108           
7109           // ((X & ~7) == 0) --> X < 8
7110           if (RHSV == 0 && isHighOnes(BOC)) {
7111             Value *X = BO->getOperand(0);
7112             Constant *NegX = ConstantExpr::getNeg(BOC);
7113             ICmpInst::Predicate pred = isICMP_NE ? 
7114               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7115             return new ICmpInst(pred, X, NegX);
7116           }
7117         }
7118       default: break;
7119       }
7120     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7121       // Handle icmp {eq|ne} <intrinsic>, intcst.
7122       if (II->getIntrinsicID() == Intrinsic::bswap) {
7123         Worklist.Add(II);
7124         ICI.setOperand(0, II->getOperand(1));
7125         ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7126         return &ICI;
7127       }
7128     }
7129   }
7130   return 0;
7131 }
7132
7133 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7134 /// We only handle extending casts so far.
7135 ///
7136 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7137   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7138   Value *LHSCIOp        = LHSCI->getOperand(0);
7139   const Type *SrcTy     = LHSCIOp->getType();
7140   const Type *DestTy    = LHSCI->getType();
7141   Value *RHSCIOp;
7142
7143   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7144   // integer type is the same size as the pointer type.
7145   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7146       TD->getPointerSizeInBits() ==
7147          cast<IntegerType>(DestTy)->getBitWidth()) {
7148     Value *RHSOp = 0;
7149     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7150       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7151     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7152       RHSOp = RHSC->getOperand(0);
7153       // If the pointer types don't match, insert a bitcast.
7154       if (LHSCIOp->getType() != RHSOp->getType())
7155         RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
7156     }
7157
7158     if (RHSOp)
7159       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7160   }
7161   
7162   // The code below only handles extension cast instructions, so far.
7163   // Enforce this.
7164   if (LHSCI->getOpcode() != Instruction::ZExt &&
7165       LHSCI->getOpcode() != Instruction::SExt)
7166     return 0;
7167
7168   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7169   bool isSignedCmp = ICI.isSignedPredicate();
7170
7171   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7172     // Not an extension from the same type?
7173     RHSCIOp = CI->getOperand(0);
7174     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7175       return 0;
7176     
7177     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7178     // and the other is a zext), then we can't handle this.
7179     if (CI->getOpcode() != LHSCI->getOpcode())
7180       return 0;
7181
7182     // Deal with equality cases early.
7183     if (ICI.isEquality())
7184       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7185
7186     // A signed comparison of sign extended values simplifies into a
7187     // signed comparison.
7188     if (isSignedCmp && isSignedExt)
7189       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7190
7191     // The other three cases all fold into an unsigned comparison.
7192     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7193   }
7194
7195   // If we aren't dealing with a constant on the RHS, exit early
7196   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7197   if (!CI)
7198     return 0;
7199
7200   // Compute the constant that would happen if we truncated to SrcTy then
7201   // reextended to DestTy.
7202   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7203   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7204                                                 Res1, DestTy);
7205
7206   // If the re-extended constant didn't change...
7207   if (Res2 == CI) {
7208     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7209     // For example, we might have:
7210     //    %A = sext i16 %X to i32
7211     //    %B = icmp ugt i32 %A, 1330
7212     // It is incorrect to transform this into 
7213     //    %B = icmp ugt i16 %X, 1330
7214     // because %A may have negative value. 
7215     //
7216     // However, we allow this when the compare is EQ/NE, because they are
7217     // signless.
7218     if (isSignedExt == isSignedCmp || ICI.isEquality())
7219       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7220     return 0;
7221   }
7222
7223   // The re-extended constant changed so the constant cannot be represented 
7224   // in the shorter type. Consequently, we cannot emit a simple comparison.
7225
7226   // First, handle some easy cases. We know the result cannot be equal at this
7227   // point so handle the ICI.isEquality() cases
7228   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7229     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7230   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7231     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7232
7233   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7234   // should have been folded away previously and not enter in here.
7235   Value *Result;
7236   if (isSignedCmp) {
7237     // We're performing a signed comparison.
7238     if (cast<ConstantInt>(CI)->getValue().isNegative())
7239       Result = ConstantInt::getFalse(*Context);          // X < (small) --> false
7240     else
7241       Result = ConstantInt::getTrue(*Context);           // X < (large) --> true
7242   } else {
7243     // We're performing an unsigned comparison.
7244     if (isSignedExt) {
7245       // We're performing an unsigned comp with a sign extended value.
7246       // This is true if the input is >= 0. [aka >s -1]
7247       Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7248       Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
7249     } else {
7250       // Unsigned extend & unsigned compare -> always true.
7251       Result = ConstantInt::getTrue(*Context);
7252     }
7253   }
7254
7255   // Finally, return the value computed.
7256   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7257       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7258     return ReplaceInstUsesWith(ICI, Result);
7259
7260   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7261           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7262          "ICmp should be folded!");
7263   if (Constant *CI = dyn_cast<Constant>(Result))
7264     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7265   return BinaryOperator::CreateNot(Result);
7266 }
7267
7268 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7269   return commonShiftTransforms(I);
7270 }
7271
7272 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7273   return commonShiftTransforms(I);
7274 }
7275
7276 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7277   if (Instruction *R = commonShiftTransforms(I))
7278     return R;
7279   
7280   Value *Op0 = I.getOperand(0);
7281   
7282   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7283   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7284     if (CSI->isAllOnesValue())
7285       return ReplaceInstUsesWith(I, CSI);
7286
7287   // See if we can turn a signed shr into an unsigned shr.
7288   if (MaskedValueIsZero(Op0,
7289                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7290     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7291
7292   // Arithmetic shifting an all-sign-bit value is a no-op.
7293   unsigned NumSignBits = ComputeNumSignBits(Op0);
7294   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7295     return ReplaceInstUsesWith(I, Op0);
7296
7297   return 0;
7298 }
7299
7300 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7301   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7302   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7303
7304   // shl X, 0 == X and shr X, 0 == X
7305   // shl 0, X == 0 and shr 0, X == 0
7306   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7307       Op0 == Constant::getNullValue(Op0->getType()))
7308     return ReplaceInstUsesWith(I, Op0);
7309   
7310   if (isa<UndefValue>(Op0)) {            
7311     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7312       return ReplaceInstUsesWith(I, Op0);
7313     else                                    // undef << X -> 0, undef >>u X -> 0
7314       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7315   }
7316   if (isa<UndefValue>(Op1)) {
7317     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7318       return ReplaceInstUsesWith(I, Op0);          
7319     else                                     // X << undef, X >>u undef -> 0
7320       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7321   }
7322
7323   // See if we can fold away this shift.
7324   if (SimplifyDemandedInstructionBits(I))
7325     return &I;
7326
7327   // Try to fold constant and into select arguments.
7328   if (isa<Constant>(Op0))
7329     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7330       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7331         return R;
7332
7333   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7334     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7335       return Res;
7336   return 0;
7337 }
7338
7339 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7340                                                BinaryOperator &I) {
7341   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7342
7343   // See if we can simplify any instructions used by the instruction whose sole 
7344   // purpose is to compute bits we don't care about.
7345   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7346   
7347   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7348   // a signed shift.
7349   //
7350   if (Op1->uge(TypeBits)) {
7351     if (I.getOpcode() != Instruction::AShr)
7352       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7353     else {
7354       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7355       return &I;
7356     }
7357   }
7358   
7359   // ((X*C1) << C2) == (X * (C1 << C2))
7360   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7361     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7362       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7363         return BinaryOperator::CreateMul(BO->getOperand(0),
7364                                         ConstantExpr::getShl(BOOp, Op1));
7365   
7366   // Try to fold constant and into select arguments.
7367   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7368     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7369       return R;
7370   if (isa<PHINode>(Op0))
7371     if (Instruction *NV = FoldOpIntoPhi(I))
7372       return NV;
7373   
7374   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7375   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7376     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7377     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7378     // place.  Don't try to do this transformation in this case.  Also, we
7379     // require that the input operand is a shift-by-constant so that we have
7380     // confidence that the shifts will get folded together.  We could do this
7381     // xform in more cases, but it is unlikely to be profitable.
7382     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7383         isa<ConstantInt>(TrOp->getOperand(1))) {
7384       // Okay, we'll do this xform.  Make the shift of shift.
7385       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7386       // (shift2 (shift1 & 0x00FF), c2)
7387       Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
7388
7389       // For logical shifts, the truncation has the effect of making the high
7390       // part of the register be zeros.  Emulate this by inserting an AND to
7391       // clear the top bits as needed.  This 'and' will usually be zapped by
7392       // other xforms later if dead.
7393       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7394       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7395       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7396       
7397       // The mask we constructed says what the trunc would do if occurring
7398       // between the shifts.  We want to know the effect *after* the second
7399       // shift.  We know that it is a logical shift by a constant, so adjust the
7400       // mask as appropriate.
7401       if (I.getOpcode() == Instruction::Shl)
7402         MaskV <<= Op1->getZExtValue();
7403       else {
7404         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7405         MaskV = MaskV.lshr(Op1->getZExtValue());
7406       }
7407
7408       // shift1 & 0x00FF
7409       Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7410                                       TI->getName());
7411
7412       // Return the value truncated to the interesting size.
7413       return new TruncInst(And, I.getType());
7414     }
7415   }
7416   
7417   if (Op0->hasOneUse()) {
7418     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7419       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7420       Value *V1, *V2;
7421       ConstantInt *CC;
7422       switch (Op0BO->getOpcode()) {
7423         default: break;
7424         case Instruction::Add:
7425         case Instruction::And:
7426         case Instruction::Or:
7427         case Instruction::Xor: {
7428           // These operators commute.
7429           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7430           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7431               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7432                     m_Specific(Op1)))) {
7433             Value *YS =         // (Y << C)
7434               Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7435             // (X + (Y << C))
7436             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7437                                             Op0BO->getOperand(1)->getName());
7438             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7439             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7440                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7441           }
7442           
7443           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7444           Value *Op0BOOp1 = Op0BO->getOperand(1);
7445           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7446               match(Op0BOOp1, 
7447                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7448                           m_ConstantInt(CC))) &&
7449               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7450             Value *YS =   // (Y << C)
7451               Builder->CreateShl(Op0BO->getOperand(0), Op1,
7452                                            Op0BO->getName());
7453             // X & (CC << C)
7454             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7455                                            V1->getName()+".mask");
7456             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7457           }
7458         }
7459           
7460         // FALL THROUGH.
7461         case Instruction::Sub: {
7462           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7463           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7464               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7465                     m_Specific(Op1)))) {
7466             Value *YS =  // (Y << C)
7467               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7468             // (X + (Y << C))
7469             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7470                                             Op0BO->getOperand(0)->getName());
7471             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7472             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7473                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7474           }
7475           
7476           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7477           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7478               match(Op0BO->getOperand(0),
7479                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7480                           m_ConstantInt(CC))) && V2 == Op1 &&
7481               cast<BinaryOperator>(Op0BO->getOperand(0))
7482                   ->getOperand(0)->hasOneUse()) {
7483             Value *YS = // (Y << C)
7484               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7485             // X & (CC << C)
7486             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7487                                            V1->getName()+".mask");
7488             
7489             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7490           }
7491           
7492           break;
7493         }
7494       }
7495       
7496       
7497       // If the operand is an bitwise operator with a constant RHS, and the
7498       // shift is the only use, we can pull it out of the shift.
7499       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7500         bool isValid = true;     // Valid only for And, Or, Xor
7501         bool highBitSet = false; // Transform if high bit of constant set?
7502         
7503         switch (Op0BO->getOpcode()) {
7504           default: isValid = false; break;   // Do not perform transform!
7505           case Instruction::Add:
7506             isValid = isLeftShift;
7507             break;
7508           case Instruction::Or:
7509           case Instruction::Xor:
7510             highBitSet = false;
7511             break;
7512           case Instruction::And:
7513             highBitSet = true;
7514             break;
7515         }
7516         
7517         // If this is a signed shift right, and the high bit is modified
7518         // by the logical operation, do not perform the transformation.
7519         // The highBitSet boolean indicates the value of the high bit of
7520         // the constant which would cause it to be modified for this
7521         // operation.
7522         //
7523         if (isValid && I.getOpcode() == Instruction::AShr)
7524           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7525         
7526         if (isValid) {
7527           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7528           
7529           Value *NewShift =
7530             Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
7531           NewShift->takeName(Op0BO);
7532           
7533           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7534                                         NewRHS);
7535         }
7536       }
7537     }
7538   }
7539   
7540   // Find out if this is a shift of a shift by a constant.
7541   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7542   if (ShiftOp && !ShiftOp->isShift())
7543     ShiftOp = 0;
7544   
7545   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7546     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7547     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7548     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7549     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7550     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7551     Value *X = ShiftOp->getOperand(0);
7552     
7553     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7554     
7555     const IntegerType *Ty = cast<IntegerType>(I.getType());
7556     
7557     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7558     if (I.getOpcode() == ShiftOp->getOpcode()) {
7559       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7560       // saturates.
7561       if (AmtSum >= TypeBits) {
7562         if (I.getOpcode() != Instruction::AShr)
7563           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7564         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7565       }
7566       
7567       return BinaryOperator::Create(I.getOpcode(), X,
7568                                     ConstantInt::get(Ty, AmtSum));
7569     }
7570     
7571     if (ShiftOp->getOpcode() == Instruction::LShr &&
7572         I.getOpcode() == Instruction::AShr) {
7573       if (AmtSum >= TypeBits)
7574         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7575       
7576       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7577       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7578     }
7579     
7580     if (ShiftOp->getOpcode() == Instruction::AShr &&
7581         I.getOpcode() == Instruction::LShr) {
7582       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7583       if (AmtSum >= TypeBits)
7584         AmtSum = TypeBits-1;
7585       
7586       Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7587
7588       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7589       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7590     }
7591     
7592     // Okay, if we get here, one shift must be left, and the other shift must be
7593     // right.  See if the amounts are equal.
7594     if (ShiftAmt1 == ShiftAmt2) {
7595       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7596       if (I.getOpcode() == Instruction::Shl) {
7597         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7598         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7599       }
7600       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7601       if (I.getOpcode() == Instruction::LShr) {
7602         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7603         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7604       }
7605       // We can simplify ((X << C) >>s C) into a trunc + sext.
7606       // NOTE: we could do this for any C, but that would make 'unusual' integer
7607       // types.  For now, just stick to ones well-supported by the code
7608       // generators.
7609       const Type *SExtType = 0;
7610       switch (Ty->getBitWidth() - ShiftAmt1) {
7611       case 1  :
7612       case 8  :
7613       case 16 :
7614       case 32 :
7615       case 64 :
7616       case 128:
7617         SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
7618         break;
7619       default: break;
7620       }
7621       if (SExtType)
7622         return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
7623       // Otherwise, we can't handle it yet.
7624     } else if (ShiftAmt1 < ShiftAmt2) {
7625       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7626       
7627       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7628       if (I.getOpcode() == Instruction::Shl) {
7629         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7630                ShiftOp->getOpcode() == Instruction::AShr);
7631         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7632         
7633         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7634         return BinaryOperator::CreateAnd(Shift,
7635                                          ConstantInt::get(*Context, Mask));
7636       }
7637       
7638       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7639       if (I.getOpcode() == Instruction::LShr) {
7640         assert(ShiftOp->getOpcode() == Instruction::Shl);
7641         Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7642         
7643         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7644         return BinaryOperator::CreateAnd(Shift,
7645                                          ConstantInt::get(*Context, Mask));
7646       }
7647       
7648       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7649     } else {
7650       assert(ShiftAmt2 < ShiftAmt1);
7651       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7652
7653       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7654       if (I.getOpcode() == Instruction::Shl) {
7655         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7656                ShiftOp->getOpcode() == Instruction::AShr);
7657         Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7658                                             ConstantInt::get(Ty, ShiftDiff));
7659         
7660         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7661         return BinaryOperator::CreateAnd(Shift,
7662                                          ConstantInt::get(*Context, Mask));
7663       }
7664       
7665       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7666       if (I.getOpcode() == Instruction::LShr) {
7667         assert(ShiftOp->getOpcode() == Instruction::Shl);
7668         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7669         
7670         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7671         return BinaryOperator::CreateAnd(Shift,
7672                                          ConstantInt::get(*Context, Mask));
7673       }
7674       
7675       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7676     }
7677   }
7678   return 0;
7679 }
7680
7681
7682 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7683 /// expression.  If so, decompose it, returning some value X, such that Val is
7684 /// X*Scale+Offset.
7685 ///
7686 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7687                                         int &Offset, LLVMContext *Context) {
7688   assert(Val->getType() == Type::getInt32Ty(*Context) && 
7689          "Unexpected allocation size type!");
7690   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7691     Offset = CI->getZExtValue();
7692     Scale  = 0;
7693     return ConstantInt::get(Type::getInt32Ty(*Context), 0);
7694   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7695     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7696       if (I->getOpcode() == Instruction::Shl) {
7697         // This is a value scaled by '1 << the shift amt'.
7698         Scale = 1U << RHS->getZExtValue();
7699         Offset = 0;
7700         return I->getOperand(0);
7701       } else if (I->getOpcode() == Instruction::Mul) {
7702         // This value is scaled by 'RHS'.
7703         Scale = RHS->getZExtValue();
7704         Offset = 0;
7705         return I->getOperand(0);
7706       } else if (I->getOpcode() == Instruction::Add) {
7707         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7708         // where C1 is divisible by C2.
7709         unsigned SubScale;
7710         Value *SubVal = 
7711           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7712                                     Offset, Context);
7713         Offset += RHS->getZExtValue();
7714         Scale = SubScale;
7715         return SubVal;
7716       }
7717     }
7718   }
7719
7720   // Otherwise, we can't look past this.
7721   Scale = 1;
7722   Offset = 0;
7723   return Val;
7724 }
7725
7726
7727 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7728 /// try to eliminate the cast by moving the type information into the alloc.
7729 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7730                                                    AllocationInst &AI) {
7731   const PointerType *PTy = cast<PointerType>(CI.getType());
7732   
7733   BuilderTy AllocaBuilder(*Builder);
7734   AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7735   
7736   // Remove any uses of AI that are dead.
7737   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7738   
7739   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7740     Instruction *User = cast<Instruction>(*UI++);
7741     if (isInstructionTriviallyDead(User)) {
7742       while (UI != E && *UI == User)
7743         ++UI; // If this instruction uses AI more than once, don't break UI.
7744       
7745       ++NumDeadInst;
7746       DEBUG(errs() << "IC: DCE: " << *User << '\n');
7747       EraseInstFromFunction(*User);
7748     }
7749   }
7750
7751   // This requires TargetData to get the alloca alignment and size information.
7752   if (!TD) return 0;
7753
7754   // Get the type really allocated and the type casted to.
7755   const Type *AllocElTy = AI.getAllocatedType();
7756   const Type *CastElTy = PTy->getElementType();
7757   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7758
7759   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7760   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7761   if (CastElTyAlign < AllocElTyAlign) return 0;
7762
7763   // If the allocation has multiple uses, only promote it if we are strictly
7764   // increasing the alignment of the resultant allocation.  If we keep it the
7765   // same, we open the door to infinite loops of various kinds.  (A reference
7766   // from a dbg.declare doesn't count as a use for this purpose.)
7767   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7768       CastElTyAlign == AllocElTyAlign) return 0;
7769
7770   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7771   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7772   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7773
7774   // See if we can satisfy the modulus by pulling a scale out of the array
7775   // size argument.
7776   unsigned ArraySizeScale;
7777   int ArrayOffset;
7778   Value *NumElements = // See if the array size is a decomposable linear expr.
7779     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7780                               ArrayOffset, Context);
7781  
7782   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7783   // do the xform.
7784   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7785       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7786
7787   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7788   Value *Amt = 0;
7789   if (Scale == 1) {
7790     Amt = NumElements;
7791   } else {
7792     Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
7793     // Insert before the alloca, not before the cast.
7794     Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
7795   }
7796   
7797   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7798     Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
7799     Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
7800   }
7801   
7802   AllocationInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7803   New->setAlignment(AI.getAlignment());
7804   New->takeName(&AI);
7805   
7806   // If the allocation has one real use plus a dbg.declare, just remove the
7807   // declare.
7808   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7809     EraseInstFromFunction(*DI);
7810   }
7811   // If the allocation has multiple real uses, insert a cast and change all
7812   // things that used it to use the new cast.  This will also hack on CI, but it
7813   // will die soon.
7814   else if (!AI.hasOneUse()) {
7815     // New is the allocation instruction, pointer typed. AI is the original
7816     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7817     Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
7818     AI.replaceAllUsesWith(NewCast);
7819   }
7820   return ReplaceInstUsesWith(CI, New);
7821 }
7822
7823 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7824 /// and return it as type Ty without inserting any new casts and without
7825 /// changing the computed value.  This is used by code that tries to decide
7826 /// whether promoting or shrinking integer operations to wider or smaller types
7827 /// will allow us to eliminate a truncate or extend.
7828 ///
7829 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7830 /// extension operation if Ty is larger.
7831 ///
7832 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7833 /// should return true if trunc(V) can be computed by computing V in the smaller
7834 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7835 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7836 /// efficiently truncated.
7837 ///
7838 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7839 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7840 /// the final result.
7841 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7842                                               unsigned CastOpc,
7843                                               int &NumCastsRemoved){
7844   // We can always evaluate constants in another type.
7845   if (isa<Constant>(V))
7846     return true;
7847   
7848   Instruction *I = dyn_cast<Instruction>(V);
7849   if (!I) return false;
7850   
7851   const Type *OrigTy = V->getType();
7852   
7853   // If this is an extension or truncate, we can often eliminate it.
7854   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7855     // If this is a cast from the destination type, we can trivially eliminate
7856     // it, and this will remove a cast overall.
7857     if (I->getOperand(0)->getType() == Ty) {
7858       // If the first operand is itself a cast, and is eliminable, do not count
7859       // this as an eliminable cast.  We would prefer to eliminate those two
7860       // casts first.
7861       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7862         ++NumCastsRemoved;
7863       return true;
7864     }
7865   }
7866
7867   // We can't extend or shrink something that has multiple uses: doing so would
7868   // require duplicating the instruction in general, which isn't profitable.
7869   if (!I->hasOneUse()) return false;
7870
7871   unsigned Opc = I->getOpcode();
7872   switch (Opc) {
7873   case Instruction::Add:
7874   case Instruction::Sub:
7875   case Instruction::Mul:
7876   case Instruction::And:
7877   case Instruction::Or:
7878   case Instruction::Xor:
7879     // These operators can all arbitrarily be extended or truncated.
7880     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7881                                       NumCastsRemoved) &&
7882            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7883                                       NumCastsRemoved);
7884
7885   case Instruction::UDiv:
7886   case Instruction::URem: {
7887     // UDiv and URem can be truncated if all the truncated bits are zero.
7888     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7889     uint32_t BitWidth = Ty->getScalarSizeInBits();
7890     if (BitWidth < OrigBitWidth) {
7891       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7892       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7893           MaskedValueIsZero(I->getOperand(1), Mask)) {
7894         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7895                                           NumCastsRemoved) &&
7896                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7897                                           NumCastsRemoved);
7898       }
7899     }
7900     break;
7901   }
7902   case Instruction::Shl:
7903     // If we are truncating the result of this SHL, and if it's a shift of a
7904     // constant amount, we can always perform a SHL in a smaller type.
7905     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7906       uint32_t BitWidth = Ty->getScalarSizeInBits();
7907       if (BitWidth < OrigTy->getScalarSizeInBits() &&
7908           CI->getLimitedValue(BitWidth) < BitWidth)
7909         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7910                                           NumCastsRemoved);
7911     }
7912     break;
7913   case Instruction::LShr:
7914     // If this is a truncate of a logical shr, we can truncate it to a smaller
7915     // lshr iff we know that the bits we would otherwise be shifting in are
7916     // already zeros.
7917     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7918       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7919       uint32_t BitWidth = Ty->getScalarSizeInBits();
7920       if (BitWidth < OrigBitWidth &&
7921           MaskedValueIsZero(I->getOperand(0),
7922             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7923           CI->getLimitedValue(BitWidth) < BitWidth) {
7924         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7925                                           NumCastsRemoved);
7926       }
7927     }
7928     break;
7929   case Instruction::ZExt:
7930   case Instruction::SExt:
7931   case Instruction::Trunc:
7932     // If this is the same kind of case as our original (e.g. zext+zext), we
7933     // can safely replace it.  Note that replacing it does not reduce the number
7934     // of casts in the input.
7935     if (Opc == CastOpc)
7936       return true;
7937
7938     // sext (zext ty1), ty2 -> zext ty2
7939     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7940       return true;
7941     break;
7942   case Instruction::Select: {
7943     SelectInst *SI = cast<SelectInst>(I);
7944     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7945                                       NumCastsRemoved) &&
7946            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7947                                       NumCastsRemoved);
7948   }
7949   case Instruction::PHI: {
7950     // We can change a phi if we can change all operands.
7951     PHINode *PN = cast<PHINode>(I);
7952     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7953       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7954                                       NumCastsRemoved))
7955         return false;
7956     return true;
7957   }
7958   default:
7959     // TODO: Can handle more cases here.
7960     break;
7961   }
7962   
7963   return false;
7964 }
7965
7966 /// EvaluateInDifferentType - Given an expression that 
7967 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7968 /// evaluate the expression.
7969 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7970                                              bool isSigned) {
7971   if (Constant *C = dyn_cast<Constant>(V))
7972     return ConstantExpr::getIntegerCast(C, Ty,
7973                                                isSigned /*Sext or ZExt*/);
7974
7975   // Otherwise, it must be an instruction.
7976   Instruction *I = cast<Instruction>(V);
7977   Instruction *Res = 0;
7978   unsigned Opc = I->getOpcode();
7979   switch (Opc) {
7980   case Instruction::Add:
7981   case Instruction::Sub:
7982   case Instruction::Mul:
7983   case Instruction::And:
7984   case Instruction::Or:
7985   case Instruction::Xor:
7986   case Instruction::AShr:
7987   case Instruction::LShr:
7988   case Instruction::Shl:
7989   case Instruction::UDiv:
7990   case Instruction::URem: {
7991     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7992     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7993     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7994     break;
7995   }    
7996   case Instruction::Trunc:
7997   case Instruction::ZExt:
7998   case Instruction::SExt:
7999     // If the source type of the cast is the type we're trying for then we can
8000     // just return the source.  There's no need to insert it because it is not
8001     // new.
8002     if (I->getOperand(0)->getType() == Ty)
8003       return I->getOperand(0);
8004     
8005     // Otherwise, must be the same type of cast, so just reinsert a new one.
8006     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8007                            Ty);
8008     break;
8009   case Instruction::Select: {
8010     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8011     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8012     Res = SelectInst::Create(I->getOperand(0), True, False);
8013     break;
8014   }
8015   case Instruction::PHI: {
8016     PHINode *OPN = cast<PHINode>(I);
8017     PHINode *NPN = PHINode::Create(Ty);
8018     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8019       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8020       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8021     }
8022     Res = NPN;
8023     break;
8024   }
8025   default: 
8026     // TODO: Can handle more cases here.
8027     llvm_unreachable("Unreachable!");
8028     break;
8029   }
8030   
8031   Res->takeName(I);
8032   return InsertNewInstBefore(Res, *I);
8033 }
8034
8035 /// @brief Implement the transforms common to all CastInst visitors.
8036 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8037   Value *Src = CI.getOperand(0);
8038
8039   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8040   // eliminate it now.
8041   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8042     if (Instruction::CastOps opc = 
8043         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8044       // The first cast (CSrc) is eliminable so we need to fix up or replace
8045       // the second cast (CI). CSrc will then have a good chance of being dead.
8046       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8047     }
8048   }
8049
8050   // If we are casting a select then fold the cast into the select
8051   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8052     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8053       return NV;
8054
8055   // If we are casting a PHI then fold the cast into the PHI
8056   if (isa<PHINode>(Src))
8057     if (Instruction *NV = FoldOpIntoPhi(CI))
8058       return NV;
8059   
8060   return 0;
8061 }
8062
8063 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8064 /// or not there is a sequence of GEP indices into the type that will land us at
8065 /// the specified offset.  If so, fill them into NewIndices and return the
8066 /// resultant element type, otherwise return null.
8067 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8068                                        SmallVectorImpl<Value*> &NewIndices,
8069                                        const TargetData *TD,
8070                                        LLVMContext *Context) {
8071   if (!TD) return 0;
8072   if (!Ty->isSized()) return 0;
8073   
8074   // Start with the index over the outer type.  Note that the type size
8075   // might be zero (even if the offset isn't zero) if the indexed type
8076   // is something like [0 x {int, int}]
8077   const Type *IntPtrTy = TD->getIntPtrType(*Context);
8078   int64_t FirstIdx = 0;
8079   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8080     FirstIdx = Offset/TySize;
8081     Offset -= FirstIdx*TySize;
8082     
8083     // Handle hosts where % returns negative instead of values [0..TySize).
8084     if (Offset < 0) {
8085       --FirstIdx;
8086       Offset += TySize;
8087       assert(Offset >= 0);
8088     }
8089     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8090   }
8091   
8092   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8093     
8094   // Index into the types.  If we fail, set OrigBase to null.
8095   while (Offset) {
8096     // Indexing into tail padding between struct/array elements.
8097     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8098       return 0;
8099     
8100     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8101       const StructLayout *SL = TD->getStructLayout(STy);
8102       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8103              "Offset must stay within the indexed type");
8104       
8105       unsigned Elt = SL->getElementContainingOffset(Offset);
8106       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8107       
8108       Offset -= SL->getElementOffset(Elt);
8109       Ty = STy->getElementType(Elt);
8110     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8111       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8112       assert(EltSize && "Cannot index into a zero-sized array");
8113       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8114       Offset %= EltSize;
8115       Ty = AT->getElementType();
8116     } else {
8117       // Otherwise, we can't index into the middle of this atomic type, bail.
8118       return 0;
8119     }
8120   }
8121   
8122   return Ty;
8123 }
8124
8125 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8126 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8127   Value *Src = CI.getOperand(0);
8128   
8129   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8130     // If casting the result of a getelementptr instruction with no offset, turn
8131     // this into a cast of the original pointer!
8132     if (GEP->hasAllZeroIndices()) {
8133       // Changing the cast operand is usually not a good idea but it is safe
8134       // here because the pointer operand is being replaced with another 
8135       // pointer operand so the opcode doesn't need to change.
8136       Worklist.Add(GEP);
8137       CI.setOperand(0, GEP->getOperand(0));
8138       return &CI;
8139     }
8140     
8141     // If the GEP has a single use, and the base pointer is a bitcast, and the
8142     // GEP computes a constant offset, see if we can convert these three
8143     // instructions into fewer.  This typically happens with unions and other
8144     // non-type-safe code.
8145     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8146       if (GEP->hasAllConstantIndices()) {
8147         // We are guaranteed to get a constant from EmitGEPOffset.
8148         ConstantInt *OffsetV =
8149                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8150         int64_t Offset = OffsetV->getSExtValue();
8151         
8152         // Get the base pointer input of the bitcast, and the type it points to.
8153         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8154         const Type *GEPIdxTy =
8155           cast<PointerType>(OrigBase->getType())->getElementType();
8156         SmallVector<Value*, 8> NewIndices;
8157         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8158           // If we were able to index down into an element, create the GEP
8159           // and bitcast the result.  This eliminates one bitcast, potentially
8160           // two.
8161           Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8162             Builder->CreateInBoundsGEP(OrigBase,
8163                                        NewIndices.begin(), NewIndices.end()) :
8164             Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
8165           NGEP->takeName(GEP);
8166           
8167           if (isa<BitCastInst>(CI))
8168             return new BitCastInst(NGEP, CI.getType());
8169           assert(isa<PtrToIntInst>(CI));
8170           return new PtrToIntInst(NGEP, CI.getType());
8171         }
8172       }      
8173     }
8174   }
8175     
8176   return commonCastTransforms(CI);
8177 }
8178
8179 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8180 /// type like i42.  We don't want to introduce operations on random non-legal
8181 /// integer types where they don't already exist in the code.  In the future,
8182 /// we should consider making this based off target-data, so that 32-bit targets
8183 /// won't get i64 operations etc.
8184 static bool isSafeIntegerType(const Type *Ty) {
8185   switch (Ty->getPrimitiveSizeInBits()) {
8186   case 8:
8187   case 16:
8188   case 32:
8189   case 64:
8190     return true;
8191   default: 
8192     return false;
8193   }
8194 }
8195
8196 /// commonIntCastTransforms - This function implements the common transforms
8197 /// for trunc, zext, and sext.
8198 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8199   if (Instruction *Result = commonCastTransforms(CI))
8200     return Result;
8201
8202   Value *Src = CI.getOperand(0);
8203   const Type *SrcTy = Src->getType();
8204   const Type *DestTy = CI.getType();
8205   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8206   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8207
8208   // See if we can simplify any instructions used by the LHS whose sole 
8209   // purpose is to compute bits we don't care about.
8210   if (SimplifyDemandedInstructionBits(CI))
8211     return &CI;
8212
8213   // If the source isn't an instruction or has more than one use then we
8214   // can't do anything more. 
8215   Instruction *SrcI = dyn_cast<Instruction>(Src);
8216   if (!SrcI || !Src->hasOneUse())
8217     return 0;
8218
8219   // Attempt to propagate the cast into the instruction for int->int casts.
8220   int NumCastsRemoved = 0;
8221   // Only do this if the dest type is a simple type, don't convert the
8222   // expression tree to something weird like i93 unless the source is also
8223   // strange.
8224   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8225        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8226       CanEvaluateInDifferentType(SrcI, DestTy,
8227                                  CI.getOpcode(), NumCastsRemoved)) {
8228     // If this cast is a truncate, evaluting in a different type always
8229     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8230     // we need to do an AND to maintain the clear top-part of the computation,
8231     // so we require that the input have eliminated at least one cast.  If this
8232     // is a sign extension, we insert two new casts (to do the extension) so we
8233     // require that two casts have been eliminated.
8234     bool DoXForm = false;
8235     bool JustReplace = false;
8236     switch (CI.getOpcode()) {
8237     default:
8238       // All the others use floating point so we shouldn't actually 
8239       // get here because of the check above.
8240       llvm_unreachable("Unknown cast type");
8241     case Instruction::Trunc:
8242       DoXForm = true;
8243       break;
8244     case Instruction::ZExt: {
8245       DoXForm = NumCastsRemoved >= 1;
8246       if (!DoXForm && 0) {
8247         // If it's unnecessary to issue an AND to clear the high bits, it's
8248         // always profitable to do this xform.
8249         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8250         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8251         if (MaskedValueIsZero(TryRes, Mask))
8252           return ReplaceInstUsesWith(CI, TryRes);
8253         
8254         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8255           if (TryI->use_empty())
8256             EraseInstFromFunction(*TryI);
8257       }
8258       break;
8259     }
8260     case Instruction::SExt: {
8261       DoXForm = NumCastsRemoved >= 2;
8262       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8263         // If we do not have to emit the truncate + sext pair, then it's always
8264         // profitable to do this xform.
8265         //
8266         // It's not safe to eliminate the trunc + sext pair if one of the
8267         // eliminated cast is a truncate. e.g.
8268         // t2 = trunc i32 t1 to i16
8269         // t3 = sext i16 t2 to i32
8270         // !=
8271         // i32 t1
8272         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8273         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8274         if (NumSignBits > (DestBitSize - SrcBitSize))
8275           return ReplaceInstUsesWith(CI, TryRes);
8276         
8277         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8278           if (TryI->use_empty())
8279             EraseInstFromFunction(*TryI);
8280       }
8281       break;
8282     }
8283     }
8284     
8285     if (DoXForm) {
8286       DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8287             " to avoid cast: " << CI);
8288       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8289                                            CI.getOpcode() == Instruction::SExt);
8290       if (JustReplace)
8291         // Just replace this cast with the result.
8292         return ReplaceInstUsesWith(CI, Res);
8293
8294       assert(Res->getType() == DestTy);
8295       switch (CI.getOpcode()) {
8296       default: llvm_unreachable("Unknown cast type!");
8297       case Instruction::Trunc:
8298         // Just replace this cast with the result.
8299         return ReplaceInstUsesWith(CI, Res);
8300       case Instruction::ZExt: {
8301         assert(SrcBitSize < DestBitSize && "Not a zext?");
8302
8303         // If the high bits are already zero, just replace this cast with the
8304         // result.
8305         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8306         if (MaskedValueIsZero(Res, Mask))
8307           return ReplaceInstUsesWith(CI, Res);
8308
8309         // We need to emit an AND to clear the high bits.
8310         Constant *C = ConstantInt::get(*Context, 
8311                                  APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8312         return BinaryOperator::CreateAnd(Res, C);
8313       }
8314       case Instruction::SExt: {
8315         // If the high bits are already filled with sign bit, just replace this
8316         // cast with the result.
8317         unsigned NumSignBits = ComputeNumSignBits(Res);
8318         if (NumSignBits > (DestBitSize - SrcBitSize))
8319           return ReplaceInstUsesWith(CI, Res);
8320
8321         // We need to emit a cast to truncate, then a cast to sext.
8322         return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
8323       }
8324       }
8325     }
8326   }
8327   
8328   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8329   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8330
8331   switch (SrcI->getOpcode()) {
8332   case Instruction::Add:
8333   case Instruction::Mul:
8334   case Instruction::And:
8335   case Instruction::Or:
8336   case Instruction::Xor:
8337     // If we are discarding information, rewrite.
8338     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8339       // Don't insert two casts unless at least one can be eliminated.
8340       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8341           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8342         Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8343         Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8344         return BinaryOperator::Create(
8345             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8346       }
8347     }
8348
8349     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8350     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8351         SrcI->getOpcode() == Instruction::Xor &&
8352         Op1 == ConstantInt::getTrue(*Context) &&
8353         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8354       Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
8355       return BinaryOperator::CreateXor(New,
8356                                       ConstantInt::get(CI.getType(), 1));
8357     }
8358     break;
8359
8360   case Instruction::Shl: {
8361     // Canonicalize trunc inside shl, if we can.
8362     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8363     if (CI && DestBitSize < SrcBitSize &&
8364         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8365       Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8366       Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8367       return BinaryOperator::CreateShl(Op0c, Op1c);
8368     }
8369     break;
8370   }
8371   }
8372   return 0;
8373 }
8374
8375 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8376   if (Instruction *Result = commonIntCastTransforms(CI))
8377     return Result;
8378   
8379   Value *Src = CI.getOperand(0);
8380   const Type *Ty = CI.getType();
8381   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8382   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8383
8384   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8385   if (DestBitWidth == 1) {
8386     Constant *One = ConstantInt::get(Src->getType(), 1);
8387     Src = Builder->CreateAnd(Src, One, "tmp");
8388     Value *Zero = Constant::getNullValue(Src->getType());
8389     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8390   }
8391
8392   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8393   ConstantInt *ShAmtV = 0;
8394   Value *ShiftOp = 0;
8395   if (Src->hasOneUse() &&
8396       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8397     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8398     
8399     // Get a mask for the bits shifting in.
8400     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8401     if (MaskedValueIsZero(ShiftOp, Mask)) {
8402       if (ShAmt >= DestBitWidth)        // All zeros.
8403         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8404       
8405       // Okay, we can shrink this.  Truncate the input, then return a new
8406       // shift.
8407       Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
8408       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8409       return BinaryOperator::CreateLShr(V1, V2);
8410     }
8411   }
8412   
8413   return 0;
8414 }
8415
8416 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8417 /// in order to eliminate the icmp.
8418 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8419                                              bool DoXform) {
8420   // If we are just checking for a icmp eq of a single bit and zext'ing it
8421   // to an integer, then shift the bit to the appropriate place and then
8422   // cast to integer to avoid the comparison.
8423   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8424     const APInt &Op1CV = Op1C->getValue();
8425       
8426     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8427     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8428     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8429         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8430       if (!DoXform) return ICI;
8431
8432       Value *In = ICI->getOperand(0);
8433       Value *Sh = ConstantInt::get(In->getType(),
8434                                    In->getType()->getScalarSizeInBits()-1);
8435       In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
8436       if (In->getType() != CI.getType())
8437         In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
8438
8439       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8440         Constant *One = ConstantInt::get(In->getType(), 1);
8441         In = Builder->CreateXor(In, One, In->getName()+".not");
8442       }
8443
8444       return ReplaceInstUsesWith(CI, In);
8445     }
8446       
8447       
8448       
8449     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8450     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8451     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8452     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8453     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8454     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8455     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8456     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8457     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8458         // This only works for EQ and NE
8459         ICI->isEquality()) {
8460       // If Op1C some other power of two, convert:
8461       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8462       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8463       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8464       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8465         
8466       APInt KnownZeroMask(~KnownZero);
8467       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8468         if (!DoXform) return ICI;
8469
8470         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8471         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8472           // (X&4) == 2 --> false
8473           // (X&4) != 2 --> true
8474           Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8475           Res = ConstantExpr::getZExt(Res, CI.getType());
8476           return ReplaceInstUsesWith(CI, Res);
8477         }
8478           
8479         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8480         Value *In = ICI->getOperand(0);
8481         if (ShiftAmt) {
8482           // Perform a logical shr by shiftamt.
8483           // Insert the shift to put the result in the low bit.
8484           In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8485                                    In->getName()+".lobit");
8486         }
8487           
8488         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8489           Constant *One = ConstantInt::get(In->getType(), 1);
8490           In = Builder->CreateXor(In, One, "tmp");
8491         }
8492           
8493         if (CI.getType() == In->getType())
8494           return ReplaceInstUsesWith(CI, In);
8495         else
8496           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8497       }
8498     }
8499   }
8500
8501   return 0;
8502 }
8503
8504 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8505   // If one of the common conversion will work ..
8506   if (Instruction *Result = commonIntCastTransforms(CI))
8507     return Result;
8508
8509   Value *Src = CI.getOperand(0);
8510
8511   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8512   // types and if the sizes are just right we can convert this into a logical
8513   // 'and' which will be much cheaper than the pair of casts.
8514   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8515     // Get the sizes of the types involved.  We know that the intermediate type
8516     // will be smaller than A or C, but don't know the relation between A and C.
8517     Value *A = CSrc->getOperand(0);
8518     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8519     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8520     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8521     // If we're actually extending zero bits, then if
8522     // SrcSize <  DstSize: zext(a & mask)
8523     // SrcSize == DstSize: a & mask
8524     // SrcSize  > DstSize: trunc(a) & mask
8525     if (SrcSize < DstSize) {
8526       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8527       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8528       Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
8529       return new ZExtInst(And, CI.getType());
8530     }
8531     
8532     if (SrcSize == DstSize) {
8533       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8534       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8535                                                            AndValue));
8536     }
8537     if (SrcSize > DstSize) {
8538       Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
8539       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8540       return BinaryOperator::CreateAnd(Trunc, 
8541                                        ConstantInt::get(Trunc->getType(),
8542                                                                AndValue));
8543     }
8544   }
8545
8546   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8547     return transformZExtICmp(ICI, CI);
8548
8549   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8550   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8551     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8552     // of the (zext icmp) will be transformed.
8553     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8554     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8555     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8556         (transformZExtICmp(LHS, CI, false) ||
8557          transformZExtICmp(RHS, CI, false))) {
8558       Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8559       Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
8560       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8561     }
8562   }
8563
8564   // zext(trunc(t) & C) -> (t & zext(C)).
8565   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8566     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8567       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8568         Value *TI0 = TI->getOperand(0);
8569         if (TI0->getType() == CI.getType())
8570           return
8571             BinaryOperator::CreateAnd(TI0,
8572                                 ConstantExpr::getZExt(C, CI.getType()));
8573       }
8574
8575   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8576   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8577     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8578       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8579         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8580             And->getOperand(1) == C)
8581           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8582             Value *TI0 = TI->getOperand(0);
8583             if (TI0->getType() == CI.getType()) {
8584               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8585               Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
8586               return BinaryOperator::CreateXor(NewAnd, ZC);
8587             }
8588           }
8589
8590   return 0;
8591 }
8592
8593 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8594   if (Instruction *I = commonIntCastTransforms(CI))
8595     return I;
8596   
8597   Value *Src = CI.getOperand(0);
8598   
8599   // Canonicalize sign-extend from i1 to a select.
8600   if (Src->getType() == Type::getInt1Ty(*Context))
8601     return SelectInst::Create(Src,
8602                               Constant::getAllOnesValue(CI.getType()),
8603                               Constant::getNullValue(CI.getType()));
8604
8605   // See if the value being truncated is already sign extended.  If so, just
8606   // eliminate the trunc/sext pair.
8607   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8608     Value *Op = cast<User>(Src)->getOperand(0);
8609     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8610     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8611     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8612     unsigned NumSignBits = ComputeNumSignBits(Op);
8613
8614     if (OpBits == DestBits) {
8615       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8616       // bits, it is already ready.
8617       if (NumSignBits > DestBits-MidBits)
8618         return ReplaceInstUsesWith(CI, Op);
8619     } else if (OpBits < DestBits) {
8620       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8621       // bits, just sext from i32.
8622       if (NumSignBits > OpBits-MidBits)
8623         return new SExtInst(Op, CI.getType(), "tmp");
8624     } else {
8625       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8626       // bits, just truncate to i32.
8627       if (NumSignBits > OpBits-MidBits)
8628         return new TruncInst(Op, CI.getType(), "tmp");
8629     }
8630   }
8631
8632   // If the input is a shl/ashr pair of a same constant, then this is a sign
8633   // extension from a smaller value.  If we could trust arbitrary bitwidth
8634   // integers, we could turn this into a truncate to the smaller bit and then
8635   // use a sext for the whole extension.  Since we don't, look deeper and check
8636   // for a truncate.  If the source and dest are the same type, eliminate the
8637   // trunc and extend and just do shifts.  For example, turn:
8638   //   %a = trunc i32 %i to i8
8639   //   %b = shl i8 %a, 6
8640   //   %c = ashr i8 %b, 6
8641   //   %d = sext i8 %c to i32
8642   // into:
8643   //   %a = shl i32 %i, 30
8644   //   %d = ashr i32 %a, 30
8645   Value *A = 0;
8646   ConstantInt *BA = 0, *CA = 0;
8647   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8648                         m_ConstantInt(CA))) &&
8649       BA == CA && isa<TruncInst>(A)) {
8650     Value *I = cast<TruncInst>(A)->getOperand(0);
8651     if (I->getType() == CI.getType()) {
8652       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8653       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8654       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8655       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8656       I = Builder->CreateShl(I, ShAmtV, CI.getName());
8657       return BinaryOperator::CreateAShr(I, ShAmtV);
8658     }
8659   }
8660   
8661   return 0;
8662 }
8663
8664 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8665 /// in the specified FP type without changing its value.
8666 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8667                               LLVMContext *Context) {
8668   bool losesInfo;
8669   APFloat F = CFP->getValueAPF();
8670   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8671   if (!losesInfo)
8672     return ConstantFP::get(*Context, F);
8673   return 0;
8674 }
8675
8676 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8677 /// through it until we get the source value.
8678 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8679   if (Instruction *I = dyn_cast<Instruction>(V))
8680     if (I->getOpcode() == Instruction::FPExt)
8681       return LookThroughFPExtensions(I->getOperand(0), Context);
8682   
8683   // If this value is a constant, return the constant in the smallest FP type
8684   // that can accurately represent it.  This allows us to turn
8685   // (float)((double)X+2.0) into x+2.0f.
8686   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8687     if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
8688       return V;  // No constant folding of this.
8689     // See if the value can be truncated to float and then reextended.
8690     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8691       return V;
8692     if (CFP->getType() == Type::getDoubleTy(*Context))
8693       return V;  // Won't shrink.
8694     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8695       return V;
8696     // Don't try to shrink to various long double types.
8697   }
8698   
8699   return V;
8700 }
8701
8702 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8703   if (Instruction *I = commonCastTransforms(CI))
8704     return I;
8705   
8706   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8707   // smaller than the destination type, we can eliminate the truncate by doing
8708   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8709   // many builtins (sqrt, etc).
8710   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8711   if (OpI && OpI->hasOneUse()) {
8712     switch (OpI->getOpcode()) {
8713     default: break;
8714     case Instruction::FAdd:
8715     case Instruction::FSub:
8716     case Instruction::FMul:
8717     case Instruction::FDiv:
8718     case Instruction::FRem:
8719       const Type *SrcTy = OpI->getType();
8720       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8721       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8722       if (LHSTrunc->getType() != SrcTy && 
8723           RHSTrunc->getType() != SrcTy) {
8724         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8725         // If the source types were both smaller than the destination type of
8726         // the cast, do this xform.
8727         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8728             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8729           LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8730           RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
8731           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8732         }
8733       }
8734       break;  
8735     }
8736   }
8737   return 0;
8738 }
8739
8740 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8741   return commonCastTransforms(CI);
8742 }
8743
8744 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8745   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8746   if (OpI == 0)
8747     return commonCastTransforms(FI);
8748
8749   // fptoui(uitofp(X)) --> X
8750   // fptoui(sitofp(X)) --> X
8751   // This is safe if the intermediate type has enough bits in its mantissa to
8752   // accurately represent all values of X.  For example, do not do this with
8753   // i64->float->i64.  This is also safe for sitofp case, because any negative
8754   // 'X' value would cause an undefined result for the fptoui. 
8755   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8756       OpI->getOperand(0)->getType() == FI.getType() &&
8757       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8758                     OpI->getType()->getFPMantissaWidth())
8759     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8760
8761   return commonCastTransforms(FI);
8762 }
8763
8764 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8765   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8766   if (OpI == 0)
8767     return commonCastTransforms(FI);
8768   
8769   // fptosi(sitofp(X)) --> X
8770   // fptosi(uitofp(X)) --> X
8771   // This is safe if the intermediate type has enough bits in its mantissa to
8772   // accurately represent all values of X.  For example, do not do this with
8773   // i64->float->i64.  This is also safe for sitofp case, because any negative
8774   // 'X' value would cause an undefined result for the fptoui. 
8775   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8776       OpI->getOperand(0)->getType() == FI.getType() &&
8777       (int)FI.getType()->getScalarSizeInBits() <=
8778                     OpI->getType()->getFPMantissaWidth())
8779     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8780   
8781   return commonCastTransforms(FI);
8782 }
8783
8784 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8785   return commonCastTransforms(CI);
8786 }
8787
8788 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8789   return commonCastTransforms(CI);
8790 }
8791
8792 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8793   // If the destination integer type is smaller than the intptr_t type for
8794   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8795   // trunc to be exposed to other transforms.  Don't do this for extending
8796   // ptrtoint's, because we don't know if the target sign or zero extends its
8797   // pointers.
8798   if (TD &&
8799       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8800     Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8801                                        TD->getIntPtrType(CI.getContext()),
8802                                        "tmp");
8803     return new TruncInst(P, CI.getType());
8804   }
8805   
8806   return commonPointerCastTransforms(CI);
8807 }
8808
8809 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8810   // If the source integer type is larger than the intptr_t type for
8811   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8812   // allows the trunc to be exposed to other transforms.  Don't do this for
8813   // extending inttoptr's, because we don't know if the target sign or zero
8814   // extends to pointers.
8815   if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
8816       TD->getPointerSizeInBits()) {
8817     Value *P = Builder->CreateTrunc(CI.getOperand(0),
8818                                     TD->getIntPtrType(CI.getContext()), "tmp");
8819     return new IntToPtrInst(P, CI.getType());
8820   }
8821   
8822   if (Instruction *I = commonCastTransforms(CI))
8823     return I;
8824
8825   return 0;
8826 }
8827
8828 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8829   // If the operands are integer typed then apply the integer transforms,
8830   // otherwise just apply the common ones.
8831   Value *Src = CI.getOperand(0);
8832   const Type *SrcTy = Src->getType();
8833   const Type *DestTy = CI.getType();
8834
8835   if (isa<PointerType>(SrcTy)) {
8836     if (Instruction *I = commonPointerCastTransforms(CI))
8837       return I;
8838   } else {
8839     if (Instruction *Result = commonCastTransforms(CI))
8840       return Result;
8841   }
8842
8843
8844   // Get rid of casts from one type to the same type. These are useless and can
8845   // be replaced by the operand.
8846   if (DestTy == Src->getType())
8847     return ReplaceInstUsesWith(CI, Src);
8848
8849   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8850     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8851     const Type *DstElTy = DstPTy->getElementType();
8852     const Type *SrcElTy = SrcPTy->getElementType();
8853     
8854     // If the address spaces don't match, don't eliminate the bitcast, which is
8855     // required for changing types.
8856     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8857       return 0;
8858     
8859     // If we are casting a alloca to a pointer to a type of the same
8860     // size, rewrite the allocation instruction to allocate the "right" type.
8861     // There is no need to modify malloc calls because it is their bitcast that
8862     // needs to be cleaned up.
8863     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8864       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8865         return V;
8866     
8867     // If the source and destination are pointers, and this cast is equivalent
8868     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8869     // This can enhance SROA and other transforms that want type-safe pointers.
8870     Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
8871     unsigned NumZeros = 0;
8872     while (SrcElTy != DstElTy && 
8873            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8874            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8875       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8876       ++NumZeros;
8877     }
8878
8879     // If we found a path from the src to dest, create the getelementptr now.
8880     if (SrcElTy == DstElTy) {
8881       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8882       return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8883                                                ((Instruction*) NULL));
8884     }
8885   }
8886
8887   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8888     if (DestVTy->getNumElements() == 1) {
8889       if (!isa<VectorType>(SrcTy)) {
8890         Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
8891         return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
8892                             Constant::getNullValue(Type::getInt32Ty(*Context)));
8893       }
8894       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8895     }
8896   }
8897
8898   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8899     if (SrcVTy->getNumElements() == 1) {
8900       if (!isa<VectorType>(DestTy)) {
8901         Value *Elem = 
8902           Builder->CreateExtractElement(Src,
8903                             Constant::getNullValue(Type::getInt32Ty(*Context)));
8904         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8905       }
8906     }
8907   }
8908
8909   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8910     if (SVI->hasOneUse()) {
8911       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8912       // a bitconvert to a vector with the same # elts.
8913       if (isa<VectorType>(DestTy) && 
8914           cast<VectorType>(DestTy)->getNumElements() ==
8915                 SVI->getType()->getNumElements() &&
8916           SVI->getType()->getNumElements() ==
8917             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8918         CastInst *Tmp;
8919         // If either of the operands is a cast from CI.getType(), then
8920         // evaluating the shuffle in the casted destination's type will allow
8921         // us to eliminate at least one cast.
8922         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8923              Tmp->getOperand(0)->getType() == DestTy) ||
8924             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8925              Tmp->getOperand(0)->getType() == DestTy)) {
8926           Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8927           Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
8928           // Return a new shuffle vector.  Use the same element ID's, as we
8929           // know the vector types match #elts.
8930           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8931         }
8932       }
8933     }
8934   }
8935   return 0;
8936 }
8937
8938 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8939 ///   %C = or %A, %B
8940 ///   %D = select %cond, %C, %A
8941 /// into:
8942 ///   %C = select %cond, %B, 0
8943 ///   %D = or %A, %C
8944 ///
8945 /// Assuming that the specified instruction is an operand to the select, return
8946 /// a bitmask indicating which operands of this instruction are foldable if they
8947 /// equal the other incoming value of the select.
8948 ///
8949 static unsigned GetSelectFoldableOperands(Instruction *I) {
8950   switch (I->getOpcode()) {
8951   case Instruction::Add:
8952   case Instruction::Mul:
8953   case Instruction::And:
8954   case Instruction::Or:
8955   case Instruction::Xor:
8956     return 3;              // Can fold through either operand.
8957   case Instruction::Sub:   // Can only fold on the amount subtracted.
8958   case Instruction::Shl:   // Can only fold on the shift amount.
8959   case Instruction::LShr:
8960   case Instruction::AShr:
8961     return 1;
8962   default:
8963     return 0;              // Cannot fold
8964   }
8965 }
8966
8967 /// GetSelectFoldableConstant - For the same transformation as the previous
8968 /// function, return the identity constant that goes into the select.
8969 static Constant *GetSelectFoldableConstant(Instruction *I,
8970                                            LLVMContext *Context) {
8971   switch (I->getOpcode()) {
8972   default: llvm_unreachable("This cannot happen!");
8973   case Instruction::Add:
8974   case Instruction::Sub:
8975   case Instruction::Or:
8976   case Instruction::Xor:
8977   case Instruction::Shl:
8978   case Instruction::LShr:
8979   case Instruction::AShr:
8980     return Constant::getNullValue(I->getType());
8981   case Instruction::And:
8982     return Constant::getAllOnesValue(I->getType());
8983   case Instruction::Mul:
8984     return ConstantInt::get(I->getType(), 1);
8985   }
8986 }
8987
8988 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8989 /// have the same opcode and only one use each.  Try to simplify this.
8990 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8991                                           Instruction *FI) {
8992   if (TI->getNumOperands() == 1) {
8993     // If this is a non-volatile load or a cast from the same type,
8994     // merge.
8995     if (TI->isCast()) {
8996       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8997         return 0;
8998     } else {
8999       return 0;  // unknown unary op.
9000     }
9001
9002     // Fold this by inserting a select from the input values.
9003     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9004                                           FI->getOperand(0), SI.getName()+".v");
9005     InsertNewInstBefore(NewSI, SI);
9006     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9007                             TI->getType());
9008   }
9009
9010   // Only handle binary operators here.
9011   if (!isa<BinaryOperator>(TI))
9012     return 0;
9013
9014   // Figure out if the operations have any operands in common.
9015   Value *MatchOp, *OtherOpT, *OtherOpF;
9016   bool MatchIsOpZero;
9017   if (TI->getOperand(0) == FI->getOperand(0)) {
9018     MatchOp  = TI->getOperand(0);
9019     OtherOpT = TI->getOperand(1);
9020     OtherOpF = FI->getOperand(1);
9021     MatchIsOpZero = true;
9022   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9023     MatchOp  = TI->getOperand(1);
9024     OtherOpT = TI->getOperand(0);
9025     OtherOpF = FI->getOperand(0);
9026     MatchIsOpZero = false;
9027   } else if (!TI->isCommutative()) {
9028     return 0;
9029   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9030     MatchOp  = TI->getOperand(0);
9031     OtherOpT = TI->getOperand(1);
9032     OtherOpF = FI->getOperand(0);
9033     MatchIsOpZero = true;
9034   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9035     MatchOp  = TI->getOperand(1);
9036     OtherOpT = TI->getOperand(0);
9037     OtherOpF = FI->getOperand(1);
9038     MatchIsOpZero = true;
9039   } else {
9040     return 0;
9041   }
9042
9043   // If we reach here, they do have operations in common.
9044   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9045                                          OtherOpF, SI.getName()+".v");
9046   InsertNewInstBefore(NewSI, SI);
9047
9048   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9049     if (MatchIsOpZero)
9050       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9051     else
9052       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9053   }
9054   llvm_unreachable("Shouldn't get here");
9055   return 0;
9056 }
9057
9058 static bool isSelect01(Constant *C1, Constant *C2) {
9059   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9060   if (!C1I)
9061     return false;
9062   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9063   if (!C2I)
9064     return false;
9065   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9066 }
9067
9068 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9069 /// facilitate further optimization.
9070 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9071                                             Value *FalseVal) {
9072   // See the comment above GetSelectFoldableOperands for a description of the
9073   // transformation we are doing here.
9074   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9075     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9076         !isa<Constant>(FalseVal)) {
9077       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9078         unsigned OpToFold = 0;
9079         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9080           OpToFold = 1;
9081         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9082           OpToFold = 2;
9083         }
9084
9085         if (OpToFold) {
9086           Constant *C = GetSelectFoldableConstant(TVI, Context);
9087           Value *OOp = TVI->getOperand(2-OpToFold);
9088           // Avoid creating select between 2 constants unless it's selecting
9089           // between 0 and 1.
9090           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9091             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9092             InsertNewInstBefore(NewSel, SI);
9093             NewSel->takeName(TVI);
9094             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9095               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9096             llvm_unreachable("Unknown instruction!!");
9097           }
9098         }
9099       }
9100     }
9101   }
9102
9103   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9104     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9105         !isa<Constant>(TrueVal)) {
9106       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9107         unsigned OpToFold = 0;
9108         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9109           OpToFold = 1;
9110         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9111           OpToFold = 2;
9112         }
9113
9114         if (OpToFold) {
9115           Constant *C = GetSelectFoldableConstant(FVI, Context);
9116           Value *OOp = FVI->getOperand(2-OpToFold);
9117           // Avoid creating select between 2 constants unless it's selecting
9118           // between 0 and 1.
9119           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9120             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9121             InsertNewInstBefore(NewSel, SI);
9122             NewSel->takeName(FVI);
9123             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9124               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9125             llvm_unreachable("Unknown instruction!!");
9126           }
9127         }
9128       }
9129     }
9130   }
9131
9132   return 0;
9133 }
9134
9135 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9136 /// ICmpInst as its first operand.
9137 ///
9138 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9139                                                    ICmpInst *ICI) {
9140   bool Changed = false;
9141   ICmpInst::Predicate Pred = ICI->getPredicate();
9142   Value *CmpLHS = ICI->getOperand(0);
9143   Value *CmpRHS = ICI->getOperand(1);
9144   Value *TrueVal = SI.getTrueValue();
9145   Value *FalseVal = SI.getFalseValue();
9146
9147   // Check cases where the comparison is with a constant that
9148   // can be adjusted to fit the min/max idiom. We may edit ICI in
9149   // place here, so make sure the select is the only user.
9150   if (ICI->hasOneUse())
9151     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9152       switch (Pred) {
9153       default: break;
9154       case ICmpInst::ICMP_ULT:
9155       case ICmpInst::ICMP_SLT: {
9156         // X < MIN ? T : F  -->  F
9157         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9158           return ReplaceInstUsesWith(SI, FalseVal);
9159         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9160         Constant *AdjustedRHS = SubOne(CI);
9161         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9162             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9163           Pred = ICmpInst::getSwappedPredicate(Pred);
9164           CmpRHS = AdjustedRHS;
9165           std::swap(FalseVal, TrueVal);
9166           ICI->setPredicate(Pred);
9167           ICI->setOperand(1, CmpRHS);
9168           SI.setOperand(1, TrueVal);
9169           SI.setOperand(2, FalseVal);
9170           Changed = true;
9171         }
9172         break;
9173       }
9174       case ICmpInst::ICMP_UGT:
9175       case ICmpInst::ICMP_SGT: {
9176         // X > MAX ? T : F  -->  F
9177         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9178           return ReplaceInstUsesWith(SI, FalseVal);
9179         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9180         Constant *AdjustedRHS = AddOne(CI);
9181         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9182             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9183           Pred = ICmpInst::getSwappedPredicate(Pred);
9184           CmpRHS = AdjustedRHS;
9185           std::swap(FalseVal, TrueVal);
9186           ICI->setPredicate(Pred);
9187           ICI->setOperand(1, CmpRHS);
9188           SI.setOperand(1, TrueVal);
9189           SI.setOperand(2, FalseVal);
9190           Changed = true;
9191         }
9192         break;
9193       }
9194       }
9195
9196       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9197       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9198       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9199       if (match(TrueVal, m_ConstantInt<-1>()) &&
9200           match(FalseVal, m_ConstantInt<0>()))
9201         Pred = ICI->getPredicate();
9202       else if (match(TrueVal, m_ConstantInt<0>()) &&
9203                match(FalseVal, m_ConstantInt<-1>()))
9204         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9205       
9206       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9207         // If we are just checking for a icmp eq of a single bit and zext'ing it
9208         // to an integer, then shift the bit to the appropriate place and then
9209         // cast to integer to avoid the comparison.
9210         const APInt &Op1CV = CI->getValue();
9211     
9212         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9213         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9214         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9215             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9216           Value *In = ICI->getOperand(0);
9217           Value *Sh = ConstantInt::get(In->getType(),
9218                                        In->getType()->getScalarSizeInBits()-1);
9219           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9220                                                         In->getName()+".lobit"),
9221                                    *ICI);
9222           if (In->getType() != SI.getType())
9223             In = CastInst::CreateIntegerCast(In, SI.getType(),
9224                                              true/*SExt*/, "tmp", ICI);
9225     
9226           if (Pred == ICmpInst::ICMP_SGT)
9227             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9228                                        In->getName()+".not"), *ICI);
9229     
9230           return ReplaceInstUsesWith(SI, In);
9231         }
9232       }
9233     }
9234
9235   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9236     // Transform (X == Y) ? X : Y  -> Y
9237     if (Pred == ICmpInst::ICMP_EQ)
9238       return ReplaceInstUsesWith(SI, FalseVal);
9239     // Transform (X != Y) ? X : Y  -> X
9240     if (Pred == ICmpInst::ICMP_NE)
9241       return ReplaceInstUsesWith(SI, TrueVal);
9242     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9243
9244   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9245     // Transform (X == Y) ? Y : X  -> X
9246     if (Pred == ICmpInst::ICMP_EQ)
9247       return ReplaceInstUsesWith(SI, FalseVal);
9248     // Transform (X != Y) ? Y : X  -> Y
9249     if (Pred == ICmpInst::ICMP_NE)
9250       return ReplaceInstUsesWith(SI, TrueVal);
9251     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9252   }
9253
9254   /// NOTE: if we wanted to, this is where to detect integer ABS
9255
9256   return Changed ? &SI : 0;
9257 }
9258
9259 /// isDefinedInBB - Return true if the value is an instruction defined in the
9260 /// specified basicblock.
9261 static bool isDefinedInBB(const Value *V, const BasicBlock *BB) {
9262   const Instruction *I = dyn_cast<Instruction>(V);
9263   return I != 0 && I->getParent() == BB;
9264 }
9265
9266
9267 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9268   Value *CondVal = SI.getCondition();
9269   Value *TrueVal = SI.getTrueValue();
9270   Value *FalseVal = SI.getFalseValue();
9271
9272   // select true, X, Y  -> X
9273   // select false, X, Y -> Y
9274   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9275     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9276
9277   // select C, X, X -> X
9278   if (TrueVal == FalseVal)
9279     return ReplaceInstUsesWith(SI, TrueVal);
9280
9281   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9282     return ReplaceInstUsesWith(SI, FalseVal);
9283   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9284     return ReplaceInstUsesWith(SI, TrueVal);
9285   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9286     if (isa<Constant>(TrueVal))
9287       return ReplaceInstUsesWith(SI, TrueVal);
9288     else
9289       return ReplaceInstUsesWith(SI, FalseVal);
9290   }
9291
9292   if (SI.getType() == Type::getInt1Ty(*Context)) {
9293     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9294       if (C->getZExtValue()) {
9295         // Change: A = select B, true, C --> A = or B, C
9296         return BinaryOperator::CreateOr(CondVal, FalseVal);
9297       } else {
9298         // Change: A = select B, false, C --> A = and !B, C
9299         Value *NotCond =
9300           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9301                                              "not."+CondVal->getName()), SI);
9302         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9303       }
9304     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9305       if (C->getZExtValue() == false) {
9306         // Change: A = select B, C, false --> A = and B, C
9307         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9308       } else {
9309         // Change: A = select B, C, true --> A = or !B, C
9310         Value *NotCond =
9311           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9312                                              "not."+CondVal->getName()), SI);
9313         return BinaryOperator::CreateOr(NotCond, TrueVal);
9314       }
9315     }
9316     
9317     // select a, b, a  -> a&b
9318     // select a, a, b  -> a|b
9319     if (CondVal == TrueVal)
9320       return BinaryOperator::CreateOr(CondVal, FalseVal);
9321     else if (CondVal == FalseVal)
9322       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9323   }
9324
9325   // Selecting between two integer constants?
9326   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9327     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9328       // select C, 1, 0 -> zext C to int
9329       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9330         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9331       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9332         // select C, 0, 1 -> zext !C to int
9333         Value *NotCond =
9334           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9335                                                "not."+CondVal->getName()), SI);
9336         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9337       }
9338
9339       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9340         // If one of the constants is zero (we know they can't both be) and we
9341         // have an icmp instruction with zero, and we have an 'and' with the
9342         // non-constant value, eliminate this whole mess.  This corresponds to
9343         // cases like this: ((X & 27) ? 27 : 0)
9344         if (TrueValC->isZero() || FalseValC->isZero())
9345           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9346               cast<Constant>(IC->getOperand(1))->isNullValue())
9347             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9348               if (ICA->getOpcode() == Instruction::And &&
9349                   isa<ConstantInt>(ICA->getOperand(1)) &&
9350                   (ICA->getOperand(1) == TrueValC ||
9351                    ICA->getOperand(1) == FalseValC) &&
9352                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9353                 // Okay, now we know that everything is set up, we just don't
9354                 // know whether we have a icmp_ne or icmp_eq and whether the 
9355                 // true or false val is the zero.
9356                 bool ShouldNotVal = !TrueValC->isZero();
9357                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9358                 Value *V = ICA;
9359                 if (ShouldNotVal)
9360                   V = InsertNewInstBefore(BinaryOperator::Create(
9361                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9362                 return ReplaceInstUsesWith(SI, V);
9363               }
9364       }
9365     }
9366
9367   // See if we are selecting two values based on a comparison of the two values.
9368   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9369     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9370       // Transform (X == Y) ? X : Y  -> Y
9371       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9372         // This is not safe in general for floating point:  
9373         // consider X== -0, Y== +0.
9374         // It becomes safe if either operand is a nonzero constant.
9375         ConstantFP *CFPt, *CFPf;
9376         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9377               !CFPt->getValueAPF().isZero()) ||
9378             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9379              !CFPf->getValueAPF().isZero()))
9380         return ReplaceInstUsesWith(SI, FalseVal);
9381       }
9382       // Transform (X != Y) ? X : Y  -> X
9383       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9384         return ReplaceInstUsesWith(SI, TrueVal);
9385       // NOTE: if we wanted to, this is where to detect MIN/MAX
9386
9387     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9388       // Transform (X == Y) ? Y : X  -> X
9389       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9390         // This is not safe in general for floating point:  
9391         // consider X== -0, Y== +0.
9392         // It becomes safe if either operand is a nonzero constant.
9393         ConstantFP *CFPt, *CFPf;
9394         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9395               !CFPt->getValueAPF().isZero()) ||
9396             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9397              !CFPf->getValueAPF().isZero()))
9398           return ReplaceInstUsesWith(SI, FalseVal);
9399       }
9400       // Transform (X != Y) ? Y : X  -> Y
9401       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9402         return ReplaceInstUsesWith(SI, TrueVal);
9403       // NOTE: if we wanted to, this is where to detect MIN/MAX
9404     }
9405     // NOTE: if we wanted to, this is where to detect ABS
9406   }
9407
9408   // See if we are selecting two values based on a comparison of the two values.
9409   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9410     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9411       return Result;
9412
9413   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9414     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9415       if (TI->hasOneUse() && FI->hasOneUse()) {
9416         Instruction *AddOp = 0, *SubOp = 0;
9417
9418         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9419         if (TI->getOpcode() == FI->getOpcode())
9420           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9421             return IV;
9422
9423         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9424         // even legal for FP.
9425         if ((TI->getOpcode() == Instruction::Sub &&
9426              FI->getOpcode() == Instruction::Add) ||
9427             (TI->getOpcode() == Instruction::FSub &&
9428              FI->getOpcode() == Instruction::FAdd)) {
9429           AddOp = FI; SubOp = TI;
9430         } else if ((FI->getOpcode() == Instruction::Sub &&
9431                     TI->getOpcode() == Instruction::Add) ||
9432                    (FI->getOpcode() == Instruction::FSub &&
9433                     TI->getOpcode() == Instruction::FAdd)) {
9434           AddOp = TI; SubOp = FI;
9435         }
9436
9437         if (AddOp) {
9438           Value *OtherAddOp = 0;
9439           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9440             OtherAddOp = AddOp->getOperand(1);
9441           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9442             OtherAddOp = AddOp->getOperand(0);
9443           }
9444
9445           if (OtherAddOp) {
9446             // So at this point we know we have (Y -> OtherAddOp):
9447             //        select C, (add X, Y), (sub X, Z)
9448             Value *NegVal;  // Compute -Z
9449             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9450               NegVal = ConstantExpr::getNeg(C);
9451             } else {
9452               NegVal = InsertNewInstBefore(
9453                     BinaryOperator::CreateNeg(SubOp->getOperand(1),
9454                                               "tmp"), SI);
9455             }
9456
9457             Value *NewTrueOp = OtherAddOp;
9458             Value *NewFalseOp = NegVal;
9459             if (AddOp != TI)
9460               std::swap(NewTrueOp, NewFalseOp);
9461             Instruction *NewSel =
9462               SelectInst::Create(CondVal, NewTrueOp,
9463                                  NewFalseOp, SI.getName() + ".p");
9464
9465             NewSel = InsertNewInstBefore(NewSel, SI);
9466             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9467           }
9468         }
9469       }
9470
9471   // See if we can fold the select into one of our operands.
9472   if (SI.getType()->isInteger()) {
9473     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9474     if (FoldI)
9475       return FoldI;
9476   }
9477
9478   // See if we can fold the select into a phi node.  The true/false values have
9479   // to be live in the predecessor blocks.  If they are instructions in SI's
9480   // block, we can't map to the predecessor.
9481   if (isa<PHINode>(SI.getCondition()) &&
9482       (!isDefinedInBB(SI.getTrueValue(), SI.getParent()) ||
9483        isa<PHINode>(SI.getTrueValue())) &&
9484       (!isDefinedInBB(SI.getFalseValue(), SI.getParent()) ||
9485        isa<PHINode>(SI.getFalseValue())))
9486     if (Instruction *NV = FoldOpIntoPhi(SI))
9487       return NV;
9488
9489   if (BinaryOperator::isNot(CondVal)) {
9490     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9491     SI.setOperand(1, FalseVal);
9492     SI.setOperand(2, TrueVal);
9493     return &SI;
9494   }
9495
9496   return 0;
9497 }
9498
9499 /// EnforceKnownAlignment - If the specified pointer points to an object that
9500 /// we control, modify the object's alignment to PrefAlign. This isn't
9501 /// often possible though. If alignment is important, a more reliable approach
9502 /// is to simply align all global variables and allocation instructions to
9503 /// their preferred alignment from the beginning.
9504 ///
9505 static unsigned EnforceKnownAlignment(Value *V,
9506                                       unsigned Align, unsigned PrefAlign) {
9507
9508   User *U = dyn_cast<User>(V);
9509   if (!U) return Align;
9510
9511   switch (Operator::getOpcode(U)) {
9512   default: break;
9513   case Instruction::BitCast:
9514     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9515   case Instruction::GetElementPtr: {
9516     // If all indexes are zero, it is just the alignment of the base pointer.
9517     bool AllZeroOperands = true;
9518     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9519       if (!isa<Constant>(*i) ||
9520           !cast<Constant>(*i)->isNullValue()) {
9521         AllZeroOperands = false;
9522         break;
9523       }
9524
9525     if (AllZeroOperands) {
9526       // Treat this like a bitcast.
9527       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9528     }
9529     break;
9530   }
9531   }
9532
9533   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9534     // If there is a large requested alignment and we can, bump up the alignment
9535     // of the global.
9536     if (!GV->isDeclaration()) {
9537       if (GV->getAlignment() >= PrefAlign)
9538         Align = GV->getAlignment();
9539       else {
9540         GV->setAlignment(PrefAlign);
9541         Align = PrefAlign;
9542       }
9543     }
9544   } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9545     // If there is a requested alignment and if this is an alloca, round up.
9546     if (AI->getAlignment() >= PrefAlign)
9547       Align = AI->getAlignment();
9548     else {
9549       AI->setAlignment(PrefAlign);
9550       Align = PrefAlign;
9551     }
9552   }
9553
9554   return Align;
9555 }
9556
9557 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9558 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9559 /// and it is more than the alignment of the ultimate object, see if we can
9560 /// increase the alignment of the ultimate object, making this check succeed.
9561 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9562                                                   unsigned PrefAlign) {
9563   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9564                       sizeof(PrefAlign) * CHAR_BIT;
9565   APInt Mask = APInt::getAllOnesValue(BitWidth);
9566   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9567   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9568   unsigned TrailZ = KnownZero.countTrailingOnes();
9569   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9570
9571   if (PrefAlign > Align)
9572     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9573   
9574     // We don't need to make any adjustment.
9575   return Align;
9576 }
9577
9578 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9579   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9580   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9581   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9582   unsigned CopyAlign = MI->getAlignment();
9583
9584   if (CopyAlign < MinAlign) {
9585     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 
9586                                              MinAlign, false));
9587     return MI;
9588   }
9589   
9590   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9591   // load/store.
9592   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9593   if (MemOpLength == 0) return 0;
9594   
9595   // Source and destination pointer types are always "i8*" for intrinsic.  See
9596   // if the size is something we can handle with a single primitive load/store.
9597   // A single load+store correctly handles overlapping memory in the memmove
9598   // case.
9599   unsigned Size = MemOpLength->getZExtValue();
9600   if (Size == 0) return MI;  // Delete this mem transfer.
9601   
9602   if (Size > 8 || (Size&(Size-1)))
9603     return 0;  // If not 1/2/4/8 bytes, exit.
9604   
9605   // Use an integer load+store unless we can find something better.
9606   Type *NewPtrTy =
9607                 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
9608   
9609   // Memcpy forces the use of i8* for the source and destination.  That means
9610   // that if you're using memcpy to move one double around, you'll get a cast
9611   // from double* to i8*.  We'd much rather use a double load+store rather than
9612   // an i64 load+store, here because this improves the odds that the source or
9613   // dest address will be promotable.  See if we can find a better type than the
9614   // integer datatype.
9615   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9616     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9617     if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9618       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9619       // down through these levels if so.
9620       while (!SrcETy->isSingleValueType()) {
9621         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9622           if (STy->getNumElements() == 1)
9623             SrcETy = STy->getElementType(0);
9624           else
9625             break;
9626         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9627           if (ATy->getNumElements() == 1)
9628             SrcETy = ATy->getElementType();
9629           else
9630             break;
9631         } else
9632           break;
9633       }
9634       
9635       if (SrcETy->isSingleValueType())
9636         NewPtrTy = PointerType::getUnqual(SrcETy);
9637     }
9638   }
9639   
9640   
9641   // If the memcpy/memmove provides better alignment info than we can
9642   // infer, use it.
9643   SrcAlign = std::max(SrcAlign, CopyAlign);
9644   DstAlign = std::max(DstAlign, CopyAlign);
9645   
9646   Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9647   Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
9648   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9649   InsertNewInstBefore(L, *MI);
9650   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9651
9652   // Set the size of the copy to 0, it will be deleted on the next iteration.
9653   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9654   return MI;
9655 }
9656
9657 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9658   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9659   if (MI->getAlignment() < Alignment) {
9660     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9661                                              Alignment, false));
9662     return MI;
9663   }
9664   
9665   // Extract the length and alignment and fill if they are constant.
9666   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9667   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9668   if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
9669     return 0;
9670   uint64_t Len = LenC->getZExtValue();
9671   Alignment = MI->getAlignment();
9672   
9673   // If the length is zero, this is a no-op
9674   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9675   
9676   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9677   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9678     const Type *ITy = IntegerType::get(*Context, Len*8);  // n=1 -> i8.
9679     
9680     Value *Dest = MI->getDest();
9681     Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
9682
9683     // Alignment 0 is identity for alignment 1 for memset, but not store.
9684     if (Alignment == 0) Alignment = 1;
9685     
9686     // Extract the fill value and store.
9687     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9688     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9689                                       Dest, false, Alignment), *MI);
9690     
9691     // Set the size of the copy to 0, it will be deleted on the next iteration.
9692     MI->setLength(Constant::getNullValue(LenC->getType()));
9693     return MI;
9694   }
9695
9696   return 0;
9697 }
9698
9699
9700 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9701 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9702 /// the heavy lifting.
9703 ///
9704 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9705   // If the caller function is nounwind, mark the call as nounwind, even if the
9706   // callee isn't.
9707   if (CI.getParent()->getParent()->doesNotThrow() &&
9708       !CI.doesNotThrow()) {
9709     CI.setDoesNotThrow();
9710     return &CI;
9711   }
9712   
9713   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9714   if (!II) return visitCallSite(&CI);
9715   
9716   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9717   // visitCallSite.
9718   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9719     bool Changed = false;
9720
9721     // memmove/cpy/set of zero bytes is a noop.
9722     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9723       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9724
9725       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9726         if (CI->getZExtValue() == 1) {
9727           // Replace the instruction with just byte operations.  We would
9728           // transform other cases to loads/stores, but we don't know if
9729           // alignment is sufficient.
9730         }
9731     }
9732
9733     // If we have a memmove and the source operation is a constant global,
9734     // then the source and dest pointers can't alias, so we can change this
9735     // into a call to memcpy.
9736     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9737       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9738         if (GVSrc->isConstant()) {
9739           Module *M = CI.getParent()->getParent()->getParent();
9740           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9741           const Type *Tys[1];
9742           Tys[0] = CI.getOperand(3)->getType();
9743           CI.setOperand(0, 
9744                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9745           Changed = true;
9746         }
9747
9748       // memmove(x,x,size) -> noop.
9749       if (MMI->getSource() == MMI->getDest())
9750         return EraseInstFromFunction(CI);
9751     }
9752
9753     // If we can determine a pointer alignment that is bigger than currently
9754     // set, update the alignment.
9755     if (isa<MemTransferInst>(MI)) {
9756       if (Instruction *I = SimplifyMemTransfer(MI))
9757         return I;
9758     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9759       if (Instruction *I = SimplifyMemSet(MSI))
9760         return I;
9761     }
9762           
9763     if (Changed) return II;
9764   }
9765   
9766   switch (II->getIntrinsicID()) {
9767   default: break;
9768   case Intrinsic::bswap:
9769     // bswap(bswap(x)) -> x
9770     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9771       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9772         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9773     break;
9774   case Intrinsic::ppc_altivec_lvx:
9775   case Intrinsic::ppc_altivec_lvxl:
9776   case Intrinsic::x86_sse_loadu_ps:
9777   case Intrinsic::x86_sse2_loadu_pd:
9778   case Intrinsic::x86_sse2_loadu_dq:
9779     // Turn PPC lvx     -> load if the pointer is known aligned.
9780     // Turn X86 loadups -> load if the pointer is known aligned.
9781     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9782       Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9783                                          PointerType::getUnqual(II->getType()));
9784       return new LoadInst(Ptr);
9785     }
9786     break;
9787   case Intrinsic::ppc_altivec_stvx:
9788   case Intrinsic::ppc_altivec_stvxl:
9789     // Turn stvx -> store if the pointer is known aligned.
9790     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9791       const Type *OpPtrTy = 
9792         PointerType::getUnqual(II->getOperand(1)->getType());
9793       Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
9794       return new StoreInst(II->getOperand(1), Ptr);
9795     }
9796     break;
9797   case Intrinsic::x86_sse_storeu_ps:
9798   case Intrinsic::x86_sse2_storeu_pd:
9799   case Intrinsic::x86_sse2_storeu_dq:
9800     // Turn X86 storeu -> store if the pointer is known aligned.
9801     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9802       const Type *OpPtrTy = 
9803         PointerType::getUnqual(II->getOperand(2)->getType());
9804       Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
9805       return new StoreInst(II->getOperand(2), Ptr);
9806     }
9807     break;
9808     
9809   case Intrinsic::x86_sse_cvttss2si: {
9810     // These intrinsics only demands the 0th element of its input vector.  If
9811     // we can simplify the input based on that, do so now.
9812     unsigned VWidth =
9813       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9814     APInt DemandedElts(VWidth, 1);
9815     APInt UndefElts(VWidth, 0);
9816     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9817                                               UndefElts)) {
9818       II->setOperand(1, V);
9819       return II;
9820     }
9821     break;
9822   }
9823     
9824   case Intrinsic::ppc_altivec_vperm:
9825     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9826     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9827       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9828       
9829       // Check that all of the elements are integer constants or undefs.
9830       bool AllEltsOk = true;
9831       for (unsigned i = 0; i != 16; ++i) {
9832         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9833             !isa<UndefValue>(Mask->getOperand(i))) {
9834           AllEltsOk = false;
9835           break;
9836         }
9837       }
9838       
9839       if (AllEltsOk) {
9840         // Cast the input vectors to byte vectors.
9841         Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9842         Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
9843         Value *Result = UndefValue::get(Op0->getType());
9844         
9845         // Only extract each element once.
9846         Value *ExtractedElts[32];
9847         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9848         
9849         for (unsigned i = 0; i != 16; ++i) {
9850           if (isa<UndefValue>(Mask->getOperand(i)))
9851             continue;
9852           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9853           Idx &= 31;  // Match the hardware behavior.
9854           
9855           if (ExtractedElts[Idx] == 0) {
9856             ExtractedElts[Idx] = 
9857               Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1, 
9858                   ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9859                                             "tmp");
9860           }
9861         
9862           // Insert this value into the result vector.
9863           Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9864                          ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9865                                                 "tmp");
9866         }
9867         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9868       }
9869     }
9870     break;
9871
9872   case Intrinsic::stackrestore: {
9873     // If the save is right next to the restore, remove the restore.  This can
9874     // happen when variable allocas are DCE'd.
9875     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9876       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9877         BasicBlock::iterator BI = SS;
9878         if (&*++BI == II)
9879           return EraseInstFromFunction(CI);
9880       }
9881     }
9882     
9883     // Scan down this block to see if there is another stack restore in the
9884     // same block without an intervening call/alloca.
9885     BasicBlock::iterator BI = II;
9886     TerminatorInst *TI = II->getParent()->getTerminator();
9887     bool CannotRemove = false;
9888     for (++BI; &*BI != TI; ++BI) {
9889       if (isa<AllocaInst>(BI) || isMalloc(BI)) {
9890         CannotRemove = true;
9891         break;
9892       }
9893       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9894         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9895           // If there is a stackrestore below this one, remove this one.
9896           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9897             return EraseInstFromFunction(CI);
9898           // Otherwise, ignore the intrinsic.
9899         } else {
9900           // If we found a non-intrinsic call, we can't remove the stack
9901           // restore.
9902           CannotRemove = true;
9903           break;
9904         }
9905       }
9906     }
9907     
9908     // If the stack restore is in a return/unwind block and if there are no
9909     // allocas or calls between the restore and the return, nuke the restore.
9910     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9911       return EraseInstFromFunction(CI);
9912     break;
9913   }
9914   }
9915
9916   return visitCallSite(II);
9917 }
9918
9919 // InvokeInst simplification
9920 //
9921 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9922   return visitCallSite(&II);
9923 }
9924
9925 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9926 /// passed through the varargs area, we can eliminate the use of the cast.
9927 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9928                                          const CastInst * const CI,
9929                                          const TargetData * const TD,
9930                                          const int ix) {
9931   if (!CI->isLosslessCast())
9932     return false;
9933
9934   // The size of ByVal arguments is derived from the type, so we
9935   // can't change to a type with a different size.  If the size were
9936   // passed explicitly we could avoid this check.
9937   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9938     return true;
9939
9940   const Type* SrcTy = 
9941             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9942   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9943   if (!SrcTy->isSized() || !DstTy->isSized())
9944     return false;
9945   if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
9946     return false;
9947   return true;
9948 }
9949
9950 // visitCallSite - Improvements for call and invoke instructions.
9951 //
9952 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9953   bool Changed = false;
9954
9955   // If the callee is a constexpr cast of a function, attempt to move the cast
9956   // to the arguments of the call/invoke.
9957   if (transformConstExprCastCall(CS)) return 0;
9958
9959   Value *Callee = CS.getCalledValue();
9960
9961   if (Function *CalleeF = dyn_cast<Function>(Callee))
9962     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9963       Instruction *OldCall = CS.getInstruction();
9964       // If the call and callee calling conventions don't match, this call must
9965       // be unreachable, as the call is undefined.
9966       new StoreInst(ConstantInt::getTrue(*Context),
9967                 UndefValue::get(Type::getInt1PtrTy(*Context)), 
9968                                   OldCall);
9969       // If OldCall dues not return void then replaceAllUsesWith undef.
9970       // This allows ValueHandlers and custom metadata to adjust itself.
9971       if (!OldCall->getType()->isVoidTy())
9972         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9973       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
9974         return EraseInstFromFunction(*OldCall);
9975       return 0;
9976     }
9977
9978   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9979     // This instruction is not reachable, just remove it.  We insert a store to
9980     // undef so that we know that this code is not reachable, despite the fact
9981     // that we can't modify the CFG here.
9982     new StoreInst(ConstantInt::getTrue(*Context),
9983                UndefValue::get(Type::getInt1PtrTy(*Context)),
9984                   CS.getInstruction());
9985
9986     // If CS dues not return void then replaceAllUsesWith undef.
9987     // This allows ValueHandlers and custom metadata to adjust itself.
9988     if (!CS.getInstruction()->getType()->isVoidTy())
9989       CS.getInstruction()->
9990         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9991
9992     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9993       // Don't break the CFG, insert a dummy cond branch.
9994       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9995                          ConstantInt::getTrue(*Context), II);
9996     }
9997     return EraseInstFromFunction(*CS.getInstruction());
9998   }
9999
10000   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10001     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10002       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10003         return transformCallThroughTrampoline(CS);
10004
10005   const PointerType *PTy = cast<PointerType>(Callee->getType());
10006   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10007   if (FTy->isVarArg()) {
10008     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10009     // See if we can optimize any arguments passed through the varargs area of
10010     // the call.
10011     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10012            E = CS.arg_end(); I != E; ++I, ++ix) {
10013       CastInst *CI = dyn_cast<CastInst>(*I);
10014       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10015         *I = CI->getOperand(0);
10016         Changed = true;
10017       }
10018     }
10019   }
10020
10021   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10022     // Inline asm calls cannot throw - mark them 'nounwind'.
10023     CS.setDoesNotThrow();
10024     Changed = true;
10025   }
10026
10027   return Changed ? CS.getInstruction() : 0;
10028 }
10029
10030 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10031 // attempt to move the cast to the arguments of the call/invoke.
10032 //
10033 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10034   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10035   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10036   if (CE->getOpcode() != Instruction::BitCast || 
10037       !isa<Function>(CE->getOperand(0)))
10038     return false;
10039   Function *Callee = cast<Function>(CE->getOperand(0));
10040   Instruction *Caller = CS.getInstruction();
10041   const AttrListPtr &CallerPAL = CS.getAttributes();
10042
10043   // Okay, this is a cast from a function to a different type.  Unless doing so
10044   // would cause a type conversion of one of our arguments, change this call to
10045   // be a direct call with arguments casted to the appropriate types.
10046   //
10047   const FunctionType *FT = Callee->getFunctionType();
10048   const Type *OldRetTy = Caller->getType();
10049   const Type *NewRetTy = FT->getReturnType();
10050
10051   if (isa<StructType>(NewRetTy))
10052     return false; // TODO: Handle multiple return values.
10053
10054   // Check to see if we are changing the return type...
10055   if (OldRetTy != NewRetTy) {
10056     if (Callee->isDeclaration() &&
10057         // Conversion is ok if changing from one pointer type to another or from
10058         // a pointer to an integer of the same size.
10059         !((isa<PointerType>(OldRetTy) || !TD ||
10060            OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
10061           (isa<PointerType>(NewRetTy) || !TD ||
10062            NewRetTy == TD->getIntPtrType(Caller->getContext()))))
10063       return false;   // Cannot transform this return value.
10064
10065     if (!Caller->use_empty() &&
10066         // void -> non-void is handled specially
10067         !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
10068       return false;   // Cannot transform this return value.
10069
10070     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10071       Attributes RAttrs = CallerPAL.getRetAttributes();
10072       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10073         return false;   // Attribute not compatible with transformed value.
10074     }
10075
10076     // If the callsite is an invoke instruction, and the return value is used by
10077     // a PHI node in a successor, we cannot change the return type of the call
10078     // because there is no place to put the cast instruction (without breaking
10079     // the critical edge).  Bail out in this case.
10080     if (!Caller->use_empty())
10081       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10082         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10083              UI != E; ++UI)
10084           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10085             if (PN->getParent() == II->getNormalDest() ||
10086                 PN->getParent() == II->getUnwindDest())
10087               return false;
10088   }
10089
10090   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10091   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10092
10093   CallSite::arg_iterator AI = CS.arg_begin();
10094   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10095     const Type *ParamTy = FT->getParamType(i);
10096     const Type *ActTy = (*AI)->getType();
10097
10098     if (!CastInst::isCastable(ActTy, ParamTy))
10099       return false;   // Cannot transform this parameter value.
10100
10101     if (CallerPAL.getParamAttributes(i + 1) 
10102         & Attribute::typeIncompatible(ParamTy))
10103       return false;   // Attribute not compatible with transformed value.
10104
10105     // Converting from one pointer type to another or between a pointer and an
10106     // integer of the same size is safe even if we do not have a body.
10107     bool isConvertible = ActTy == ParamTy ||
10108       (TD && ((isa<PointerType>(ParamTy) ||
10109       ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10110               (isa<PointerType>(ActTy) ||
10111               ActTy == TD->getIntPtrType(Caller->getContext()))));
10112     if (Callee->isDeclaration() && !isConvertible) return false;
10113   }
10114
10115   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10116       Callee->isDeclaration())
10117     return false;   // Do not delete arguments unless we have a function body.
10118
10119   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10120       !CallerPAL.isEmpty())
10121     // In this case we have more arguments than the new function type, but we
10122     // won't be dropping them.  Check that these extra arguments have attributes
10123     // that are compatible with being a vararg call argument.
10124     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10125       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10126         break;
10127       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10128       if (PAttrs & Attribute::VarArgsIncompatible)
10129         return false;
10130     }
10131
10132   // Okay, we decided that this is a safe thing to do: go ahead and start
10133   // inserting cast instructions as necessary...
10134   std::vector<Value*> Args;
10135   Args.reserve(NumActualArgs);
10136   SmallVector<AttributeWithIndex, 8> attrVec;
10137   attrVec.reserve(NumCommonArgs);
10138
10139   // Get any return attributes.
10140   Attributes RAttrs = CallerPAL.getRetAttributes();
10141
10142   // If the return value is not being used, the type may not be compatible
10143   // with the existing attributes.  Wipe out any problematic attributes.
10144   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10145
10146   // Add the new return attributes.
10147   if (RAttrs)
10148     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10149
10150   AI = CS.arg_begin();
10151   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10152     const Type *ParamTy = FT->getParamType(i);
10153     if ((*AI)->getType() == ParamTy) {
10154       Args.push_back(*AI);
10155     } else {
10156       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10157           false, ParamTy, false);
10158       Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
10159     }
10160
10161     // Add any parameter attributes.
10162     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10163       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10164   }
10165
10166   // If the function takes more arguments than the call was taking, add them
10167   // now.
10168   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10169     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10170
10171   // If we are removing arguments to the function, emit an obnoxious warning.
10172   if (FT->getNumParams() < NumActualArgs) {
10173     if (!FT->isVarArg()) {
10174       errs() << "WARNING: While resolving call to function '"
10175              << Callee->getName() << "' arguments were dropped!\n";
10176     } else {
10177       // Add all of the arguments in their promoted form to the arg list.
10178       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10179         const Type *PTy = getPromotedType((*AI)->getType());
10180         if (PTy != (*AI)->getType()) {
10181           // Must promote to pass through va_arg area!
10182           Instruction::CastOps opcode =
10183             CastInst::getCastOpcode(*AI, false, PTy, false);
10184           Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
10185         } else {
10186           Args.push_back(*AI);
10187         }
10188
10189         // Add any parameter attributes.
10190         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10191           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10192       }
10193     }
10194   }
10195
10196   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10197     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10198
10199   if (NewRetTy->isVoidTy())
10200     Caller->setName("");   // Void type should not have a name.
10201
10202   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10203                                                      attrVec.end());
10204
10205   Instruction *NC;
10206   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10207     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10208                             Args.begin(), Args.end(),
10209                             Caller->getName(), Caller);
10210     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10211     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10212   } else {
10213     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10214                           Caller->getName(), Caller);
10215     CallInst *CI = cast<CallInst>(Caller);
10216     if (CI->isTailCall())
10217       cast<CallInst>(NC)->setTailCall();
10218     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10219     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10220   }
10221
10222   // Insert a cast of the return type as necessary.
10223   Value *NV = NC;
10224   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10225     if (!NV->getType()->isVoidTy()) {
10226       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10227                                                             OldRetTy, false);
10228       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10229
10230       // If this is an invoke instruction, we should insert it after the first
10231       // non-phi, instruction in the normal successor block.
10232       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10233         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10234         InsertNewInstBefore(NC, *I);
10235       } else {
10236         // Otherwise, it's a call, just insert cast right after the call instr
10237         InsertNewInstBefore(NC, *Caller);
10238       }
10239       Worklist.AddUsersToWorkList(*Caller);
10240     } else {
10241       NV = UndefValue::get(Caller->getType());
10242     }
10243   }
10244
10245
10246   if (!Caller->use_empty())
10247     Caller->replaceAllUsesWith(NV);
10248   
10249   EraseInstFromFunction(*Caller);
10250   return true;
10251 }
10252
10253 // transformCallThroughTrampoline - Turn a call to a function created by the
10254 // init_trampoline intrinsic into a direct call to the underlying function.
10255 //
10256 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10257   Value *Callee = CS.getCalledValue();
10258   const PointerType *PTy = cast<PointerType>(Callee->getType());
10259   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10260   const AttrListPtr &Attrs = CS.getAttributes();
10261
10262   // If the call already has the 'nest' attribute somewhere then give up -
10263   // otherwise 'nest' would occur twice after splicing in the chain.
10264   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10265     return 0;
10266
10267   IntrinsicInst *Tramp =
10268     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10269
10270   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10271   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10272   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10273
10274   const AttrListPtr &NestAttrs = NestF->getAttributes();
10275   if (!NestAttrs.isEmpty()) {
10276     unsigned NestIdx = 1;
10277     const Type *NestTy = 0;
10278     Attributes NestAttr = Attribute::None;
10279
10280     // Look for a parameter marked with the 'nest' attribute.
10281     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10282          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10283       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10284         // Record the parameter type and any other attributes.
10285         NestTy = *I;
10286         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10287         break;
10288       }
10289
10290     if (NestTy) {
10291       Instruction *Caller = CS.getInstruction();
10292       std::vector<Value*> NewArgs;
10293       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10294
10295       SmallVector<AttributeWithIndex, 8> NewAttrs;
10296       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10297
10298       // Insert the nest argument into the call argument list, which may
10299       // mean appending it.  Likewise for attributes.
10300
10301       // Add any result attributes.
10302       if (Attributes Attr = Attrs.getRetAttributes())
10303         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10304
10305       {
10306         unsigned Idx = 1;
10307         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10308         do {
10309           if (Idx == NestIdx) {
10310             // Add the chain argument and attributes.
10311             Value *NestVal = Tramp->getOperand(3);
10312             if (NestVal->getType() != NestTy)
10313               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10314             NewArgs.push_back(NestVal);
10315             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10316           }
10317
10318           if (I == E)
10319             break;
10320
10321           // Add the original argument and attributes.
10322           NewArgs.push_back(*I);
10323           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10324             NewAttrs.push_back
10325               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10326
10327           ++Idx, ++I;
10328         } while (1);
10329       }
10330
10331       // Add any function attributes.
10332       if (Attributes Attr = Attrs.getFnAttributes())
10333         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10334
10335       // The trampoline may have been bitcast to a bogus type (FTy).
10336       // Handle this by synthesizing a new function type, equal to FTy
10337       // with the chain parameter inserted.
10338
10339       std::vector<const Type*> NewTypes;
10340       NewTypes.reserve(FTy->getNumParams()+1);
10341
10342       // Insert the chain's type into the list of parameter types, which may
10343       // mean appending it.
10344       {
10345         unsigned Idx = 1;
10346         FunctionType::param_iterator I = FTy->param_begin(),
10347           E = FTy->param_end();
10348
10349         do {
10350           if (Idx == NestIdx)
10351             // Add the chain's type.
10352             NewTypes.push_back(NestTy);
10353
10354           if (I == E)
10355             break;
10356
10357           // Add the original type.
10358           NewTypes.push_back(*I);
10359
10360           ++Idx, ++I;
10361         } while (1);
10362       }
10363
10364       // Replace the trampoline call with a direct call.  Let the generic
10365       // code sort out any function type mismatches.
10366       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 
10367                                                 FTy->isVarArg());
10368       Constant *NewCallee =
10369         NestF->getType() == PointerType::getUnqual(NewFTy) ?
10370         NestF : ConstantExpr::getBitCast(NestF, 
10371                                          PointerType::getUnqual(NewFTy));
10372       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10373                                                    NewAttrs.end());
10374
10375       Instruction *NewCaller;
10376       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10377         NewCaller = InvokeInst::Create(NewCallee,
10378                                        II->getNormalDest(), II->getUnwindDest(),
10379                                        NewArgs.begin(), NewArgs.end(),
10380                                        Caller->getName(), Caller);
10381         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10382         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10383       } else {
10384         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10385                                      Caller->getName(), Caller);
10386         if (cast<CallInst>(Caller)->isTailCall())
10387           cast<CallInst>(NewCaller)->setTailCall();
10388         cast<CallInst>(NewCaller)->
10389           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10390         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10391       }
10392       if (!Caller->getType()->isVoidTy())
10393         Caller->replaceAllUsesWith(NewCaller);
10394       Caller->eraseFromParent();
10395       Worklist.Remove(Caller);
10396       return 0;
10397     }
10398   }
10399
10400   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10401   // parameter, there is no need to adjust the argument list.  Let the generic
10402   // code sort out any function type mismatches.
10403   Constant *NewCallee =
10404     NestF->getType() == PTy ? NestF : 
10405                               ConstantExpr::getBitCast(NestF, PTy);
10406   CS.setCalledFunction(NewCallee);
10407   return CS.getInstruction();
10408 }
10409
10410 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10411 /// and if a/b/c and the add's all have a single use, turn this into a phi
10412 /// and a single binop.
10413 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10414   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10415   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10416   unsigned Opc = FirstInst->getOpcode();
10417   Value *LHSVal = FirstInst->getOperand(0);
10418   Value *RHSVal = FirstInst->getOperand(1);
10419     
10420   const Type *LHSType = LHSVal->getType();
10421   const Type *RHSType = RHSVal->getType();
10422   
10423   // Scan to see if all operands are the same opcode, and all have one use.
10424   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10425     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10426     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10427         // Verify type of the LHS matches so we don't fold cmp's of different
10428         // types or GEP's with different index types.
10429         I->getOperand(0)->getType() != LHSType ||
10430         I->getOperand(1)->getType() != RHSType)
10431       return 0;
10432
10433     // If they are CmpInst instructions, check their predicates
10434     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10435       if (cast<CmpInst>(I)->getPredicate() !=
10436           cast<CmpInst>(FirstInst)->getPredicate())
10437         return 0;
10438     
10439     // Keep track of which operand needs a phi node.
10440     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10441     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10442   }
10443
10444   // If both LHS and RHS would need a PHI, don't do this transformation,
10445   // because it would increase the number of PHIs entering the block,
10446   // which leads to higher register pressure. This is especially
10447   // bad when the PHIs are in the header of a loop.
10448   if (!LHSVal && !RHSVal)
10449     return 0;
10450   
10451   // Otherwise, this is safe to transform!
10452   
10453   Value *InLHS = FirstInst->getOperand(0);
10454   Value *InRHS = FirstInst->getOperand(1);
10455   PHINode *NewLHS = 0, *NewRHS = 0;
10456   if (LHSVal == 0) {
10457     NewLHS = PHINode::Create(LHSType,
10458                              FirstInst->getOperand(0)->getName() + ".pn");
10459     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10460     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10461     InsertNewInstBefore(NewLHS, PN);
10462     LHSVal = NewLHS;
10463   }
10464   
10465   if (RHSVal == 0) {
10466     NewRHS = PHINode::Create(RHSType,
10467                              FirstInst->getOperand(1)->getName() + ".pn");
10468     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10469     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10470     InsertNewInstBefore(NewRHS, PN);
10471     RHSVal = NewRHS;
10472   }
10473   
10474   // Add all operands to the new PHIs.
10475   if (NewLHS || NewRHS) {
10476     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10477       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10478       if (NewLHS) {
10479         Value *NewInLHS = InInst->getOperand(0);
10480         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10481       }
10482       if (NewRHS) {
10483         Value *NewInRHS = InInst->getOperand(1);
10484         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10485       }
10486     }
10487   }
10488     
10489   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10490     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10491   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10492   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10493                          LHSVal, RHSVal);
10494 }
10495
10496 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10497   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10498   
10499   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10500                                         FirstInst->op_end());
10501   // This is true if all GEP bases are allocas and if all indices into them are
10502   // constants.
10503   bool AllBasePointersAreAllocas = true;
10504
10505   // We don't want to replace this phi if the replacement would require
10506   // more than one phi, which leads to higher register pressure. This is
10507   // especially bad when the PHIs are in the header of a loop.
10508   bool NeededPhi = false;
10509   
10510   // Scan to see if all operands are the same opcode, and all have one use.
10511   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10512     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10513     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10514       GEP->getNumOperands() != FirstInst->getNumOperands())
10515       return 0;
10516
10517     // Keep track of whether or not all GEPs are of alloca pointers.
10518     if (AllBasePointersAreAllocas &&
10519         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10520          !GEP->hasAllConstantIndices()))
10521       AllBasePointersAreAllocas = false;
10522     
10523     // Compare the operand lists.
10524     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10525       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10526         continue;
10527       
10528       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10529       // if one of the PHIs has a constant for the index.  The index may be
10530       // substantially cheaper to compute for the constants, so making it a
10531       // variable index could pessimize the path.  This also handles the case
10532       // for struct indices, which must always be constant.
10533       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10534           isa<ConstantInt>(GEP->getOperand(op)))
10535         return 0;
10536       
10537       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10538         return 0;
10539
10540       // If we already needed a PHI for an earlier operand, and another operand
10541       // also requires a PHI, we'd be introducing more PHIs than we're
10542       // eliminating, which increases register pressure on entry to the PHI's
10543       // block.
10544       if (NeededPhi)
10545         return 0;
10546
10547       FixedOperands[op] = 0;  // Needs a PHI.
10548       NeededPhi = true;
10549     }
10550   }
10551   
10552   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10553   // bother doing this transformation.  At best, this will just save a bit of
10554   // offset calculation, but all the predecessors will have to materialize the
10555   // stack address into a register anyway.  We'd actually rather *clone* the
10556   // load up into the predecessors so that we have a load of a gep of an alloca,
10557   // which can usually all be folded into the load.
10558   if (AllBasePointersAreAllocas)
10559     return 0;
10560   
10561   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10562   // that is variable.
10563   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10564   
10565   bool HasAnyPHIs = false;
10566   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10567     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10568     Value *FirstOp = FirstInst->getOperand(i);
10569     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10570                                      FirstOp->getName()+".pn");
10571     InsertNewInstBefore(NewPN, PN);
10572     
10573     NewPN->reserveOperandSpace(e);
10574     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10575     OperandPhis[i] = NewPN;
10576     FixedOperands[i] = NewPN;
10577     HasAnyPHIs = true;
10578   }
10579
10580   
10581   // Add all operands to the new PHIs.
10582   if (HasAnyPHIs) {
10583     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10584       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10585       BasicBlock *InBB = PN.getIncomingBlock(i);
10586       
10587       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10588         if (PHINode *OpPhi = OperandPhis[op])
10589           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10590     }
10591   }
10592   
10593   Value *Base = FixedOperands[0];
10594   return cast<GEPOperator>(FirstInst)->isInBounds() ?
10595     GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10596                                       FixedOperands.end()) :
10597     GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10598                               FixedOperands.end());
10599 }
10600
10601
10602 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10603 /// sink the load out of the block that defines it.  This means that it must be
10604 /// obvious the value of the load is not changed from the point of the load to
10605 /// the end of the block it is in.
10606 ///
10607 /// Finally, it is safe, but not profitable, to sink a load targetting a
10608 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10609 /// to a register.
10610 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10611   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10612   
10613   for (++BBI; BBI != E; ++BBI)
10614     if (BBI->mayWriteToMemory())
10615       return false;
10616   
10617   // Check for non-address taken alloca.  If not address-taken already, it isn't
10618   // profitable to do this xform.
10619   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10620     bool isAddressTaken = false;
10621     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10622          UI != E; ++UI) {
10623       if (isa<LoadInst>(UI)) continue;
10624       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10625         // If storing TO the alloca, then the address isn't taken.
10626         if (SI->getOperand(1) == AI) continue;
10627       }
10628       isAddressTaken = true;
10629       break;
10630     }
10631     
10632     if (!isAddressTaken && AI->isStaticAlloca())
10633       return false;
10634   }
10635   
10636   // If this load is a load from a GEP with a constant offset from an alloca,
10637   // then we don't want to sink it.  In its present form, it will be
10638   // load [constant stack offset].  Sinking it will cause us to have to
10639   // materialize the stack addresses in each predecessor in a register only to
10640   // do a shared load from register in the successor.
10641   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10642     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10643       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10644         return false;
10645   
10646   return true;
10647 }
10648
10649
10650 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10651 // operator and they all are only used by the PHI, PHI together their
10652 // inputs, and do the operation once, to the result of the PHI.
10653 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10654   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10655
10656   // Scan the instruction, looking for input operations that can be folded away.
10657   // If all input operands to the phi are the same instruction (e.g. a cast from
10658   // the same type or "+42") we can pull the operation through the PHI, reducing
10659   // code size and simplifying code.
10660   Constant *ConstantOp = 0;
10661   const Type *CastSrcTy = 0;
10662   bool isVolatile = false;
10663   if (isa<CastInst>(FirstInst)) {
10664     CastSrcTy = FirstInst->getOperand(0)->getType();
10665   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10666     // Can fold binop, compare or shift here if the RHS is a constant, 
10667     // otherwise call FoldPHIArgBinOpIntoPHI.
10668     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10669     if (ConstantOp == 0)
10670       return FoldPHIArgBinOpIntoPHI(PN);
10671   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10672     isVolatile = LI->isVolatile();
10673     // We can't sink the load if the loaded value could be modified between the
10674     // load and the PHI.
10675     if (LI->getParent() != PN.getIncomingBlock(0) ||
10676         !isSafeAndProfitableToSinkLoad(LI))
10677       return 0;
10678     
10679     // If the PHI is of volatile loads and the load block has multiple
10680     // successors, sinking it would remove a load of the volatile value from
10681     // the path through the other successor.
10682     if (isVolatile &&
10683         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10684       return 0;
10685     
10686   } else if (isa<GetElementPtrInst>(FirstInst)) {
10687     return FoldPHIArgGEPIntoPHI(PN);
10688   } else {
10689     return 0;  // Cannot fold this operation.
10690   }
10691
10692   // Check to see if all arguments are the same operation.
10693   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10694     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10695     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10696     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10697       return 0;
10698     if (CastSrcTy) {
10699       if (I->getOperand(0)->getType() != CastSrcTy)
10700         return 0;  // Cast operation must match.
10701     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10702       // We can't sink the load if the loaded value could be modified between 
10703       // the load and the PHI.
10704       if (LI->isVolatile() != isVolatile ||
10705           LI->getParent() != PN.getIncomingBlock(i) ||
10706           !isSafeAndProfitableToSinkLoad(LI))
10707         return 0;
10708       
10709       // If the PHI is of volatile loads and the load block has multiple
10710       // successors, sinking it would remove a load of the volatile value from
10711       // the path through the other successor.
10712       if (isVolatile &&
10713           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10714         return 0;
10715       
10716     } else if (I->getOperand(1) != ConstantOp) {
10717       return 0;
10718     }
10719   }
10720
10721   // Okay, they are all the same operation.  Create a new PHI node of the
10722   // correct type, and PHI together all of the LHS's of the instructions.
10723   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10724                                    PN.getName()+".in");
10725   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10726
10727   Value *InVal = FirstInst->getOperand(0);
10728   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10729
10730   // Add all operands to the new PHI.
10731   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10732     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10733     if (NewInVal != InVal)
10734       InVal = 0;
10735     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10736   }
10737
10738   Value *PhiVal;
10739   if (InVal) {
10740     // The new PHI unions all of the same values together.  This is really
10741     // common, so we handle it intelligently here for compile-time speed.
10742     PhiVal = InVal;
10743     delete NewPN;
10744   } else {
10745     InsertNewInstBefore(NewPN, PN);
10746     PhiVal = NewPN;
10747   }
10748
10749   // Insert and return the new operation.
10750   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10751     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10752   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10753     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10754   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10755     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10756                            PhiVal, ConstantOp);
10757   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10758   
10759   // If this was a volatile load that we are merging, make sure to loop through
10760   // and mark all the input loads as non-volatile.  If we don't do this, we will
10761   // insert a new volatile load and the old ones will not be deletable.
10762   if (isVolatile)
10763     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10764       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10765   
10766   return new LoadInst(PhiVal, "", isVolatile);
10767 }
10768
10769 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10770 /// that is dead.
10771 static bool DeadPHICycle(PHINode *PN,
10772                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10773   if (PN->use_empty()) return true;
10774   if (!PN->hasOneUse()) return false;
10775
10776   // Remember this node, and if we find the cycle, return.
10777   if (!PotentiallyDeadPHIs.insert(PN))
10778     return true;
10779   
10780   // Don't scan crazily complex things.
10781   if (PotentiallyDeadPHIs.size() == 16)
10782     return false;
10783
10784   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10785     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10786
10787   return false;
10788 }
10789
10790 /// PHIsEqualValue - Return true if this phi node is always equal to
10791 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10792 ///   z = some value; x = phi (y, z); y = phi (x, z)
10793 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10794                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10795   // See if we already saw this PHI node.
10796   if (!ValueEqualPHIs.insert(PN))
10797     return true;
10798   
10799   // Don't scan crazily complex things.
10800   if (ValueEqualPHIs.size() == 16)
10801     return false;
10802  
10803   // Scan the operands to see if they are either phi nodes or are equal to
10804   // the value.
10805   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10806     Value *Op = PN->getIncomingValue(i);
10807     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10808       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10809         return false;
10810     } else if (Op != NonPhiInVal)
10811       return false;
10812   }
10813   
10814   return true;
10815 }
10816
10817
10818 // PHINode simplification
10819 //
10820 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10821   // If LCSSA is around, don't mess with Phi nodes
10822   if (MustPreserveLCSSA) return 0;
10823   
10824   if (Value *V = PN.hasConstantValue())
10825     return ReplaceInstUsesWith(PN, V);
10826
10827   // If all PHI operands are the same operation, pull them through the PHI,
10828   // reducing code size.
10829   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10830       isa<Instruction>(PN.getIncomingValue(1)) &&
10831       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10832       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10833       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10834       // than themselves more than once.
10835       PN.getIncomingValue(0)->hasOneUse())
10836     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10837       return Result;
10838
10839   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10840   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10841   // PHI)... break the cycle.
10842   if (PN.hasOneUse()) {
10843     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10844     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10845       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10846       PotentiallyDeadPHIs.insert(&PN);
10847       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10848         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10849     }
10850    
10851     // If this phi has a single use, and if that use just computes a value for
10852     // the next iteration of a loop, delete the phi.  This occurs with unused
10853     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10854     // common case here is good because the only other things that catch this
10855     // are induction variable analysis (sometimes) and ADCE, which is only run
10856     // late.
10857     if (PHIUser->hasOneUse() &&
10858         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10859         PHIUser->use_back() == &PN) {
10860       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10861     }
10862   }
10863
10864   // We sometimes end up with phi cycles that non-obviously end up being the
10865   // same value, for example:
10866   //   z = some value; x = phi (y, z); y = phi (x, z)
10867   // where the phi nodes don't necessarily need to be in the same block.  Do a
10868   // quick check to see if the PHI node only contains a single non-phi value, if
10869   // so, scan to see if the phi cycle is actually equal to that value.
10870   {
10871     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10872     // Scan for the first non-phi operand.
10873     while (InValNo != NumOperandVals && 
10874            isa<PHINode>(PN.getIncomingValue(InValNo)))
10875       ++InValNo;
10876
10877     if (InValNo != NumOperandVals) {
10878       Value *NonPhiInVal = PN.getOperand(InValNo);
10879       
10880       // Scan the rest of the operands to see if there are any conflicts, if so
10881       // there is no need to recursively scan other phis.
10882       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10883         Value *OpVal = PN.getIncomingValue(InValNo);
10884         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10885           break;
10886       }
10887       
10888       // If we scanned over all operands, then we have one unique value plus
10889       // phi values.  Scan PHI nodes to see if they all merge in each other or
10890       // the value.
10891       if (InValNo == NumOperandVals) {
10892         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10893         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10894           return ReplaceInstUsesWith(PN, NonPhiInVal);
10895       }
10896     }
10897   }
10898   return 0;
10899 }
10900
10901 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10902   Value *PtrOp = GEP.getOperand(0);
10903   // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
10904   if (GEP.getNumOperands() == 1)
10905     return ReplaceInstUsesWith(GEP, PtrOp);
10906
10907   if (isa<UndefValue>(GEP.getOperand(0)))
10908     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10909
10910   bool HasZeroPointerIndex = false;
10911   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10912     HasZeroPointerIndex = C->isNullValue();
10913
10914   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10915     return ReplaceInstUsesWith(GEP, PtrOp);
10916
10917   // Eliminate unneeded casts for indices.
10918   if (TD) {
10919     bool MadeChange = false;
10920     unsigned PtrSize = TD->getPointerSizeInBits();
10921     
10922     gep_type_iterator GTI = gep_type_begin(GEP);
10923     for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10924          I != E; ++I, ++GTI) {
10925       if (!isa<SequentialType>(*GTI)) continue;
10926       
10927       // If we are using a wider index than needed for this platform, shrink it
10928       // to what we need.  If narrower, sign-extend it to what we need.  This
10929       // explicit cast can make subsequent optimizations more obvious.
10930       unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
10931       if (OpBits == PtrSize)
10932         continue;
10933       
10934       *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
10935       MadeChange = true;
10936     }
10937     if (MadeChange) return &GEP;
10938   }
10939
10940   // Combine Indices - If the source pointer to this getelementptr instruction
10941   // is a getelementptr instruction, combine the indices of the two
10942   // getelementptr instructions into a single instruction.
10943   //
10944   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
10945     // Note that if our source is a gep chain itself that we wait for that
10946     // chain to be resolved before we perform this transformation.  This
10947     // avoids us creating a TON of code in some cases.
10948     //
10949     if (GetElementPtrInst *SrcGEP =
10950           dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10951       if (SrcGEP->getNumOperands() == 2)
10952         return 0;   // Wait until our source is folded to completion.
10953
10954     SmallVector<Value*, 8> Indices;
10955
10956     // Find out whether the last index in the source GEP is a sequential idx.
10957     bool EndsWithSequential = false;
10958     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10959          I != E; ++I)
10960       EndsWithSequential = !isa<StructType>(*I);
10961
10962     // Can we combine the two pointer arithmetics offsets?
10963     if (EndsWithSequential) {
10964       // Replace: gep (gep %P, long B), long A, ...
10965       // With:    T = long A+B; gep %P, T, ...
10966       //
10967       Value *Sum;
10968       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10969       Value *GO1 = GEP.getOperand(1);
10970       if (SO1 == Constant::getNullValue(SO1->getType())) {
10971         Sum = GO1;
10972       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10973         Sum = SO1;
10974       } else {
10975         // If they aren't the same type, then the input hasn't been processed
10976         // by the loop above yet (which canonicalizes sequential index types to
10977         // intptr_t).  Just avoid transforming this until the input has been
10978         // normalized.
10979         if (SO1->getType() != GO1->getType())
10980           return 0;
10981         Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10982       }
10983
10984       // Update the GEP in place if possible.
10985       if (Src->getNumOperands() == 2) {
10986         GEP.setOperand(0, Src->getOperand(0));
10987         GEP.setOperand(1, Sum);
10988         return &GEP;
10989       }
10990       Indices.append(Src->op_begin()+1, Src->op_end()-1);
10991       Indices.push_back(Sum);
10992       Indices.append(GEP.op_begin()+2, GEP.op_end());
10993     } else if (isa<Constant>(*GEP.idx_begin()) &&
10994                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10995                Src->getNumOperands() != 1) {
10996       // Otherwise we can do the fold if the first index of the GEP is a zero
10997       Indices.append(Src->op_begin()+1, Src->op_end());
10998       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
10999     }
11000
11001     if (!Indices.empty())
11002       return (cast<GEPOperator>(&GEP)->isInBounds() &&
11003               Src->isInBounds()) ?
11004         GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11005                                           Indices.end(), GEP.getName()) :
11006         GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
11007                                   Indices.end(), GEP.getName());
11008   }
11009   
11010   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11011   if (Value *X = getBitCastOperand(PtrOp)) {
11012     assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
11013
11014     // If the input bitcast is actually "bitcast(bitcast(x))", then we don't 
11015     // want to change the gep until the bitcasts are eliminated.
11016     if (getBitCastOperand(X)) {
11017       Worklist.AddValue(PtrOp);
11018       return 0;
11019     }
11020     
11021     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11022     // into     : GEP [10 x i8]* X, i32 0, ...
11023     //
11024     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11025     //           into     : GEP i8* X, ...
11026     // 
11027     // This occurs when the program declares an array extern like "int X[];"
11028     if (HasZeroPointerIndex) {
11029       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11030       const PointerType *XTy = cast<PointerType>(X->getType());
11031       if (const ArrayType *CATy =
11032           dyn_cast<ArrayType>(CPTy->getElementType())) {
11033         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11034         if (CATy->getElementType() == XTy->getElementType()) {
11035           // -> GEP i8* X, ...
11036           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11037           return cast<GEPOperator>(&GEP)->isInBounds() ?
11038             GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11039                                               GEP.getName()) :
11040             GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11041                                       GEP.getName());
11042         }
11043         
11044         if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
11045           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11046           if (CATy->getElementType() == XATy->getElementType()) {
11047             // -> GEP [10 x i8]* X, i32 0, ...
11048             // At this point, we know that the cast source type is a pointer
11049             // to an array of the same type as the destination pointer
11050             // array.  Because the array type is never stepped over (there
11051             // is a leading zero) we can fold the cast into this GEP.
11052             GEP.setOperand(0, X);
11053             return &GEP;
11054           }
11055         }
11056       }
11057     } else if (GEP.getNumOperands() == 2) {
11058       // Transform things like:
11059       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11060       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11061       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11062       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11063       if (TD && isa<ArrayType>(SrcElTy) &&
11064           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11065           TD->getTypeAllocSize(ResElTy)) {
11066         Value *Idx[2];
11067         Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11068         Idx[1] = GEP.getOperand(1);
11069         Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11070           Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11071           Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11072         // V and GEP are both pointer types --> BitCast
11073         return new BitCastInst(NewGEP, GEP.getType());
11074       }
11075       
11076       // Transform things like:
11077       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11078       //   (where tmp = 8*tmp2) into:
11079       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11080       
11081       if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
11082         uint64_t ArrayEltSize =
11083             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11084         
11085         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11086         // allow either a mul, shift, or constant here.
11087         Value *NewIdx = 0;
11088         ConstantInt *Scale = 0;
11089         if (ArrayEltSize == 1) {
11090           NewIdx = GEP.getOperand(1);
11091           Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11092         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11093           NewIdx = ConstantInt::get(CI->getType(), 1);
11094           Scale = CI;
11095         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11096           if (Inst->getOpcode() == Instruction::Shl &&
11097               isa<ConstantInt>(Inst->getOperand(1))) {
11098             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11099             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11100             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11101                                      1ULL << ShAmtVal);
11102             NewIdx = Inst->getOperand(0);
11103           } else if (Inst->getOpcode() == Instruction::Mul &&
11104                      isa<ConstantInt>(Inst->getOperand(1))) {
11105             Scale = cast<ConstantInt>(Inst->getOperand(1));
11106             NewIdx = Inst->getOperand(0);
11107           }
11108         }
11109         
11110         // If the index will be to exactly the right offset with the scale taken
11111         // out, perform the transformation. Note, we don't know whether Scale is
11112         // signed or not. We'll use unsigned version of division/modulo
11113         // operation after making sure Scale doesn't have the sign bit set.
11114         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11115             Scale->getZExtValue() % ArrayEltSize == 0) {
11116           Scale = ConstantInt::get(Scale->getType(),
11117                                    Scale->getZExtValue() / ArrayEltSize);
11118           if (Scale->getZExtValue() != 1) {
11119             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11120                                                        false /*ZExt*/);
11121             NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
11122           }
11123
11124           // Insert the new GEP instruction.
11125           Value *Idx[2];
11126           Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11127           Idx[1] = NewIdx;
11128           Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11129             Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11130             Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11131           // The NewGEP must be pointer typed, so must the old one -> BitCast
11132           return new BitCastInst(NewGEP, GEP.getType());
11133         }
11134       }
11135     }
11136   }
11137   
11138   /// See if we can simplify:
11139   ///   X = bitcast A* to B*
11140   ///   Y = gep X, <...constant indices...>
11141   /// into a gep of the original struct.  This is important for SROA and alias
11142   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11143   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11144     if (TD &&
11145         !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11146       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11147       // a constant back from EmitGEPOffset.
11148       ConstantInt *OffsetV =
11149                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11150       int64_t Offset = OffsetV->getSExtValue();
11151       
11152       // If this GEP instruction doesn't move the pointer, just replace the GEP
11153       // with a bitcast of the real input to the dest type.
11154       if (Offset == 0) {
11155         // If the bitcast is of an allocation, and the allocation will be
11156         // converted to match the type of the cast, don't touch this.
11157         if (isa<AllocationInst>(BCI->getOperand(0)) ||
11158             isMalloc(BCI->getOperand(0))) {
11159           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11160           if (Instruction *I = visitBitCast(*BCI)) {
11161             if (I != BCI) {
11162               I->takeName(BCI);
11163               BCI->getParent()->getInstList().insert(BCI, I);
11164               ReplaceInstUsesWith(*BCI, I);
11165             }
11166             return &GEP;
11167           }
11168         }
11169         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11170       }
11171       
11172       // Otherwise, if the offset is non-zero, we need to find out if there is a
11173       // field at Offset in 'A's type.  If so, we can pull the cast through the
11174       // GEP.
11175       SmallVector<Value*, 8> NewIndices;
11176       const Type *InTy =
11177         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11178       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11179         Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11180           Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11181                                      NewIndices.end()) :
11182           Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11183                              NewIndices.end());
11184         
11185         if (NGEP->getType() == GEP.getType())
11186           return ReplaceInstUsesWith(GEP, NGEP);
11187         NGEP->takeName(&GEP);
11188         return new BitCastInst(NGEP, GEP.getType());
11189       }
11190     }
11191   }    
11192     
11193   return 0;
11194 }
11195
11196 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11197   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11198   if (AI.isArrayAllocation()) {  // Check C != 1
11199     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11200       const Type *NewTy = 
11201         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11202       assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11203       AllocationInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
11204       New->setAlignment(AI.getAlignment());
11205
11206       // Scan to the end of the allocation instructions, to skip over a block of
11207       // allocas if possible...also skip interleaved debug info
11208       //
11209       BasicBlock::iterator It = New;
11210       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11211
11212       // Now that I is pointing to the first non-allocation-inst in the block,
11213       // insert our getelementptr instruction...
11214       //
11215       Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
11216       Value *Idx[2];
11217       Idx[0] = NullIdx;
11218       Idx[1] = NullIdx;
11219       Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11220                                                    New->getName()+".sub", It);
11221
11222       // Now make everything use the getelementptr instead of the original
11223       // allocation.
11224       return ReplaceInstUsesWith(AI, V);
11225     } else if (isa<UndefValue>(AI.getArraySize())) {
11226       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11227     }
11228   }
11229
11230   if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11231     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11232     // Note that we only do this for alloca's, because malloc should allocate
11233     // and return a unique pointer, even for a zero byte allocation.
11234     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11235       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11236
11237     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11238     if (AI.getAlignment() == 0)
11239       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11240   }
11241
11242   return 0;
11243 }
11244
11245 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11246   Value *Op = FI.getOperand(0);
11247
11248   // free undef -> unreachable.
11249   if (isa<UndefValue>(Op)) {
11250     // Insert a new store to null because we cannot modify the CFG here.
11251     new StoreInst(ConstantInt::getTrue(*Context),
11252            UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
11253     return EraseInstFromFunction(FI);
11254   }
11255   
11256   // If we have 'free null' delete the instruction.  This can happen in stl code
11257   // when lots of inlining happens.
11258   if (isa<ConstantPointerNull>(Op))
11259     return EraseInstFromFunction(FI);
11260   
11261   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11262   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11263     FI.setOperand(0, CI->getOperand(0));
11264     return &FI;
11265   }
11266   
11267   // Change free (gep X, 0,0,0,0) into free(X)
11268   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11269     if (GEPI->hasAllZeroIndices()) {
11270       Worklist.Add(GEPI);
11271       FI.setOperand(0, GEPI->getOperand(0));
11272       return &FI;
11273     }
11274   }
11275   
11276   if (isMalloc(Op)) {
11277     if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11278       if (Op->hasOneUse() && CI->hasOneUse()) {
11279         EraseInstFromFunction(FI);
11280         EraseInstFromFunction(*CI);
11281         return EraseInstFromFunction(*cast<Instruction>(Op));
11282       }
11283     } else {
11284       // Op is a call to malloc
11285       if (Op->hasOneUse()) {
11286         EraseInstFromFunction(FI);
11287         return EraseInstFromFunction(*cast<Instruction>(Op));
11288       }
11289     }
11290   }
11291
11292   return 0;
11293 }
11294
11295
11296 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11297 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11298                                         const TargetData *TD) {
11299   User *CI = cast<User>(LI.getOperand(0));
11300   Value *CastOp = CI->getOperand(0);
11301   LLVMContext *Context = IC.getContext();
11302
11303   if (TD) {
11304     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11305       // Instead of loading constant c string, use corresponding integer value
11306       // directly if string length is small enough.
11307       std::string Str;
11308       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11309         unsigned len = Str.length();
11310         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11311         unsigned numBits = Ty->getPrimitiveSizeInBits();
11312         // Replace LI with immediate integer store.
11313         if ((numBits >> 3) == len + 1) {
11314           APInt StrVal(numBits, 0);
11315           APInt SingleChar(numBits, 0);
11316           if (TD->isLittleEndian()) {
11317             for (signed i = len-1; i >= 0; i--) {
11318               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11319               StrVal = (StrVal << 8) | SingleChar;
11320             }
11321           } else {
11322             for (unsigned i = 0; i < len; i++) {
11323               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11324               StrVal = (StrVal << 8) | SingleChar;
11325             }
11326             // Append NULL at the end.
11327             SingleChar = 0;
11328             StrVal = (StrVal << 8) | SingleChar;
11329           }
11330           Value *NL = ConstantInt::get(*Context, StrVal);
11331           return IC.ReplaceInstUsesWith(LI, NL);
11332         }
11333       }
11334     }
11335   }
11336
11337   const PointerType *DestTy = cast<PointerType>(CI->getType());
11338   const Type *DestPTy = DestTy->getElementType();
11339   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11340
11341     // If the address spaces don't match, don't eliminate the cast.
11342     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11343       return 0;
11344
11345     const Type *SrcPTy = SrcTy->getElementType();
11346
11347     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11348          isa<VectorType>(DestPTy)) {
11349       // If the source is an array, the code below will not succeed.  Check to
11350       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11351       // constants.
11352       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11353         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11354           if (ASrcTy->getNumElements() != 0) {
11355             Value *Idxs[2];
11356             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
11357             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11358             SrcTy = cast<PointerType>(CastOp->getType());
11359             SrcPTy = SrcTy->getElementType();
11360           }
11361
11362       if (IC.getTargetData() &&
11363           (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11364             isa<VectorType>(SrcPTy)) &&
11365           // Do not allow turning this into a load of an integer, which is then
11366           // casted to a pointer, this pessimizes pointer analysis a lot.
11367           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11368           IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11369                IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11370
11371         // Okay, we are casting from one integer or pointer type to another of
11372         // the same size.  Instead of casting the pointer before the load, cast
11373         // the result of the loaded value.
11374         Value *NewLoad = 
11375           IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
11376         // Now cast the result of the load.
11377         return new BitCastInst(NewLoad, LI.getType());
11378       }
11379     }
11380   }
11381   return 0;
11382 }
11383
11384 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11385   Value *Op = LI.getOperand(0);
11386
11387   // Attempt to improve the alignment.
11388   if (TD) {
11389     unsigned KnownAlign =
11390       GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11391     if (KnownAlign >
11392         (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11393                                   LI.getAlignment()))
11394       LI.setAlignment(KnownAlign);
11395   }
11396
11397   // load (cast X) --> cast (load X) iff safe.
11398   if (isa<CastInst>(Op))
11399     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11400       return Res;
11401
11402   // None of the following transforms are legal for volatile loads.
11403   if (LI.isVolatile()) return 0;
11404   
11405   // Do really simple store-to-load forwarding and load CSE, to catch cases
11406   // where there are several consequtive memory accesses to the same location,
11407   // separated by a few arithmetic operations.
11408   BasicBlock::iterator BBI = &LI;
11409   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11410     return ReplaceInstUsesWith(LI, AvailableVal);
11411
11412   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11413     const Value *GEPI0 = GEPI->getOperand(0);
11414     // TODO: Consider a target hook for valid address spaces for this xform.
11415     if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
11416       // Insert a new store to null instruction before the load to indicate
11417       // that this code is not reachable.  We do this instead of inserting
11418       // an unreachable instruction directly because we cannot modify the
11419       // CFG.
11420       new StoreInst(UndefValue::get(LI.getType()),
11421                     Constant::getNullValue(Op->getType()), &LI);
11422       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11423     }
11424   } 
11425
11426   if (Constant *C = dyn_cast<Constant>(Op)) {
11427     // load null/undef -> undef
11428     // TODO: Consider a target hook for valid address spaces for this xform.
11429     if (isa<UndefValue>(C) ||
11430         (C->isNullValue() && LI.getPointerAddressSpace() == 0)) {
11431       // Insert a new store to null instruction before the load to indicate that
11432       // this code is not reachable.  We do this instead of inserting an
11433       // unreachable instruction directly because we cannot modify the CFG.
11434       new StoreInst(UndefValue::get(LI.getType()),
11435                     Constant::getNullValue(Op->getType()), &LI);
11436       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11437     }
11438
11439     // Instcombine load (constant global) into the value loaded.
11440     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11441       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11442         return ReplaceInstUsesWith(LI, GV->getInitializer());
11443
11444     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11445     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11446       if (CE->getOpcode() == Instruction::GetElementPtr) {
11447         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11448           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11449             if (Constant *V = 
11450                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
11451               return ReplaceInstUsesWith(LI, V);
11452         if (CE->getOperand(0)->isNullValue()) {
11453           // Insert a new store to null instruction before the load to indicate
11454           // that this code is not reachable.  We do this instead of inserting
11455           // an unreachable instruction directly because we cannot modify the
11456           // CFG.
11457           new StoreInst(UndefValue::get(LI.getType()),
11458                         Constant::getNullValue(Op->getType()), &LI);
11459           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11460         }
11461
11462       } else if (CE->isCast()) {
11463         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11464           return Res;
11465       }
11466     }
11467   }
11468     
11469   // If this load comes from anywhere in a constant global, and if the global
11470   // is all undef or zero, we know what it loads.
11471   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11472     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11473       if (GV->getInitializer()->isNullValue())
11474         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11475       else if (isa<UndefValue>(GV->getInitializer()))
11476         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11477     }
11478   }
11479
11480   if (Op->hasOneUse()) {
11481     // Change select and PHI nodes to select values instead of addresses: this
11482     // helps alias analysis out a lot, allows many others simplifications, and
11483     // exposes redundancy in the code.
11484     //
11485     // Note that we cannot do the transformation unless we know that the
11486     // introduced loads cannot trap!  Something like this is valid as long as
11487     // the condition is always false: load (select bool %C, int* null, int* %G),
11488     // but it would not be valid if we transformed it to load from null
11489     // unconditionally.
11490     //
11491     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11492       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11493       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11494           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11495         Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11496                                         SI->getOperand(1)->getName()+".val");
11497         Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11498                                         SI->getOperand(2)->getName()+".val");
11499         return SelectInst::Create(SI->getCondition(), V1, V2);
11500       }
11501
11502       // load (select (cond, null, P)) -> load P
11503       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11504         if (C->isNullValue()) {
11505           LI.setOperand(0, SI->getOperand(2));
11506           return &LI;
11507         }
11508
11509       // load (select (cond, P, null)) -> load P
11510       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11511         if (C->isNullValue()) {
11512           LI.setOperand(0, SI->getOperand(1));
11513           return &LI;
11514         }
11515     }
11516   }
11517   return 0;
11518 }
11519
11520 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11521 /// when possible.  This makes it generally easy to do alias analysis and/or
11522 /// SROA/mem2reg of the memory object.
11523 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11524   User *CI = cast<User>(SI.getOperand(1));
11525   Value *CastOp = CI->getOperand(0);
11526
11527   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11528   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11529   if (SrcTy == 0) return 0;
11530   
11531   const Type *SrcPTy = SrcTy->getElementType();
11532
11533   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11534     return 0;
11535   
11536   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11537   /// to its first element.  This allows us to handle things like:
11538   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11539   /// on 32-bit hosts.
11540   SmallVector<Value*, 4> NewGEPIndices;
11541   
11542   // If the source is an array, the code below will not succeed.  Check to
11543   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11544   // constants.
11545   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11546     // Index through pointer.
11547     Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
11548     NewGEPIndices.push_back(Zero);
11549     
11550     while (1) {
11551       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11552         if (!STy->getNumElements()) /* Struct can be empty {} */
11553           break;
11554         NewGEPIndices.push_back(Zero);
11555         SrcPTy = STy->getElementType(0);
11556       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11557         NewGEPIndices.push_back(Zero);
11558         SrcPTy = ATy->getElementType();
11559       } else {
11560         break;
11561       }
11562     }
11563     
11564     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11565   }
11566
11567   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11568     return 0;
11569   
11570   // If the pointers point into different address spaces or if they point to
11571   // values with different sizes, we can't do the transformation.
11572   if (!IC.getTargetData() ||
11573       SrcTy->getAddressSpace() != 
11574         cast<PointerType>(CI->getType())->getAddressSpace() ||
11575       IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11576       IC.getTargetData()->getTypeSizeInBits(DestPTy))
11577     return 0;
11578
11579   // Okay, we are casting from one integer or pointer type to another of
11580   // the same size.  Instead of casting the pointer before 
11581   // the store, cast the value to be stored.
11582   Value *NewCast;
11583   Value *SIOp0 = SI.getOperand(0);
11584   Instruction::CastOps opcode = Instruction::BitCast;
11585   const Type* CastSrcTy = SIOp0->getType();
11586   const Type* CastDstTy = SrcPTy;
11587   if (isa<PointerType>(CastDstTy)) {
11588     if (CastSrcTy->isInteger())
11589       opcode = Instruction::IntToPtr;
11590   } else if (isa<IntegerType>(CastDstTy)) {
11591     if (isa<PointerType>(SIOp0->getType()))
11592       opcode = Instruction::PtrToInt;
11593   }
11594   
11595   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11596   // emit a GEP to index into its first field.
11597   if (!NewGEPIndices.empty())
11598     CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11599                                            NewGEPIndices.end());
11600   
11601   NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11602                                    SIOp0->getName()+".c");
11603   return new StoreInst(NewCast, CastOp);
11604 }
11605
11606 /// equivalentAddressValues - Test if A and B will obviously have the same
11607 /// value. This includes recognizing that %t0 and %t1 will have the same
11608 /// value in code like this:
11609 ///   %t0 = getelementptr \@a, 0, 3
11610 ///   store i32 0, i32* %t0
11611 ///   %t1 = getelementptr \@a, 0, 3
11612 ///   %t2 = load i32* %t1
11613 ///
11614 static bool equivalentAddressValues(Value *A, Value *B) {
11615   // Test if the values are trivially equivalent.
11616   if (A == B) return true;
11617   
11618   // Test if the values come form identical arithmetic instructions.
11619   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11620   // its only used to compare two uses within the same basic block, which
11621   // means that they'll always either have the same value or one of them
11622   // will have an undefined value.
11623   if (isa<BinaryOperator>(A) ||
11624       isa<CastInst>(A) ||
11625       isa<PHINode>(A) ||
11626       isa<GetElementPtrInst>(A))
11627     if (Instruction *BI = dyn_cast<Instruction>(B))
11628       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
11629         return true;
11630   
11631   // Otherwise they may not be equivalent.
11632   return false;
11633 }
11634
11635 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11636 // return the llvm.dbg.declare.
11637 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11638   if (!V->hasNUses(2))
11639     return 0;
11640   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11641        UI != E; ++UI) {
11642     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11643       return DI;
11644     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11645       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11646         return DI;
11647       }
11648   }
11649   return 0;
11650 }
11651
11652 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11653   Value *Val = SI.getOperand(0);
11654   Value *Ptr = SI.getOperand(1);
11655
11656   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11657     EraseInstFromFunction(SI);
11658     ++NumCombined;
11659     return 0;
11660   }
11661   
11662   // If the RHS is an alloca with a single use, zapify the store, making the
11663   // alloca dead.
11664   // If the RHS is an alloca with a two uses, the other one being a 
11665   // llvm.dbg.declare, zapify the store and the declare, making the
11666   // alloca dead.  We must do this to prevent declare's from affecting
11667   // codegen.
11668   if (!SI.isVolatile()) {
11669     if (Ptr->hasOneUse()) {
11670       if (isa<AllocaInst>(Ptr)) {
11671         EraseInstFromFunction(SI);
11672         ++NumCombined;
11673         return 0;
11674       }
11675       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11676         if (isa<AllocaInst>(GEP->getOperand(0))) {
11677           if (GEP->getOperand(0)->hasOneUse()) {
11678             EraseInstFromFunction(SI);
11679             ++NumCombined;
11680             return 0;
11681           }
11682           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11683             EraseInstFromFunction(*DI);
11684             EraseInstFromFunction(SI);
11685             ++NumCombined;
11686             return 0;
11687           }
11688         }
11689       }
11690     }
11691     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11692       EraseInstFromFunction(*DI);
11693       EraseInstFromFunction(SI);
11694       ++NumCombined;
11695       return 0;
11696     }
11697   }
11698
11699   // Attempt to improve the alignment.
11700   if (TD) {
11701     unsigned KnownAlign =
11702       GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11703     if (KnownAlign >
11704         (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11705                                   SI.getAlignment()))
11706       SI.setAlignment(KnownAlign);
11707   }
11708
11709   // Do really simple DSE, to catch cases where there are several consecutive
11710   // stores to the same location, separated by a few arithmetic operations. This
11711   // situation often occurs with bitfield accesses.
11712   BasicBlock::iterator BBI = &SI;
11713   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11714        --ScanInsts) {
11715     --BBI;
11716     // Don't count debug info directives, lest they affect codegen,
11717     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11718     // It is necessary for correctness to skip those that feed into a
11719     // llvm.dbg.declare, as these are not present when debugging is off.
11720     if (isa<DbgInfoIntrinsic>(BBI) ||
11721         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11722       ScanInsts++;
11723       continue;
11724     }    
11725     
11726     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11727       // Prev store isn't volatile, and stores to the same location?
11728       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11729                                                           SI.getOperand(1))) {
11730         ++NumDeadStore;
11731         ++BBI;
11732         EraseInstFromFunction(*PrevSI);
11733         continue;
11734       }
11735       break;
11736     }
11737     
11738     // If this is a load, we have to stop.  However, if the loaded value is from
11739     // the pointer we're loading and is producing the pointer we're storing,
11740     // then *this* store is dead (X = load P; store X -> P).
11741     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11742       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11743           !SI.isVolatile()) {
11744         EraseInstFromFunction(SI);
11745         ++NumCombined;
11746         return 0;
11747       }
11748       // Otherwise, this is a load from some other location.  Stores before it
11749       // may not be dead.
11750       break;
11751     }
11752     
11753     // Don't skip over loads or things that can modify memory.
11754     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11755       break;
11756   }
11757   
11758   
11759   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11760
11761   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11762   if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
11763     if (!isa<UndefValue>(Val)) {
11764       SI.setOperand(0, UndefValue::get(Val->getType()));
11765       if (Instruction *U = dyn_cast<Instruction>(Val))
11766         Worklist.Add(U);  // Dropped a use.
11767       ++NumCombined;
11768     }
11769     return 0;  // Do not modify these!
11770   }
11771
11772   // store undef, Ptr -> noop
11773   if (isa<UndefValue>(Val)) {
11774     EraseInstFromFunction(SI);
11775     ++NumCombined;
11776     return 0;
11777   }
11778
11779   // If the pointer destination is a cast, see if we can fold the cast into the
11780   // source instead.
11781   if (isa<CastInst>(Ptr))
11782     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11783       return Res;
11784   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11785     if (CE->isCast())
11786       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11787         return Res;
11788
11789   
11790   // If this store is the last instruction in the basic block (possibly
11791   // excepting debug info instructions and the pointer bitcasts that feed
11792   // into them), and if the block ends with an unconditional branch, try
11793   // to move it to the successor block.
11794   BBI = &SI; 
11795   do {
11796     ++BBI;
11797   } while (isa<DbgInfoIntrinsic>(BBI) ||
11798            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11799   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11800     if (BI->isUnconditional())
11801       if (SimplifyStoreAtEndOfBlock(SI))
11802         return 0;  // xform done!
11803   
11804   return 0;
11805 }
11806
11807 /// SimplifyStoreAtEndOfBlock - Turn things like:
11808 ///   if () { *P = v1; } else { *P = v2 }
11809 /// into a phi node with a store in the successor.
11810 ///
11811 /// Simplify things like:
11812 ///   *P = v1; if () { *P = v2; }
11813 /// into a phi node with a store in the successor.
11814 ///
11815 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11816   BasicBlock *StoreBB = SI.getParent();
11817   
11818   // Check to see if the successor block has exactly two incoming edges.  If
11819   // so, see if the other predecessor contains a store to the same location.
11820   // if so, insert a PHI node (if needed) and move the stores down.
11821   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11822   
11823   // Determine whether Dest has exactly two predecessors and, if so, compute
11824   // the other predecessor.
11825   pred_iterator PI = pred_begin(DestBB);
11826   BasicBlock *OtherBB = 0;
11827   if (*PI != StoreBB)
11828     OtherBB = *PI;
11829   ++PI;
11830   if (PI == pred_end(DestBB))
11831     return false;
11832   
11833   if (*PI != StoreBB) {
11834     if (OtherBB)
11835       return false;
11836     OtherBB = *PI;
11837   }
11838   if (++PI != pred_end(DestBB))
11839     return false;
11840
11841   // Bail out if all the relevant blocks aren't distinct (this can happen,
11842   // for example, if SI is in an infinite loop)
11843   if (StoreBB == DestBB || OtherBB == DestBB)
11844     return false;
11845
11846   // Verify that the other block ends in a branch and is not otherwise empty.
11847   BasicBlock::iterator BBI = OtherBB->getTerminator();
11848   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11849   if (!OtherBr || BBI == OtherBB->begin())
11850     return false;
11851   
11852   // If the other block ends in an unconditional branch, check for the 'if then
11853   // else' case.  there is an instruction before the branch.
11854   StoreInst *OtherStore = 0;
11855   if (OtherBr->isUnconditional()) {
11856     --BBI;
11857     // Skip over debugging info.
11858     while (isa<DbgInfoIntrinsic>(BBI) ||
11859            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11860       if (BBI==OtherBB->begin())
11861         return false;
11862       --BBI;
11863     }
11864     // If this isn't a store, or isn't a store to the same location, bail out.
11865     OtherStore = dyn_cast<StoreInst>(BBI);
11866     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11867       return false;
11868   } else {
11869     // Otherwise, the other block ended with a conditional branch. If one of the
11870     // destinations is StoreBB, then we have the if/then case.
11871     if (OtherBr->getSuccessor(0) != StoreBB && 
11872         OtherBr->getSuccessor(1) != StoreBB)
11873       return false;
11874     
11875     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11876     // if/then triangle.  See if there is a store to the same ptr as SI that
11877     // lives in OtherBB.
11878     for (;; --BBI) {
11879       // Check to see if we find the matching store.
11880       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11881         if (OtherStore->getOperand(1) != SI.getOperand(1))
11882           return false;
11883         break;
11884       }
11885       // If we find something that may be using or overwriting the stored
11886       // value, or if we run out of instructions, we can't do the xform.
11887       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11888           BBI == OtherBB->begin())
11889         return false;
11890     }
11891     
11892     // In order to eliminate the store in OtherBr, we have to
11893     // make sure nothing reads or overwrites the stored value in
11894     // StoreBB.
11895     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11896       // FIXME: This should really be AA driven.
11897       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11898         return false;
11899     }
11900   }
11901   
11902   // Insert a PHI node now if we need it.
11903   Value *MergedVal = OtherStore->getOperand(0);
11904   if (MergedVal != SI.getOperand(0)) {
11905     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11906     PN->reserveOperandSpace(2);
11907     PN->addIncoming(SI.getOperand(0), SI.getParent());
11908     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11909     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11910   }
11911   
11912   // Advance to a place where it is safe to insert the new store and
11913   // insert it.
11914   BBI = DestBB->getFirstNonPHI();
11915   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11916                                     OtherStore->isVolatile()), *BBI);
11917   
11918   // Nuke the old stores.
11919   EraseInstFromFunction(SI);
11920   EraseInstFromFunction(*OtherStore);
11921   ++NumCombined;
11922   return true;
11923 }
11924
11925
11926 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11927   // Change br (not X), label True, label False to: br X, label False, True
11928   Value *X = 0;
11929   BasicBlock *TrueDest;
11930   BasicBlock *FalseDest;
11931   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11932       !isa<Constant>(X)) {
11933     // Swap Destinations and condition...
11934     BI.setCondition(X);
11935     BI.setSuccessor(0, FalseDest);
11936     BI.setSuccessor(1, TrueDest);
11937     return &BI;
11938   }
11939
11940   // Cannonicalize fcmp_one -> fcmp_oeq
11941   FCmpInst::Predicate FPred; Value *Y;
11942   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11943                              TrueDest, FalseDest)) &&
11944       BI.getCondition()->hasOneUse())
11945     if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11946         FPred == FCmpInst::FCMP_OGE) {
11947       FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11948       Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11949       
11950       // Swap Destinations and condition.
11951       BI.setSuccessor(0, FalseDest);
11952       BI.setSuccessor(1, TrueDest);
11953       Worklist.Add(Cond);
11954       return &BI;
11955     }
11956
11957   // Cannonicalize icmp_ne -> icmp_eq
11958   ICmpInst::Predicate IPred;
11959   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11960                       TrueDest, FalseDest)) &&
11961       BI.getCondition()->hasOneUse())
11962     if (IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
11963         IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11964         IPred == ICmpInst::ICMP_SGE) {
11965       ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11966       Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11967       // Swap Destinations and condition.
11968       BI.setSuccessor(0, FalseDest);
11969       BI.setSuccessor(1, TrueDest);
11970       Worklist.Add(Cond);
11971       return &BI;
11972     }
11973
11974   return 0;
11975 }
11976
11977 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11978   Value *Cond = SI.getCondition();
11979   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11980     if (I->getOpcode() == Instruction::Add)
11981       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11982         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11983         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11984           SI.setOperand(i,
11985                    ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11986                                                 AddRHS));
11987         SI.setOperand(0, I->getOperand(0));
11988         Worklist.Add(I);
11989         return &SI;
11990       }
11991   }
11992   return 0;
11993 }
11994
11995 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
11996   Value *Agg = EV.getAggregateOperand();
11997
11998   if (!EV.hasIndices())
11999     return ReplaceInstUsesWith(EV, Agg);
12000
12001   if (Constant *C = dyn_cast<Constant>(Agg)) {
12002     if (isa<UndefValue>(C))
12003       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12004       
12005     if (isa<ConstantAggregateZero>(C))
12006       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12007
12008     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12009       // Extract the element indexed by the first index out of the constant
12010       Value *V = C->getOperand(*EV.idx_begin());
12011       if (EV.getNumIndices() > 1)
12012         // Extract the remaining indices out of the constant indexed by the
12013         // first index
12014         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12015       else
12016         return ReplaceInstUsesWith(EV, V);
12017     }
12018     return 0; // Can't handle other constants
12019   } 
12020   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12021     // We're extracting from an insertvalue instruction, compare the indices
12022     const unsigned *exti, *exte, *insi, *inse;
12023     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12024          exte = EV.idx_end(), inse = IV->idx_end();
12025          exti != exte && insi != inse;
12026          ++exti, ++insi) {
12027       if (*insi != *exti)
12028         // The insert and extract both reference distinctly different elements.
12029         // This means the extract is not influenced by the insert, and we can
12030         // replace the aggregate operand of the extract with the aggregate
12031         // operand of the insert. i.e., replace
12032         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12033         // %E = extractvalue { i32, { i32 } } %I, 0
12034         // with
12035         // %E = extractvalue { i32, { i32 } } %A, 0
12036         return ExtractValueInst::Create(IV->getAggregateOperand(),
12037                                         EV.idx_begin(), EV.idx_end());
12038     }
12039     if (exti == exte && insi == inse)
12040       // Both iterators are at the end: Index lists are identical. Replace
12041       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12042       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12043       // with "i32 42"
12044       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12045     if (exti == exte) {
12046       // The extract list is a prefix of the insert list. i.e. replace
12047       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12048       // %E = extractvalue { i32, { i32 } } %I, 1
12049       // with
12050       // %X = extractvalue { i32, { i32 } } %A, 1
12051       // %E = insertvalue { i32 } %X, i32 42, 0
12052       // by switching the order of the insert and extract (though the
12053       // insertvalue should be left in, since it may have other uses).
12054       Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12055                                                  EV.idx_begin(), EV.idx_end());
12056       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12057                                      insi, inse);
12058     }
12059     if (insi == inse)
12060       // The insert list is a prefix of the extract list
12061       // We can simply remove the common indices from the extract and make it
12062       // operate on the inserted value instead of the insertvalue result.
12063       // i.e., replace
12064       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12065       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12066       // with
12067       // %E extractvalue { i32 } { i32 42 }, 0
12068       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12069                                       exti, exte);
12070   }
12071   // Can't simplify extracts from other values. Note that nested extracts are
12072   // already simplified implicitely by the above (extract ( extract (insert) )
12073   // will be translated into extract ( insert ( extract ) ) first and then just
12074   // the value inserted, if appropriate).
12075   return 0;
12076 }
12077
12078 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12079 /// is to leave as a vector operation.
12080 static bool CheapToScalarize(Value *V, bool isConstant) {
12081   if (isa<ConstantAggregateZero>(V)) 
12082     return true;
12083   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12084     if (isConstant) return true;
12085     // If all elts are the same, we can extract.
12086     Constant *Op0 = C->getOperand(0);
12087     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12088       if (C->getOperand(i) != Op0)
12089         return false;
12090     return true;
12091   }
12092   Instruction *I = dyn_cast<Instruction>(V);
12093   if (!I) return false;
12094   
12095   // Insert element gets simplified to the inserted element or is deleted if
12096   // this is constant idx extract element and its a constant idx insertelt.
12097   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12098       isa<ConstantInt>(I->getOperand(2)))
12099     return true;
12100   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12101     return true;
12102   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12103     if (BO->hasOneUse() &&
12104         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12105          CheapToScalarize(BO->getOperand(1), isConstant)))
12106       return true;
12107   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12108     if (CI->hasOneUse() &&
12109         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12110          CheapToScalarize(CI->getOperand(1), isConstant)))
12111       return true;
12112   
12113   return false;
12114 }
12115
12116 /// Read and decode a shufflevector mask.
12117 ///
12118 /// It turns undef elements into values that are larger than the number of
12119 /// elements in the input.
12120 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12121   unsigned NElts = SVI->getType()->getNumElements();
12122   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12123     return std::vector<unsigned>(NElts, 0);
12124   if (isa<UndefValue>(SVI->getOperand(2)))
12125     return std::vector<unsigned>(NElts, 2*NElts);
12126
12127   std::vector<unsigned> Result;
12128   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12129   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12130     if (isa<UndefValue>(*i))
12131       Result.push_back(NElts*2);  // undef -> 8
12132     else
12133       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12134   return Result;
12135 }
12136
12137 /// FindScalarElement - Given a vector and an element number, see if the scalar
12138 /// value is already around as a register, for example if it were inserted then
12139 /// extracted from the vector.
12140 static Value *FindScalarElement(Value *V, unsigned EltNo,
12141                                 LLVMContext *Context) {
12142   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12143   const VectorType *PTy = cast<VectorType>(V->getType());
12144   unsigned Width = PTy->getNumElements();
12145   if (EltNo >= Width)  // Out of range access.
12146     return UndefValue::get(PTy->getElementType());
12147   
12148   if (isa<UndefValue>(V))
12149     return UndefValue::get(PTy->getElementType());
12150   else if (isa<ConstantAggregateZero>(V))
12151     return Constant::getNullValue(PTy->getElementType());
12152   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12153     return CP->getOperand(EltNo);
12154   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12155     // If this is an insert to a variable element, we don't know what it is.
12156     if (!isa<ConstantInt>(III->getOperand(2))) 
12157       return 0;
12158     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12159     
12160     // If this is an insert to the element we are looking for, return the
12161     // inserted value.
12162     if (EltNo == IIElt) 
12163       return III->getOperand(1);
12164     
12165     // Otherwise, the insertelement doesn't modify the value, recurse on its
12166     // vector input.
12167     return FindScalarElement(III->getOperand(0), EltNo, Context);
12168   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12169     unsigned LHSWidth =
12170       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12171     unsigned InEl = getShuffleMask(SVI)[EltNo];
12172     if (InEl < LHSWidth)
12173       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12174     else if (InEl < LHSWidth*2)
12175       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12176     else
12177       return UndefValue::get(PTy->getElementType());
12178   }
12179   
12180   // Otherwise, we don't know.
12181   return 0;
12182 }
12183
12184 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12185   // If vector val is undef, replace extract with scalar undef.
12186   if (isa<UndefValue>(EI.getOperand(0)))
12187     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12188
12189   // If vector val is constant 0, replace extract with scalar 0.
12190   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12191     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12192   
12193   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12194     // If vector val is constant with all elements the same, replace EI with
12195     // that element. When the elements are not identical, we cannot replace yet
12196     // (we do that below, but only when the index is constant).
12197     Constant *op0 = C->getOperand(0);
12198     for (unsigned i = 1; i != C->getNumOperands(); ++i)
12199       if (C->getOperand(i) != op0) {
12200         op0 = 0; 
12201         break;
12202       }
12203     if (op0)
12204       return ReplaceInstUsesWith(EI, op0);
12205   }
12206   
12207   // If extracting a specified index from the vector, see if we can recursively
12208   // find a previously computed scalar that was inserted into the vector.
12209   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12210     unsigned IndexVal = IdxC->getZExtValue();
12211     unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
12212       
12213     // If this is extracting an invalid index, turn this into undef, to avoid
12214     // crashing the code below.
12215     if (IndexVal >= VectorWidth)
12216       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12217     
12218     // This instruction only demands the single element from the input vector.
12219     // If the input vector has a single use, simplify it based on this use
12220     // property.
12221     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12222       APInt UndefElts(VectorWidth, 0);
12223       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12224       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12225                                                 DemandedMask, UndefElts)) {
12226         EI.setOperand(0, V);
12227         return &EI;
12228       }
12229     }
12230     
12231     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12232       return ReplaceInstUsesWith(EI, Elt);
12233     
12234     // If the this extractelement is directly using a bitcast from a vector of
12235     // the same number of elements, see if we can find the source element from
12236     // it.  In this case, we will end up needing to bitcast the scalars.
12237     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12238       if (const VectorType *VT = 
12239               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12240         if (VT->getNumElements() == VectorWidth)
12241           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12242                                              IndexVal, Context))
12243             return new BitCastInst(Elt, EI.getType());
12244     }
12245   }
12246   
12247   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12248     // Push extractelement into predecessor operation if legal and
12249     // profitable to do so
12250     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12251       if (I->hasOneUse() &&
12252           CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12253         Value *newEI0 =
12254           Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12255                                         EI.getName()+".lhs");
12256         Value *newEI1 =
12257           Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12258                                         EI.getName()+".rhs");
12259         return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12260       }
12261     } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12262       // Extracting the inserted element?
12263       if (IE->getOperand(2) == EI.getOperand(1))
12264         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12265       // If the inserted and extracted elements are constants, they must not
12266       // be the same value, extract from the pre-inserted value instead.
12267       if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
12268         Worklist.AddValue(EI.getOperand(0));
12269         EI.setOperand(0, IE->getOperand(0));
12270         return &EI;
12271       }
12272     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12273       // If this is extracting an element from a shufflevector, figure out where
12274       // it came from and extract from the appropriate input element instead.
12275       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12276         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12277         Value *Src;
12278         unsigned LHSWidth =
12279           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12280
12281         if (SrcIdx < LHSWidth)
12282           Src = SVI->getOperand(0);
12283         else if (SrcIdx < LHSWidth*2) {
12284           SrcIdx -= LHSWidth;
12285           Src = SVI->getOperand(1);
12286         } else {
12287           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12288         }
12289         return ExtractElementInst::Create(Src,
12290                          ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12291                                           false));
12292       }
12293     }
12294     // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12295   }
12296   return 0;
12297 }
12298
12299 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12300 /// elements from either LHS or RHS, return the shuffle mask and true. 
12301 /// Otherwise, return false.
12302 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12303                                          std::vector<Constant*> &Mask,
12304                                          LLVMContext *Context) {
12305   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12306          "Invalid CollectSingleShuffleElements");
12307   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12308
12309   if (isa<UndefValue>(V)) {
12310     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12311     return true;
12312   } else if (V == LHS) {
12313     for (unsigned i = 0; i != NumElts; ++i)
12314       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12315     return true;
12316   } else if (V == RHS) {
12317     for (unsigned i = 0; i != NumElts; ++i)
12318       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
12319     return true;
12320   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12321     // If this is an insert of an extract from some other vector, include it.
12322     Value *VecOp    = IEI->getOperand(0);
12323     Value *ScalarOp = IEI->getOperand(1);
12324     Value *IdxOp    = IEI->getOperand(2);
12325     
12326     if (!isa<ConstantInt>(IdxOp))
12327       return false;
12328     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12329     
12330     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12331       // Okay, we can handle this if the vector we are insertinting into is
12332       // transitively ok.
12333       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12334         // If so, update the mask to reflect the inserted undef.
12335         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
12336         return true;
12337       }      
12338     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12339       if (isa<ConstantInt>(EI->getOperand(1)) &&
12340           EI->getOperand(0)->getType() == V->getType()) {
12341         unsigned ExtractedIdx =
12342           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12343         
12344         // This must be extracting from either LHS or RHS.
12345         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12346           // Okay, we can handle this if the vector we are insertinting into is
12347           // transitively ok.
12348           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12349             // If so, update the mask to reflect the inserted value.
12350             if (EI->getOperand(0) == LHS) {
12351               Mask[InsertedIdx % NumElts] = 
12352                  ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12353             } else {
12354               assert(EI->getOperand(0) == RHS);
12355               Mask[InsertedIdx % NumElts] = 
12356                 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
12357               
12358             }
12359             return true;
12360           }
12361         }
12362       }
12363     }
12364   }
12365   // TODO: Handle shufflevector here!
12366   
12367   return false;
12368 }
12369
12370 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12371 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12372 /// that computes V and the LHS value of the shuffle.
12373 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12374                                      Value *&RHS, LLVMContext *Context) {
12375   assert(isa<VectorType>(V->getType()) && 
12376          (RHS == 0 || V->getType() == RHS->getType()) &&
12377          "Invalid shuffle!");
12378   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12379
12380   if (isa<UndefValue>(V)) {
12381     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12382     return V;
12383   } else if (isa<ConstantAggregateZero>(V)) {
12384     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
12385     return V;
12386   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12387     // If this is an insert of an extract from some other vector, include it.
12388     Value *VecOp    = IEI->getOperand(0);
12389     Value *ScalarOp = IEI->getOperand(1);
12390     Value *IdxOp    = IEI->getOperand(2);
12391     
12392     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12393       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12394           EI->getOperand(0)->getType() == V->getType()) {
12395         unsigned ExtractedIdx =
12396           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12397         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12398         
12399         // Either the extracted from or inserted into vector must be RHSVec,
12400         // otherwise we'd end up with a shuffle of three inputs.
12401         if (EI->getOperand(0) == RHS || RHS == 0) {
12402           RHS = EI->getOperand(0);
12403           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12404           Mask[InsertedIdx % NumElts] = 
12405             ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
12406           return V;
12407         }
12408         
12409         if (VecOp == RHS) {
12410           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12411                                             RHS, Context);
12412           // Everything but the extracted element is replaced with the RHS.
12413           for (unsigned i = 0; i != NumElts; ++i) {
12414             if (i != InsertedIdx)
12415               Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
12416           }
12417           return V;
12418         }
12419         
12420         // If this insertelement is a chain that comes from exactly these two
12421         // vectors, return the vector and the effective shuffle.
12422         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12423                                          Context))
12424           return EI->getOperand(0);
12425         
12426       }
12427     }
12428   }
12429   // TODO: Handle shufflevector here!
12430   
12431   // Otherwise, can't do anything fancy.  Return an identity vector.
12432   for (unsigned i = 0; i != NumElts; ++i)
12433     Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12434   return V;
12435 }
12436
12437 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12438   Value *VecOp    = IE.getOperand(0);
12439   Value *ScalarOp = IE.getOperand(1);
12440   Value *IdxOp    = IE.getOperand(2);
12441   
12442   // Inserting an undef or into an undefined place, remove this.
12443   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12444     ReplaceInstUsesWith(IE, VecOp);
12445   
12446   // If the inserted element was extracted from some other vector, and if the 
12447   // indexes are constant, try to turn this into a shufflevector operation.
12448   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12449     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12450         EI->getOperand(0)->getType() == IE.getType()) {
12451       unsigned NumVectorElts = IE.getType()->getNumElements();
12452       unsigned ExtractedIdx =
12453         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12454       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12455       
12456       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12457         return ReplaceInstUsesWith(IE, VecOp);
12458       
12459       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12460         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12461       
12462       // If we are extracting a value from a vector, then inserting it right
12463       // back into the same place, just use the input vector.
12464       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12465         return ReplaceInstUsesWith(IE, VecOp);      
12466       
12467       // If this insertelement isn't used by some other insertelement, turn it
12468       // (and any insertelements it points to), into one big shuffle.
12469       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12470         std::vector<Constant*> Mask;
12471         Value *RHS = 0;
12472         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12473         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12474         // We now have a shuffle of LHS, RHS, Mask.
12475         return new ShuffleVectorInst(LHS, RHS,
12476                                      ConstantVector::get(Mask));
12477       }
12478     }
12479   }
12480
12481   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12482   APInt UndefElts(VWidth, 0);
12483   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12484   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12485     return &IE;
12486
12487   return 0;
12488 }
12489
12490
12491 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12492   Value *LHS = SVI.getOperand(0);
12493   Value *RHS = SVI.getOperand(1);
12494   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12495
12496   bool MadeChange = false;
12497
12498   // Undefined shuffle mask -> undefined value.
12499   if (isa<UndefValue>(SVI.getOperand(2)))
12500     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12501
12502   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12503
12504   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12505     return 0;
12506
12507   APInt UndefElts(VWidth, 0);
12508   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12509   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12510     LHS = SVI.getOperand(0);
12511     RHS = SVI.getOperand(1);
12512     MadeChange = true;
12513   }
12514   
12515   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12516   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12517   if (LHS == RHS || isa<UndefValue>(LHS)) {
12518     if (isa<UndefValue>(LHS) && LHS == RHS) {
12519       // shuffle(undef,undef,mask) -> undef.
12520       return ReplaceInstUsesWith(SVI, LHS);
12521     }
12522     
12523     // Remap any references to RHS to use LHS.
12524     std::vector<Constant*> Elts;
12525     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12526       if (Mask[i] >= 2*e)
12527         Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12528       else {
12529         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12530             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12531           Mask[i] = 2*e;     // Turn into undef.
12532           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12533         } else {
12534           Mask[i] = Mask[i] % e;  // Force to LHS.
12535           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
12536         }
12537       }
12538     }
12539     SVI.setOperand(0, SVI.getOperand(1));
12540     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12541     SVI.setOperand(2, ConstantVector::get(Elts));
12542     LHS = SVI.getOperand(0);
12543     RHS = SVI.getOperand(1);
12544     MadeChange = true;
12545   }
12546   
12547   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12548   bool isLHSID = true, isRHSID = true;
12549     
12550   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12551     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12552     // Is this an identity shuffle of the LHS value?
12553     isLHSID &= (Mask[i] == i);
12554       
12555     // Is this an identity shuffle of the RHS value?
12556     isRHSID &= (Mask[i]-e == i);
12557   }
12558
12559   // Eliminate identity shuffles.
12560   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12561   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12562   
12563   // If the LHS is a shufflevector itself, see if we can combine it with this
12564   // one without producing an unusual shuffle.  Here we are really conservative:
12565   // we are absolutely afraid of producing a shuffle mask not in the input
12566   // program, because the code gen may not be smart enough to turn a merged
12567   // shuffle into two specific shuffles: it may produce worse code.  As such,
12568   // we only merge two shuffles if the result is one of the two input shuffle
12569   // masks.  In this case, merging the shuffles just removes one instruction,
12570   // which we know is safe.  This is good for things like turning:
12571   // (splat(splat)) -> splat.
12572   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12573     if (isa<UndefValue>(RHS)) {
12574       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12575
12576       std::vector<unsigned> NewMask;
12577       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12578         if (Mask[i] >= 2*e)
12579           NewMask.push_back(2*e);
12580         else
12581           NewMask.push_back(LHSMask[Mask[i]]);
12582       
12583       // If the result mask is equal to the src shuffle or this shuffle mask, do
12584       // the replacement.
12585       if (NewMask == LHSMask || NewMask == Mask) {
12586         unsigned LHSInNElts =
12587           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12588         std::vector<Constant*> Elts;
12589         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12590           if (NewMask[i] >= LHSInNElts*2) {
12591             Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12592           } else {
12593             Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
12594           }
12595         }
12596         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12597                                      LHSSVI->getOperand(1),
12598                                      ConstantVector::get(Elts));
12599       }
12600     }
12601   }
12602
12603   return MadeChange ? &SVI : 0;
12604 }
12605
12606
12607
12608
12609 /// TryToSinkInstruction - Try to move the specified instruction from its
12610 /// current block into the beginning of DestBlock, which can only happen if it's
12611 /// safe to move the instruction past all of the instructions between it and the
12612 /// end of its block.
12613 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12614   assert(I->hasOneUse() && "Invariants didn't hold!");
12615
12616   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12617   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12618     return false;
12619
12620   // Do not sink alloca instructions out of the entry block.
12621   if (isa<AllocaInst>(I) && I->getParent() ==
12622         &DestBlock->getParent()->getEntryBlock())
12623     return false;
12624
12625   // We can only sink load instructions if there is nothing between the load and
12626   // the end of block that could change the value.
12627   if (I->mayReadFromMemory()) {
12628     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12629          Scan != E; ++Scan)
12630       if (Scan->mayWriteToMemory())
12631         return false;
12632   }
12633
12634   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12635
12636   CopyPrecedingStopPoint(I, InsertPos);
12637   I->moveBefore(InsertPos);
12638   ++NumSunkInst;
12639   return true;
12640 }
12641
12642
12643 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12644 /// all reachable code to the worklist.
12645 ///
12646 /// This has a couple of tricks to make the code faster and more powerful.  In
12647 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12648 /// them to the worklist (this significantly speeds up instcombine on code where
12649 /// many instructions are dead or constant).  Additionally, if we find a branch
12650 /// whose condition is a known constant, we only visit the reachable successors.
12651 ///
12652 static bool AddReachableCodeToWorklist(BasicBlock *BB, 
12653                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12654                                        InstCombiner &IC,
12655                                        const TargetData *TD) {
12656   bool MadeIRChange = false;
12657   SmallVector<BasicBlock*, 256> Worklist;
12658   Worklist.push_back(BB);
12659   
12660   std::vector<Instruction*> InstrsForInstCombineWorklist;
12661   InstrsForInstCombineWorklist.reserve(128);
12662
12663   SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
12664   
12665   while (!Worklist.empty()) {
12666     BB = Worklist.back();
12667     Worklist.pop_back();
12668     
12669     // We have now visited this block!  If we've already been here, ignore it.
12670     if (!Visited.insert(BB)) continue;
12671
12672     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12673       Instruction *Inst = BBI++;
12674       
12675       // DCE instruction if trivially dead.
12676       if (isInstructionTriviallyDead(Inst)) {
12677         ++NumDeadInst;
12678         DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
12679         Inst->eraseFromParent();
12680         continue;
12681       }
12682       
12683       // ConstantProp instruction if trivially constant.
12684       if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
12685         if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12686           DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12687                        << *Inst << '\n');
12688           Inst->replaceAllUsesWith(C);
12689           ++NumConstProp;
12690           Inst->eraseFromParent();
12691           continue;
12692         }
12693       
12694       
12695       
12696       if (TD) {
12697         // See if we can constant fold its operands.
12698         for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
12699              i != e; ++i) {
12700           ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
12701           if (CE == 0) continue;
12702           
12703           // If we already folded this constant, don't try again.
12704           if (!FoldedConstants.insert(CE))
12705             continue;
12706           
12707           Constant *NewC =
12708             ConstantFoldConstantExpression(CE, BB->getContext(), TD);
12709           if (NewC && NewC != CE) {
12710             *i = NewC;
12711             MadeIRChange = true;
12712           }
12713         }
12714       }
12715       
12716
12717       InstrsForInstCombineWorklist.push_back(Inst);
12718     }
12719
12720     // Recursively visit successors.  If this is a branch or switch on a
12721     // constant, only visit the reachable successor.
12722     TerminatorInst *TI = BB->getTerminator();
12723     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12724       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12725         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12726         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12727         Worklist.push_back(ReachableBB);
12728         continue;
12729       }
12730     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12731       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12732         // See if this is an explicit destination.
12733         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12734           if (SI->getCaseValue(i) == Cond) {
12735             BasicBlock *ReachableBB = SI->getSuccessor(i);
12736             Worklist.push_back(ReachableBB);
12737             continue;
12738           }
12739         
12740         // Otherwise it is the default destination.
12741         Worklist.push_back(SI->getSuccessor(0));
12742         continue;
12743       }
12744     }
12745     
12746     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12747       Worklist.push_back(TI->getSuccessor(i));
12748   }
12749   
12750   // Once we've found all of the instructions to add to instcombine's worklist,
12751   // add them in reverse order.  This way instcombine will visit from the top
12752   // of the function down.  This jives well with the way that it adds all uses
12753   // of instructions to the worklist after doing a transformation, thus avoiding
12754   // some N^2 behavior in pathological cases.
12755   IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
12756                               InstrsForInstCombineWorklist.size());
12757   
12758   return MadeIRChange;
12759 }
12760
12761 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12762   MadeIRChange = false;
12763   
12764   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12765         << F.getNameStr() << "\n");
12766
12767   {
12768     // Do a depth-first traversal of the function, populate the worklist with
12769     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12770     // track of which blocks we visit.
12771     SmallPtrSet<BasicBlock*, 64> Visited;
12772     MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12773
12774     // Do a quick scan over the function.  If we find any blocks that are
12775     // unreachable, remove any instructions inside of them.  This prevents
12776     // the instcombine code from having to deal with some bad special cases.
12777     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12778       if (!Visited.count(BB)) {
12779         Instruction *Term = BB->getTerminator();
12780         while (Term != BB->begin()) {   // Remove instrs bottom-up
12781           BasicBlock::iterator I = Term; --I;
12782
12783           DEBUG(errs() << "IC: DCE: " << *I << '\n');
12784           // A debug intrinsic shouldn't force another iteration if we weren't
12785           // going to do one without it.
12786           if (!isa<DbgInfoIntrinsic>(I)) {
12787             ++NumDeadInst;
12788             MadeIRChange = true;
12789           }
12790
12791           // If I is not void type then replaceAllUsesWith undef.
12792           // This allows ValueHandlers and custom metadata to adjust itself.
12793           if (!I->getType()->isVoidTy())
12794             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12795           I->eraseFromParent();
12796         }
12797       }
12798   }
12799
12800   while (!Worklist.isEmpty()) {
12801     Instruction *I = Worklist.RemoveOne();
12802     if (I == 0) continue;  // skip null values.
12803
12804     // Check to see if we can DCE the instruction.
12805     if (isInstructionTriviallyDead(I)) {
12806       DEBUG(errs() << "IC: DCE: " << *I << '\n');
12807       EraseInstFromFunction(*I);
12808       ++NumDeadInst;
12809       MadeIRChange = true;
12810       continue;
12811     }
12812
12813     // Instruction isn't dead, see if we can constant propagate it.
12814     if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
12815       if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12816         DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
12817
12818         // Add operands to the worklist.
12819         ReplaceInstUsesWith(*I, C);
12820         ++NumConstProp;
12821         EraseInstFromFunction(*I);
12822         MadeIRChange = true;
12823         continue;
12824       }
12825
12826     // See if we can trivially sink this instruction to a successor basic block.
12827     if (I->hasOneUse()) {
12828       BasicBlock *BB = I->getParent();
12829       Instruction *UserInst = cast<Instruction>(I->use_back());
12830       BasicBlock *UserParent;
12831       
12832       // Get the block the use occurs in.
12833       if (PHINode *PN = dyn_cast<PHINode>(UserInst))
12834         UserParent = PN->getIncomingBlock(I->use_begin().getUse());
12835       else
12836         UserParent = UserInst->getParent();
12837       
12838       if (UserParent != BB) {
12839         bool UserIsSuccessor = false;
12840         // See if the user is one of our successors.
12841         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12842           if (*SI == UserParent) {
12843             UserIsSuccessor = true;
12844             break;
12845           }
12846
12847         // If the user is one of our immediate successors, and if that successor
12848         // only has us as a predecessors (we'd have to split the critical edge
12849         // otherwise), we can keep going.
12850         if (UserIsSuccessor && UserParent->getSinglePredecessor())
12851           // Okay, the CFG is simple enough, try to sink this instruction.
12852           MadeIRChange |= TryToSinkInstruction(I, UserParent);
12853       }
12854     }
12855
12856     // Now that we have an instruction, try combining it to simplify it.
12857     Builder->SetInsertPoint(I->getParent(), I);
12858     
12859 #ifndef NDEBUG
12860     std::string OrigI;
12861 #endif
12862     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
12863     DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
12864
12865     if (Instruction *Result = visit(*I)) {
12866       ++NumCombined;
12867       // Should we replace the old instruction with a new one?
12868       if (Result != I) {
12869         DEBUG(errs() << "IC: Old = " << *I << '\n'
12870                      << "    New = " << *Result << '\n');
12871
12872         // Everything uses the new instruction now.
12873         I->replaceAllUsesWith(Result);
12874
12875         // Push the new instruction and any users onto the worklist.
12876         Worklist.Add(Result);
12877         Worklist.AddUsersToWorkList(*Result);
12878
12879         // Move the name to the new instruction first.
12880         Result->takeName(I);
12881
12882         // Insert the new instruction into the basic block...
12883         BasicBlock *InstParent = I->getParent();
12884         BasicBlock::iterator InsertPos = I;
12885
12886         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12887           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12888             ++InsertPos;
12889
12890         InstParent->getInstList().insert(InsertPos, Result);
12891
12892         EraseInstFromFunction(*I);
12893       } else {
12894 #ifndef NDEBUG
12895         DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12896                      << "    New = " << *I << '\n');
12897 #endif
12898
12899         // If the instruction was modified, it's possible that it is now dead.
12900         // if so, remove it.
12901         if (isInstructionTriviallyDead(I)) {
12902           EraseInstFromFunction(*I);
12903         } else {
12904           Worklist.Add(I);
12905           Worklist.AddUsersToWorkList(*I);
12906         }
12907       }
12908       MadeIRChange = true;
12909     }
12910   }
12911
12912   Worklist.Zap();
12913   return MadeIRChange;
12914 }
12915
12916
12917 bool InstCombiner::runOnFunction(Function &F) {
12918   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12919   Context = &F.getContext();
12920   TD = getAnalysisIfAvailable<TargetData>();
12921
12922   
12923   /// Builder - This is an IRBuilder that automatically inserts new
12924   /// instructions into the worklist when they are created.
12925   IRBuilder<true, TargetFolder, InstCombineIRInserter> 
12926     TheBuilder(F.getContext(), TargetFolder(TD, F.getContext()),
12927                InstCombineIRInserter(Worklist));
12928   Builder = &TheBuilder;
12929   
12930   bool EverMadeChange = false;
12931
12932   // Iterate while there is work to do.
12933   unsigned Iteration = 0;
12934   while (DoOneIteration(F, Iteration++))
12935     EverMadeChange = true;
12936   
12937   Builder = 0;
12938   return EverMadeChange;
12939 }
12940
12941 FunctionPass *llvm::createInstructionCombiningPass() {
12942   return new InstCombiner();
12943 }