fix instcombine to only do store sinking when the alignments
[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/MemoryBuiltins.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 *visitAllocaInst(AllocaInst &AI);
288     Instruction *visitFree(Instruction &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     Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
420
421     
422     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
423                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
424     
425     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
426                               bool isSub, Instruction &I);
427     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
428                                  bool isSigned, bool Inside, Instruction &IB);
429     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
430     Instruction *MatchBSwap(BinaryOperator &I);
431     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
432     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
433     Instruction *SimplifyMemSet(MemSetInst *MI);
434
435
436     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
437
438     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
439                                     unsigned CastOpc, int &NumCastsRemoved);
440     unsigned GetOrEnforceKnownAlignment(Value *V,
441                                         unsigned PrefAlign = 0);
442
443   };
444 } // end anonymous namespace
445
446 char InstCombiner::ID = 0;
447 static RegisterPass<InstCombiner>
448 X("instcombine", "Combine redundant instructions");
449
450 // getComplexity:  Assign a complexity or rank value to LLVM Values...
451 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
452 static unsigned getComplexity(Value *V) {
453   if (isa<Instruction>(V)) {
454     if (BinaryOperator::isNeg(V) ||
455         BinaryOperator::isFNeg(V) ||
456         BinaryOperator::isNot(V))
457       return 3;
458     return 4;
459   }
460   if (isa<Argument>(V)) return 3;
461   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
462 }
463
464 // isOnlyUse - Return true if this instruction will be deleted if we stop using
465 // it.
466 static bool isOnlyUse(Value *V) {
467   return V->hasOneUse() || isa<Constant>(V);
468 }
469
470 // getPromotedType - Return the specified type promoted as it would be to pass
471 // though a va_arg area...
472 static const Type *getPromotedType(const Type *Ty) {
473   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
474     if (ITy->getBitWidth() < 32)
475       return Type::getInt32Ty(Ty->getContext());
476   }
477   return Ty;
478 }
479
480 /// getBitCastOperand - If the specified operand is a CastInst, a constant
481 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
482 /// operand value, otherwise return null.
483 static Value *getBitCastOperand(Value *V) {
484   if (Operator *O = dyn_cast<Operator>(V)) {
485     if (O->getOpcode() == Instruction::BitCast)
486       return O->getOperand(0);
487     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
488       if (GEP->hasAllZeroIndices())
489         return GEP->getPointerOperand();
490   }
491   return 0;
492 }
493
494 /// This function is a wrapper around CastInst::isEliminableCastPair. It
495 /// simply extracts arguments and returns what that function returns.
496 static Instruction::CastOps 
497 isEliminableCastPair(
498   const CastInst *CI, ///< The first cast instruction
499   unsigned opcode,       ///< The opcode of the second cast instruction
500   const Type *DstTy,     ///< The target type for the second cast instruction
501   TargetData *TD         ///< The target data for pointer size
502 ) {
503
504   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
505   const Type *MidTy = CI->getType();                  // B from above
506
507   // Get the opcodes of the two Cast instructions
508   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
509   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
510
511   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
512                                                 DstTy,
513                                   TD ? TD->getIntPtrType(CI->getContext()) : 0);
514   
515   // We don't want to form an inttoptr or ptrtoint that converts to an integer
516   // type that differs from the pointer size.
517   if ((Res == Instruction::IntToPtr &&
518           (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
519       (Res == Instruction::PtrToInt &&
520           (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
521     Res = 0;
522   
523   return Instruction::CastOps(Res);
524 }
525
526 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
527 /// in any code being generated.  It does not require codegen if V is simple
528 /// enough or if the cast can be folded into other casts.
529 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
530                               const Type *Ty, TargetData *TD) {
531   if (V->getType() == Ty || isa<Constant>(V)) return false;
532   
533   // If this is another cast that can be eliminated, it isn't codegen either.
534   if (const CastInst *CI = dyn_cast<CastInst>(V))
535     if (isEliminableCastPair(CI, opcode, Ty, TD))
536       return false;
537   return true;
538 }
539
540 // SimplifyCommutative - This performs a few simplifications for commutative
541 // operators:
542 //
543 //  1. Order operands such that they are listed from right (least complex) to
544 //     left (most complex).  This puts constants before unary operators before
545 //     binary operators.
546 //
547 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
548 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
549 //
550 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
551   bool Changed = false;
552   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
553     Changed = !I.swapOperands();
554
555   if (!I.isAssociative()) return Changed;
556   Instruction::BinaryOps Opcode = I.getOpcode();
557   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
558     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
559       if (isa<Constant>(I.getOperand(1))) {
560         Constant *Folded = ConstantExpr::get(I.getOpcode(),
561                                              cast<Constant>(I.getOperand(1)),
562                                              cast<Constant>(Op->getOperand(1)));
563         I.setOperand(0, Op->getOperand(0));
564         I.setOperand(1, Folded);
565         return true;
566       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
567         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
568             isOnlyUse(Op) && isOnlyUse(Op1)) {
569           Constant *C1 = cast<Constant>(Op->getOperand(1));
570           Constant *C2 = cast<Constant>(Op1->getOperand(1));
571
572           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
573           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
574           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
575                                                     Op1->getOperand(0),
576                                                     Op1->getName(), &I);
577           Worklist.Add(New);
578           I.setOperand(0, New);
579           I.setOperand(1, Folded);
580           return true;
581         }
582     }
583   return Changed;
584 }
585
586 /// SimplifyCompare - For a CmpInst this function just orders the operands
587 /// so that theyare listed from right (least complex) to left (most complex).
588 /// This puts constants before unary operators before binary operators.
589 bool InstCombiner::SimplifyCompare(CmpInst &I) {
590   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
591     return false;
592   I.swapOperands();
593   // Compare instructions are not associative so there's nothing else we can do.
594   return true;
595 }
596
597 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
598 // if the LHS is a constant zero (which is the 'negate' form).
599 //
600 static inline Value *dyn_castNegVal(Value *V) {
601   if (BinaryOperator::isNeg(V))
602     return BinaryOperator::getNegArgument(V);
603
604   // Constants can be considered to be negated values if they can be folded.
605   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
606     return ConstantExpr::getNeg(C);
607
608   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
609     if (C->getType()->getElementType()->isInteger())
610       return ConstantExpr::getNeg(C);
611
612   return 0;
613 }
614
615 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
616 // instruction if the LHS is a constant negative zero (which is the 'negate'
617 // form).
618 //
619 static inline Value *dyn_castFNegVal(Value *V) {
620   if (BinaryOperator::isFNeg(V))
621     return BinaryOperator::getFNegArgument(V);
622
623   // Constants can be considered to be negated values if they can be folded.
624   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
625     return ConstantExpr::getFNeg(C);
626
627   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
628     if (C->getType()->getElementType()->isFloatingPoint())
629       return ConstantExpr::getFNeg(C);
630
631   return 0;
632 }
633
634 /// isFreeToInvert - Return true if the specified value is free to invert (apply
635 /// ~ to).  This happens in cases where the ~ can be eliminated.
636 static inline bool isFreeToInvert(Value *V) {
637   // ~(~(X)) -> X.
638   if (BinaryOperator::isNot(V))
639     return true;
640   
641   // Constants can be considered to be not'ed values.
642   if (isa<ConstantInt>(V))
643     return true;
644   
645   // Compares can be inverted if they have a single use.
646   if (CmpInst *CI = dyn_cast<CmpInst>(V))
647     return CI->hasOneUse();
648   
649   return false;
650 }
651
652 static inline Value *dyn_castNotVal(Value *V) {
653   // If this is not(not(x)) don't return that this is a not: we want the two
654   // not's to be folded first.
655   if (BinaryOperator::isNot(V)) {
656     Value *Operand = BinaryOperator::getNotArgument(V);
657     if (!isFreeToInvert(Operand))
658       return Operand;
659   }
660
661   // Constants can be considered to be not'ed values...
662   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
663     return ConstantInt::get(C->getType(), ~C->getValue());
664   return 0;
665 }
666
667
668
669 // dyn_castFoldableMul - If this value is a multiply that can be folded into
670 // other computations (because it has a constant operand), return the
671 // non-constant operand of the multiply, and set CST to point to the multiplier.
672 // Otherwise, return null.
673 //
674 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
675   if (V->hasOneUse() && V->getType()->isInteger())
676     if (Instruction *I = dyn_cast<Instruction>(V)) {
677       if (I->getOpcode() == Instruction::Mul)
678         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
679           return I->getOperand(0);
680       if (I->getOpcode() == Instruction::Shl)
681         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
682           // The multiplier is really 1 << CST.
683           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
684           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
685           CST = ConstantInt::get(V->getType()->getContext(),
686                                  APInt(BitWidth, 1).shl(CSTVal));
687           return I->getOperand(0);
688         }
689     }
690   return 0;
691 }
692
693 /// AddOne - Add one to a ConstantInt
694 static Constant *AddOne(Constant *C) {
695   return ConstantExpr::getAdd(C, 
696     ConstantInt::get(C->getType(), 1));
697 }
698 /// SubOne - Subtract one from a ConstantInt
699 static Constant *SubOne(ConstantInt *C) {
700   return ConstantExpr::getSub(C, 
701     ConstantInt::get(C->getType(), 1));
702 }
703 /// MultiplyOverflows - True if the multiply can not be expressed in an int
704 /// this size.
705 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
706   uint32_t W = C1->getBitWidth();
707   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
708   if (sign) {
709     LHSExt.sext(W * 2);
710     RHSExt.sext(W * 2);
711   } else {
712     LHSExt.zext(W * 2);
713     RHSExt.zext(W * 2);
714   }
715
716   APInt MulExt = LHSExt * RHSExt;
717
718   if (sign) {
719     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
720     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
721     return MulExt.slt(Min) || MulExt.sgt(Max);
722   } else 
723     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
724 }
725
726
727 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
728 /// specified instruction is a constant integer.  If so, check to see if there
729 /// are any bits set in the constant that are not demanded.  If so, shrink the
730 /// constant and return true.
731 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
732                                    APInt Demanded) {
733   assert(I && "No instruction?");
734   assert(OpNo < I->getNumOperands() && "Operand index too large");
735
736   // If the operand is not a constant integer, nothing to do.
737   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
738   if (!OpC) return false;
739
740   // If there are no bits set that aren't demanded, nothing to do.
741   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
742   if ((~Demanded & OpC->getValue()) == 0)
743     return false;
744
745   // This instruction is producing bits that are not demanded. Shrink the RHS.
746   Demanded &= OpC->getValue();
747   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
748   return true;
749 }
750
751 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
752 // set of known zero and one bits, compute the maximum and minimum values that
753 // could have the specified known zero and known one bits, returning them in
754 // min/max.
755 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
756                                                    const APInt& KnownOne,
757                                                    APInt& Min, APInt& Max) {
758   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
759          KnownZero.getBitWidth() == Min.getBitWidth() &&
760          KnownZero.getBitWidth() == Max.getBitWidth() &&
761          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
762   APInt UnknownBits = ~(KnownZero|KnownOne);
763
764   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
765   // bit if it is unknown.
766   Min = KnownOne;
767   Max = KnownOne|UnknownBits;
768   
769   if (UnknownBits.isNegative()) { // Sign bit is unknown
770     Min.set(Min.getBitWidth()-1);
771     Max.clear(Max.getBitWidth()-1);
772   }
773 }
774
775 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
776 // a set of known zero and one bits, compute the maximum and minimum values that
777 // could have the specified known zero and known one bits, returning them in
778 // min/max.
779 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
780                                                      const APInt &KnownOne,
781                                                      APInt &Min, APInt &Max) {
782   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
783          KnownZero.getBitWidth() == Min.getBitWidth() &&
784          KnownZero.getBitWidth() == Max.getBitWidth() &&
785          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
786   APInt UnknownBits = ~(KnownZero|KnownOne);
787   
788   // The minimum value is when the unknown bits are all zeros.
789   Min = KnownOne;
790   // The maximum value is when the unknown bits are all ones.
791   Max = KnownOne|UnknownBits;
792 }
793
794 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
795 /// SimplifyDemandedBits knows about.  See if the instruction has any
796 /// properties that allow us to simplify its operands.
797 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
798   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
799   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
800   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
801   
802   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
803                                      KnownZero, KnownOne, 0);
804   if (V == 0) return false;
805   if (V == &Inst) return true;
806   ReplaceInstUsesWith(Inst, V);
807   return true;
808 }
809
810 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
811 /// specified instruction operand if possible, updating it in place.  It returns
812 /// true if it made any change and false otherwise.
813 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
814                                         APInt &KnownZero, APInt &KnownOne,
815                                         unsigned Depth) {
816   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
817                                           KnownZero, KnownOne, Depth);
818   if (NewVal == 0) return false;
819   U = NewVal;
820   return true;
821 }
822
823
824 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
825 /// value based on the demanded bits.  When this function is called, it is known
826 /// that only the bits set in DemandedMask of the result of V are ever used
827 /// downstream. Consequently, depending on the mask and V, it may be possible
828 /// to replace V with a constant or one of its operands. In such cases, this
829 /// function does the replacement and returns true. In all other cases, it
830 /// returns false after analyzing the expression and setting KnownOne and known
831 /// to be one in the expression.  KnownZero contains all the bits that are known
832 /// to be zero in the expression. These are provided to potentially allow the
833 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
834 /// the expression. KnownOne and KnownZero always follow the invariant that 
835 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
836 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
837 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
838 /// and KnownOne must all be the same.
839 ///
840 /// This returns null if it did not change anything and it permits no
841 /// simplification.  This returns V itself if it did some simplification of V's
842 /// operands based on the information about what bits are demanded. This returns
843 /// some other non-null value if it found out that V is equal to another value
844 /// in the context where the specified bits are demanded, but not for all users.
845 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
846                                              APInt &KnownZero, APInt &KnownOne,
847                                              unsigned Depth) {
848   assert(V != 0 && "Null pointer of Value???");
849   assert(Depth <= 6 && "Limit Search Depth");
850   uint32_t BitWidth = DemandedMask.getBitWidth();
851   const Type *VTy = V->getType();
852   assert((TD || !isa<PointerType>(VTy)) &&
853          "SimplifyDemandedBits needs to know bit widths!");
854   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
855          (!VTy->isIntOrIntVector() ||
856           VTy->getScalarSizeInBits() == BitWidth) &&
857          KnownZero.getBitWidth() == BitWidth &&
858          KnownOne.getBitWidth() == BitWidth &&
859          "Value *V, DemandedMask, KnownZero and KnownOne "
860          "must have same BitWidth");
861   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
862     // We know all of the bits for a constant!
863     KnownOne = CI->getValue() & DemandedMask;
864     KnownZero = ~KnownOne & DemandedMask;
865     return 0;
866   }
867   if (isa<ConstantPointerNull>(V)) {
868     // We know all of the bits for a constant!
869     KnownOne.clear();
870     KnownZero = DemandedMask;
871     return 0;
872   }
873
874   KnownZero.clear();
875   KnownOne.clear();
876   if (DemandedMask == 0) {   // Not demanding any bits from V.
877     if (isa<UndefValue>(V))
878       return 0;
879     return UndefValue::get(VTy);
880   }
881   
882   if (Depth == 6)        // Limit search depth.
883     return 0;
884   
885   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
886   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
887
888   Instruction *I = dyn_cast<Instruction>(V);
889   if (!I) {
890     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
891     return 0;        // Only analyze instructions.
892   }
893
894   // If there are multiple uses of this value and we aren't at the root, then
895   // we can't do any simplifications of the operands, because DemandedMask
896   // only reflects the bits demanded by *one* of the users.
897   if (Depth != 0 && !I->hasOneUse()) {
898     // Despite the fact that we can't simplify this instruction in all User's
899     // context, we can at least compute the knownzero/knownone bits, and we can
900     // do simplifications that apply to *just* the one user if we know that
901     // this instruction has a simpler value in that context.
902     if (I->getOpcode() == Instruction::And) {
903       // If either the LHS or the RHS are Zero, the result is zero.
904       ComputeMaskedBits(I->getOperand(1), DemandedMask,
905                         RHSKnownZero, RHSKnownOne, Depth+1);
906       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
907                         LHSKnownZero, LHSKnownOne, Depth+1);
908       
909       // If all of the demanded bits are known 1 on one side, return the other.
910       // These bits cannot contribute to the result of the 'and' in this
911       // context.
912       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
913           (DemandedMask & ~LHSKnownZero))
914         return I->getOperand(0);
915       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
916           (DemandedMask & ~RHSKnownZero))
917         return I->getOperand(1);
918       
919       // If all of the demanded bits in the inputs are known zeros, return zero.
920       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
921         return Constant::getNullValue(VTy);
922       
923     } else if (I->getOpcode() == Instruction::Or) {
924       // We can simplify (X|Y) -> X or Y in the user's context if we know that
925       // only bits from X or Y are demanded.
926       
927       // If either the LHS or the RHS are One, the result is One.
928       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
929                         RHSKnownZero, RHSKnownOne, Depth+1);
930       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
931                         LHSKnownZero, LHSKnownOne, Depth+1);
932       
933       // If all of the demanded bits are known zero on one side, return the
934       // other.  These bits cannot contribute to the result of the 'or' in this
935       // context.
936       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
937           (DemandedMask & ~LHSKnownOne))
938         return I->getOperand(0);
939       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
940           (DemandedMask & ~RHSKnownOne))
941         return I->getOperand(1);
942       
943       // If all of the potentially set bits on one side are known to be set on
944       // the other side, just use the 'other' side.
945       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
946           (DemandedMask & (~RHSKnownZero)))
947         return I->getOperand(0);
948       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
949           (DemandedMask & (~LHSKnownZero)))
950         return I->getOperand(1);
951     }
952     
953     // Compute the KnownZero/KnownOne bits to simplify things downstream.
954     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
955     return 0;
956   }
957   
958   // If this is the root being simplified, allow it to have multiple uses,
959   // just set the DemandedMask to all bits so that we can try to simplify the
960   // operands.  This allows visitTruncInst (for example) to simplify the
961   // operand of a trunc without duplicating all the logic below.
962   if (Depth == 0 && !V->hasOneUse())
963     DemandedMask = APInt::getAllOnesValue(BitWidth);
964   
965   switch (I->getOpcode()) {
966   default:
967     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
968     break;
969   case Instruction::And:
970     // If either the LHS or the RHS are Zero, the result is zero.
971     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
972                              RHSKnownZero, RHSKnownOne, Depth+1) ||
973         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
974                              LHSKnownZero, LHSKnownOne, Depth+1))
975       return I;
976     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
977     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
978
979     // If all of the demanded bits are known 1 on one side, return the other.
980     // These bits cannot contribute to the result of the 'and'.
981     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
982         (DemandedMask & ~LHSKnownZero))
983       return I->getOperand(0);
984     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
985         (DemandedMask & ~RHSKnownZero))
986       return I->getOperand(1);
987     
988     // If all of the demanded bits in the inputs are known zeros, return zero.
989     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
990       return Constant::getNullValue(VTy);
991       
992     // If the RHS is a constant, see if we can simplify it.
993     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
994       return I;
995       
996     // Output known-1 bits are only known if set in both the LHS & RHS.
997     RHSKnownOne &= LHSKnownOne;
998     // Output known-0 are known to be clear if zero in either the LHS | RHS.
999     RHSKnownZero |= LHSKnownZero;
1000     break;
1001   case Instruction::Or:
1002     // If either the LHS or the RHS are One, the result is One.
1003     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1004                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1005         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
1006                              LHSKnownZero, LHSKnownOne, Depth+1))
1007       return I;
1008     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1009     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1010     
1011     // If all of the demanded bits are known zero on one side, return the other.
1012     // These bits cannot contribute to the result of the 'or'.
1013     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
1014         (DemandedMask & ~LHSKnownOne))
1015       return I->getOperand(0);
1016     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
1017         (DemandedMask & ~RHSKnownOne))
1018       return I->getOperand(1);
1019
1020     // If all of the potentially set bits on one side are known to be set on
1021     // the other side, just use the 'other' side.
1022     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
1023         (DemandedMask & (~RHSKnownZero)))
1024       return I->getOperand(0);
1025     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1026         (DemandedMask & (~LHSKnownZero)))
1027       return I->getOperand(1);
1028         
1029     // If the RHS is a constant, see if we can simplify it.
1030     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1031       return I;
1032           
1033     // Output known-0 bits are only known if clear in both the LHS & RHS.
1034     RHSKnownZero &= LHSKnownZero;
1035     // Output known-1 are known to be set if set in either the LHS | RHS.
1036     RHSKnownOne |= LHSKnownOne;
1037     break;
1038   case Instruction::Xor: {
1039     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1040                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1041         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1042                              LHSKnownZero, LHSKnownOne, Depth+1))
1043       return I;
1044     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1045     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1046     
1047     // If all of the demanded bits are known zero on one side, return the other.
1048     // These bits cannot contribute to the result of the 'xor'.
1049     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1050       return I->getOperand(0);
1051     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1052       return I->getOperand(1);
1053     
1054     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1055     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1056                          (RHSKnownOne & LHSKnownOne);
1057     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1058     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1059                         (RHSKnownOne & LHSKnownZero);
1060     
1061     // If all of the demanded bits are known to be zero on one side or the
1062     // other, turn this into an *inclusive* or.
1063     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1064     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1065       Instruction *Or = 
1066         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1067                                  I->getName());
1068       return InsertNewInstBefore(Or, *I);
1069     }
1070     
1071     // If all of the demanded bits on one side are known, and all of the set
1072     // bits on that side are also known to be set on the other side, turn this
1073     // into an AND, as we know the bits will be cleared.
1074     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1075     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1076       // all known
1077       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1078         Constant *AndC = Constant::getIntegerValue(VTy,
1079                                                    ~RHSKnownOne & DemandedMask);
1080         Instruction *And = 
1081           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1082         return InsertNewInstBefore(And, *I);
1083       }
1084     }
1085     
1086     // If the RHS is a constant, see if we can simplify it.
1087     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1088     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1089       return I;
1090     
1091     // If our LHS is an 'and' and if it has one use, and if any of the bits we
1092     // are flipping are known to be set, then the xor is just resetting those
1093     // bits to zero.  We can just knock out bits from the 'and' and the 'xor',
1094     // simplifying both of them.
1095     if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1096       if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1097           isa<ConstantInt>(I->getOperand(1)) &&
1098           isa<ConstantInt>(LHSInst->getOperand(1)) &&
1099           (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1100         ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1101         ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1102         APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1103         
1104         Constant *AndC =
1105           ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1106         Instruction *NewAnd = 
1107           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1108         InsertNewInstBefore(NewAnd, *I);
1109         
1110         Constant *XorC =
1111           ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1112         Instruction *NewXor =
1113           BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1114         return InsertNewInstBefore(NewXor, *I);
1115       }
1116           
1117           
1118     RHSKnownZero = KnownZeroOut;
1119     RHSKnownOne  = KnownOneOut;
1120     break;
1121   }
1122   case Instruction::Select:
1123     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1124                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1125         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1126                              LHSKnownZero, LHSKnownOne, Depth+1))
1127       return I;
1128     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1129     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1130     
1131     // If the operands are constants, see if we can simplify them.
1132     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1133         ShrinkDemandedConstant(I, 2, DemandedMask))
1134       return I;
1135     
1136     // Only known if known in both the LHS and RHS.
1137     RHSKnownOne &= LHSKnownOne;
1138     RHSKnownZero &= LHSKnownZero;
1139     break;
1140   case Instruction::Trunc: {
1141     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1142     DemandedMask.zext(truncBf);
1143     RHSKnownZero.zext(truncBf);
1144     RHSKnownOne.zext(truncBf);
1145     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1146                              RHSKnownZero, RHSKnownOne, Depth+1))
1147       return I;
1148     DemandedMask.trunc(BitWidth);
1149     RHSKnownZero.trunc(BitWidth);
1150     RHSKnownOne.trunc(BitWidth);
1151     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1152     break;
1153   }
1154   case Instruction::BitCast:
1155     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1156       return false;  // vector->int or fp->int?
1157
1158     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1159       if (const VectorType *SrcVTy =
1160             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1161         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1162           // Don't touch a bitcast between vectors of different element counts.
1163           return false;
1164       } else
1165         // Don't touch a scalar-to-vector bitcast.
1166         return false;
1167     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1168       // Don't touch a vector-to-scalar bitcast.
1169       return false;
1170
1171     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1172                              RHSKnownZero, RHSKnownOne, Depth+1))
1173       return I;
1174     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1175     break;
1176   case Instruction::ZExt: {
1177     // Compute the bits in the result that are not present in the input.
1178     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1179     
1180     DemandedMask.trunc(SrcBitWidth);
1181     RHSKnownZero.trunc(SrcBitWidth);
1182     RHSKnownOne.trunc(SrcBitWidth);
1183     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1184                              RHSKnownZero, RHSKnownOne, Depth+1))
1185       return I;
1186     DemandedMask.zext(BitWidth);
1187     RHSKnownZero.zext(BitWidth);
1188     RHSKnownOne.zext(BitWidth);
1189     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1190     // The top bits are known to be zero.
1191     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1192     break;
1193   }
1194   case Instruction::SExt: {
1195     // Compute the bits in the result that are not present in the input.
1196     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1197     
1198     APInt InputDemandedBits = DemandedMask & 
1199                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1200
1201     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1202     // If any of the sign extended bits are demanded, we know that the sign
1203     // bit is demanded.
1204     if ((NewBits & DemandedMask) != 0)
1205       InputDemandedBits.set(SrcBitWidth-1);
1206       
1207     InputDemandedBits.trunc(SrcBitWidth);
1208     RHSKnownZero.trunc(SrcBitWidth);
1209     RHSKnownOne.trunc(SrcBitWidth);
1210     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1211                              RHSKnownZero, RHSKnownOne, Depth+1))
1212       return I;
1213     InputDemandedBits.zext(BitWidth);
1214     RHSKnownZero.zext(BitWidth);
1215     RHSKnownOne.zext(BitWidth);
1216     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1217       
1218     // If the sign bit of the input is known set or clear, then we know the
1219     // top bits of the result.
1220
1221     // If the input sign bit is known zero, or if the NewBits are not demanded
1222     // convert this into a zero extension.
1223     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1224       // Convert to ZExt cast
1225       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1226       return InsertNewInstBefore(NewCast, *I);
1227     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1228       RHSKnownOne |= NewBits;
1229     }
1230     break;
1231   }
1232   case Instruction::Add: {
1233     // Figure out what the input bits are.  If the top bits of the and result
1234     // are not demanded, then the add doesn't demand them from its input
1235     // either.
1236     unsigned NLZ = DemandedMask.countLeadingZeros();
1237       
1238     // If there is a constant on the RHS, there are a variety of xformations
1239     // we can do.
1240     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1241       // If null, this should be simplified elsewhere.  Some of the xforms here
1242       // won't work if the RHS is zero.
1243       if (RHS->isZero())
1244         break;
1245       
1246       // If the top bit of the output is demanded, demand everything from the
1247       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1248       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1249
1250       // Find information about known zero/one bits in the input.
1251       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1252                                LHSKnownZero, LHSKnownOne, Depth+1))
1253         return I;
1254
1255       // If the RHS of the add has bits set that can't affect the input, reduce
1256       // the constant.
1257       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1258         return I;
1259       
1260       // Avoid excess work.
1261       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1262         break;
1263       
1264       // Turn it into OR if input bits are zero.
1265       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1266         Instruction *Or =
1267           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1268                                    I->getName());
1269         return InsertNewInstBefore(Or, *I);
1270       }
1271       
1272       // We can say something about the output known-zero and known-one bits,
1273       // depending on potential carries from the input constant and the
1274       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1275       // bits set and the RHS constant is 0x01001, then we know we have a known
1276       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1277       
1278       // To compute this, we first compute the potential carry bits.  These are
1279       // the bits which may be modified.  I'm not aware of a better way to do
1280       // this scan.
1281       const APInt &RHSVal = RHS->getValue();
1282       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1283       
1284       // Now that we know which bits have carries, compute the known-1/0 sets.
1285       
1286       // Bits are known one if they are known zero in one operand and one in the
1287       // other, and there is no input carry.
1288       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1289                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1290       
1291       // Bits are known zero if they are known zero in both operands and there
1292       // is no input carry.
1293       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1294     } else {
1295       // If the high-bits of this ADD are not demanded, then it does not demand
1296       // the high bits of its LHS or RHS.
1297       if (DemandedMask[BitWidth-1] == 0) {
1298         // Right fill the mask of bits for this ADD to demand the most
1299         // significant bit and all those below it.
1300         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1301         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1302                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1303             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1304                                  LHSKnownZero, LHSKnownOne, Depth+1))
1305           return I;
1306       }
1307     }
1308     break;
1309   }
1310   case Instruction::Sub:
1311     // If the high-bits of this SUB are not demanded, then it does not demand
1312     // the high bits of its LHS or RHS.
1313     if (DemandedMask[BitWidth-1] == 0) {
1314       // Right fill the mask of bits for this SUB to demand the most
1315       // significant bit and all those below it.
1316       uint32_t NLZ = DemandedMask.countLeadingZeros();
1317       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1318       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1319                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1320           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1321                                LHSKnownZero, LHSKnownOne, Depth+1))
1322         return I;
1323     }
1324     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1325     // the known zeros and ones.
1326     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1327     break;
1328   case Instruction::Shl:
1329     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1330       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1331       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1332       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1333                                RHSKnownZero, RHSKnownOne, Depth+1))
1334         return I;
1335       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1336       RHSKnownZero <<= ShiftAmt;
1337       RHSKnownOne  <<= ShiftAmt;
1338       // low bits known zero.
1339       if (ShiftAmt)
1340         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1341     }
1342     break;
1343   case Instruction::LShr:
1344     // For a logical shift right
1345     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1346       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1347       
1348       // Unsigned shift right.
1349       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1350       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1351                                RHSKnownZero, RHSKnownOne, Depth+1))
1352         return I;
1353       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1354       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1355       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1356       if (ShiftAmt) {
1357         // Compute the new bits that are at the top now.
1358         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1359         RHSKnownZero |= HighBits;  // high bits known zero.
1360       }
1361     }
1362     break;
1363   case Instruction::AShr:
1364     // If this is an arithmetic shift right and only the low-bit is set, we can
1365     // always convert this into a logical shr, even if the shift amount is
1366     // variable.  The low bit of the shift cannot be an input sign bit unless
1367     // the shift amount is >= the size of the datatype, which is undefined.
1368     if (DemandedMask == 1) {
1369       // Perform the logical shift right.
1370       Instruction *NewVal = BinaryOperator::CreateLShr(
1371                         I->getOperand(0), I->getOperand(1), I->getName());
1372       return InsertNewInstBefore(NewVal, *I);
1373     }    
1374
1375     // If the sign bit is the only bit demanded by this ashr, then there is no
1376     // need to do it, the shift doesn't change the high bit.
1377     if (DemandedMask.isSignBit())
1378       return I->getOperand(0);
1379     
1380     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1381       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1382       
1383       // Signed shift right.
1384       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1385       // If any of the "high bits" are demanded, we should set the sign bit as
1386       // demanded.
1387       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1388         DemandedMaskIn.set(BitWidth-1);
1389       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1390                                RHSKnownZero, RHSKnownOne, Depth+1))
1391         return I;
1392       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1393       // Compute the new bits that are at the top now.
1394       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1395       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1396       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1397         
1398       // Handle the sign bits.
1399       APInt SignBit(APInt::getSignBit(BitWidth));
1400       // Adjust to where it is now in the mask.
1401       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1402         
1403       // If the input sign bit is known to be zero, or if none of the top bits
1404       // are demanded, turn this into an unsigned shift right.
1405       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1406           (HighBits & ~DemandedMask) == HighBits) {
1407         // Perform the logical shift right.
1408         Instruction *NewVal = BinaryOperator::CreateLShr(
1409                           I->getOperand(0), SA, I->getName());
1410         return InsertNewInstBefore(NewVal, *I);
1411       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1412         RHSKnownOne |= HighBits;
1413       }
1414     }
1415     break;
1416   case Instruction::SRem:
1417     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1418       APInt RA = Rem->getValue().abs();
1419       if (RA.isPowerOf2()) {
1420         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1421           return I->getOperand(0);
1422
1423         APInt LowBits = RA - 1;
1424         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1425         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1426                                  LHSKnownZero, LHSKnownOne, Depth+1))
1427           return I;
1428
1429         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1430           LHSKnownZero |= ~LowBits;
1431
1432         KnownZero |= LHSKnownZero & DemandedMask;
1433
1434         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1435       }
1436     }
1437     break;
1438   case Instruction::URem: {
1439     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1440     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1441     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1442                              KnownZero2, KnownOne2, Depth+1) ||
1443         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1444                              KnownZero2, KnownOne2, Depth+1))
1445       return I;
1446
1447     unsigned Leaders = KnownZero2.countLeadingOnes();
1448     Leaders = std::max(Leaders,
1449                        KnownZero2.countLeadingOnes());
1450     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1451     break;
1452   }
1453   case Instruction::Call:
1454     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1455       switch (II->getIntrinsicID()) {
1456       default: break;
1457       case Intrinsic::bswap: {
1458         // If the only bits demanded come from one byte of the bswap result,
1459         // just shift the input byte into position to eliminate the bswap.
1460         unsigned NLZ = DemandedMask.countLeadingZeros();
1461         unsigned NTZ = DemandedMask.countTrailingZeros();
1462           
1463         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1464         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1465         // have 14 leading zeros, round to 8.
1466         NLZ &= ~7;
1467         NTZ &= ~7;
1468         // If we need exactly one byte, we can do this transformation.
1469         if (BitWidth-NLZ-NTZ == 8) {
1470           unsigned ResultBit = NTZ;
1471           unsigned InputBit = BitWidth-NTZ-8;
1472           
1473           // Replace this with either a left or right shift to get the byte into
1474           // the right place.
1475           Instruction *NewVal;
1476           if (InputBit > ResultBit)
1477             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1478                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1479           else
1480             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1481                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1482           NewVal->takeName(I);
1483           return InsertNewInstBefore(NewVal, *I);
1484         }
1485           
1486         // TODO: Could compute known zero/one bits based on the input.
1487         break;
1488       }
1489       }
1490     }
1491     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1492     break;
1493   }
1494   
1495   // If the client is only demanding bits that we know, return the known
1496   // constant.
1497   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1498     return Constant::getIntegerValue(VTy, RHSKnownOne);
1499   return false;
1500 }
1501
1502
1503 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1504 /// any number of elements. DemandedElts contains the set of elements that are
1505 /// actually used by the caller.  This method analyzes which elements of the
1506 /// operand are undef and returns that information in UndefElts.
1507 ///
1508 /// If the information about demanded elements can be used to simplify the
1509 /// operation, the operation is simplified, then the resultant value is
1510 /// returned.  This returns null if no change was made.
1511 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1512                                                 APInt& UndefElts,
1513                                                 unsigned Depth) {
1514   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1515   APInt EltMask(APInt::getAllOnesValue(VWidth));
1516   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1517
1518   if (isa<UndefValue>(V)) {
1519     // If the entire vector is undefined, just return this info.
1520     UndefElts = EltMask;
1521     return 0;
1522   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1523     UndefElts = EltMask;
1524     return UndefValue::get(V->getType());
1525   }
1526
1527   UndefElts = 0;
1528   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1529     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1530     Constant *Undef = UndefValue::get(EltTy);
1531
1532     std::vector<Constant*> Elts;
1533     for (unsigned i = 0; i != VWidth; ++i)
1534       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1535         Elts.push_back(Undef);
1536         UndefElts.set(i);
1537       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1538         Elts.push_back(Undef);
1539         UndefElts.set(i);
1540       } else {                               // Otherwise, defined.
1541         Elts.push_back(CP->getOperand(i));
1542       }
1543
1544     // If we changed the constant, return it.
1545     Constant *NewCP = ConstantVector::get(Elts);
1546     return NewCP != CP ? NewCP : 0;
1547   } else if (isa<ConstantAggregateZero>(V)) {
1548     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1549     // set to undef.
1550     
1551     // Check if this is identity. If so, return 0 since we are not simplifying
1552     // anything.
1553     if (DemandedElts == ((1ULL << VWidth) -1))
1554       return 0;
1555     
1556     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1557     Constant *Zero = Constant::getNullValue(EltTy);
1558     Constant *Undef = UndefValue::get(EltTy);
1559     std::vector<Constant*> Elts;
1560     for (unsigned i = 0; i != VWidth; ++i) {
1561       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1562       Elts.push_back(Elt);
1563     }
1564     UndefElts = DemandedElts ^ EltMask;
1565     return ConstantVector::get(Elts);
1566   }
1567   
1568   // Limit search depth.
1569   if (Depth == 10)
1570     return 0;
1571
1572   // If multiple users are using the root value, procede with
1573   // simplification conservatively assuming that all elements
1574   // are needed.
1575   if (!V->hasOneUse()) {
1576     // Quit if we find multiple users of a non-root value though.
1577     // They'll be handled when it's their turn to be visited by
1578     // the main instcombine process.
1579     if (Depth != 0)
1580       // TODO: Just compute the UndefElts information recursively.
1581       return 0;
1582
1583     // Conservatively assume that all elements are needed.
1584     DemandedElts = EltMask;
1585   }
1586   
1587   Instruction *I = dyn_cast<Instruction>(V);
1588   if (!I) return 0;        // Only analyze instructions.
1589   
1590   bool MadeChange = false;
1591   APInt UndefElts2(VWidth, 0);
1592   Value *TmpV;
1593   switch (I->getOpcode()) {
1594   default: break;
1595     
1596   case Instruction::InsertElement: {
1597     // If this is a variable index, we don't know which element it overwrites.
1598     // demand exactly the same input as we produce.
1599     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1600     if (Idx == 0) {
1601       // Note that we can't propagate undef elt info, because we don't know
1602       // which elt is getting updated.
1603       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1604                                         UndefElts2, Depth+1);
1605       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1606       break;
1607     }
1608     
1609     // If this is inserting an element that isn't demanded, remove this
1610     // insertelement.
1611     unsigned IdxNo = Idx->getZExtValue();
1612     if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1613       Worklist.Add(I);
1614       return I->getOperand(0);
1615     }
1616     
1617     // Otherwise, the element inserted overwrites whatever was there, so the
1618     // input demanded set is simpler than the output set.
1619     APInt DemandedElts2 = DemandedElts;
1620     DemandedElts2.clear(IdxNo);
1621     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1622                                       UndefElts, Depth+1);
1623     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1624
1625     // The inserted element is defined.
1626     UndefElts.clear(IdxNo);
1627     break;
1628   }
1629   case Instruction::ShuffleVector: {
1630     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1631     uint64_t LHSVWidth =
1632       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1633     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1634     for (unsigned i = 0; i < VWidth; i++) {
1635       if (DemandedElts[i]) {
1636         unsigned MaskVal = Shuffle->getMaskValue(i);
1637         if (MaskVal != -1u) {
1638           assert(MaskVal < LHSVWidth * 2 &&
1639                  "shufflevector mask index out of range!");
1640           if (MaskVal < LHSVWidth)
1641             LeftDemanded.set(MaskVal);
1642           else
1643             RightDemanded.set(MaskVal - LHSVWidth);
1644         }
1645       }
1646     }
1647
1648     APInt UndefElts4(LHSVWidth, 0);
1649     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1650                                       UndefElts4, Depth+1);
1651     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1652
1653     APInt UndefElts3(LHSVWidth, 0);
1654     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1655                                       UndefElts3, Depth+1);
1656     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1657
1658     bool NewUndefElts = false;
1659     for (unsigned i = 0; i < VWidth; i++) {
1660       unsigned MaskVal = Shuffle->getMaskValue(i);
1661       if (MaskVal == -1u) {
1662         UndefElts.set(i);
1663       } else if (MaskVal < LHSVWidth) {
1664         if (UndefElts4[MaskVal]) {
1665           NewUndefElts = true;
1666           UndefElts.set(i);
1667         }
1668       } else {
1669         if (UndefElts3[MaskVal - LHSVWidth]) {
1670           NewUndefElts = true;
1671           UndefElts.set(i);
1672         }
1673       }
1674     }
1675
1676     if (NewUndefElts) {
1677       // Add additional discovered undefs.
1678       std::vector<Constant*> Elts;
1679       for (unsigned i = 0; i < VWidth; ++i) {
1680         if (UndefElts[i])
1681           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
1682         else
1683           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
1684                                           Shuffle->getMaskValue(i)));
1685       }
1686       I->setOperand(2, ConstantVector::get(Elts));
1687       MadeChange = true;
1688     }
1689     break;
1690   }
1691   case Instruction::BitCast: {
1692     // Vector->vector casts only.
1693     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1694     if (!VTy) break;
1695     unsigned InVWidth = VTy->getNumElements();
1696     APInt InputDemandedElts(InVWidth, 0);
1697     unsigned Ratio;
1698
1699     if (VWidth == InVWidth) {
1700       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1701       // elements as are demanded of us.
1702       Ratio = 1;
1703       InputDemandedElts = DemandedElts;
1704     } else if (VWidth > InVWidth) {
1705       // Untested so far.
1706       break;
1707       
1708       // If there are more elements in the result than there are in the source,
1709       // then an input element is live if any of the corresponding output
1710       // elements are live.
1711       Ratio = VWidth/InVWidth;
1712       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1713         if (DemandedElts[OutIdx])
1714           InputDemandedElts.set(OutIdx/Ratio);
1715       }
1716     } else {
1717       // Untested so far.
1718       break;
1719       
1720       // If there are more elements in the source than there are in the result,
1721       // then an input element is live if the corresponding output element is
1722       // live.
1723       Ratio = InVWidth/VWidth;
1724       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1725         if (DemandedElts[InIdx/Ratio])
1726           InputDemandedElts.set(InIdx);
1727     }
1728     
1729     // div/rem demand all inputs, because they don't want divide by zero.
1730     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1731                                       UndefElts2, Depth+1);
1732     if (TmpV) {
1733       I->setOperand(0, TmpV);
1734       MadeChange = true;
1735     }
1736     
1737     UndefElts = UndefElts2;
1738     if (VWidth > InVWidth) {
1739       llvm_unreachable("Unimp");
1740       // If there are more elements in the result than there are in the source,
1741       // then an output element is undef if the corresponding input element is
1742       // undef.
1743       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1744         if (UndefElts2[OutIdx/Ratio])
1745           UndefElts.set(OutIdx);
1746     } else if (VWidth < InVWidth) {
1747       llvm_unreachable("Unimp");
1748       // If there are more elements in the source than there are in the result,
1749       // then a result element is undef if all of the corresponding input
1750       // elements are undef.
1751       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1752       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1753         if (!UndefElts2[InIdx])            // Not undef?
1754           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1755     }
1756     break;
1757   }
1758   case Instruction::And:
1759   case Instruction::Or:
1760   case Instruction::Xor:
1761   case Instruction::Add:
1762   case Instruction::Sub:
1763   case Instruction::Mul:
1764     // div/rem demand all inputs, because they don't want divide by zero.
1765     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1766                                       UndefElts, Depth+1);
1767     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1768     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1769                                       UndefElts2, Depth+1);
1770     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1771       
1772     // Output elements are undefined if both are undefined.  Consider things
1773     // like undef&0.  The result is known zero, not undef.
1774     UndefElts &= UndefElts2;
1775     break;
1776     
1777   case Instruction::Call: {
1778     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1779     if (!II) break;
1780     switch (II->getIntrinsicID()) {
1781     default: break;
1782       
1783     // Binary vector operations that work column-wise.  A dest element is a
1784     // function of the corresponding input elements from the two inputs.
1785     case Intrinsic::x86_sse_sub_ss:
1786     case Intrinsic::x86_sse_mul_ss:
1787     case Intrinsic::x86_sse_min_ss:
1788     case Intrinsic::x86_sse_max_ss:
1789     case Intrinsic::x86_sse2_sub_sd:
1790     case Intrinsic::x86_sse2_mul_sd:
1791     case Intrinsic::x86_sse2_min_sd:
1792     case Intrinsic::x86_sse2_max_sd:
1793       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1794                                         UndefElts, Depth+1);
1795       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1796       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1797                                         UndefElts2, Depth+1);
1798       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1799
1800       // If only the low elt is demanded and this is a scalarizable intrinsic,
1801       // scalarize it now.
1802       if (DemandedElts == 1) {
1803         switch (II->getIntrinsicID()) {
1804         default: break;
1805         case Intrinsic::x86_sse_sub_ss:
1806         case Intrinsic::x86_sse_mul_ss:
1807         case Intrinsic::x86_sse2_sub_sd:
1808         case Intrinsic::x86_sse2_mul_sd:
1809           // TODO: Lower MIN/MAX/ABS/etc
1810           Value *LHS = II->getOperand(1);
1811           Value *RHS = II->getOperand(2);
1812           // Extract the element as scalars.
1813           LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS, 
1814             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1815           RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1816             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1817           
1818           switch (II->getIntrinsicID()) {
1819           default: llvm_unreachable("Case stmts out of sync!");
1820           case Intrinsic::x86_sse_sub_ss:
1821           case Intrinsic::x86_sse2_sub_sd:
1822             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1823                                                         II->getName()), *II);
1824             break;
1825           case Intrinsic::x86_sse_mul_ss:
1826           case Intrinsic::x86_sse2_mul_sd:
1827             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1828                                                          II->getName()), *II);
1829             break;
1830           }
1831           
1832           Instruction *New =
1833             InsertElementInst::Create(
1834               UndefValue::get(II->getType()), TmpV,
1835               ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
1836           InsertNewInstBefore(New, *II);
1837           return New;
1838         }            
1839       }
1840         
1841       // Output elements are undefined if both are undefined.  Consider things
1842       // like undef&0.  The result is known zero, not undef.
1843       UndefElts &= UndefElts2;
1844       break;
1845     }
1846     break;
1847   }
1848   }
1849   return MadeChange ? I : 0;
1850 }
1851
1852
1853 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1854 /// function is designed to check a chain of associative operators for a
1855 /// potential to apply a certain optimization.  Since the optimization may be
1856 /// applicable if the expression was reassociated, this checks the chain, then
1857 /// reassociates the expression as necessary to expose the optimization
1858 /// opportunity.  This makes use of a special Functor, which must define
1859 /// 'shouldApply' and 'apply' methods.
1860 ///
1861 template<typename Functor>
1862 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1863   unsigned Opcode = Root.getOpcode();
1864   Value *LHS = Root.getOperand(0);
1865
1866   // Quick check, see if the immediate LHS matches...
1867   if (F.shouldApply(LHS))
1868     return F.apply(Root);
1869
1870   // Otherwise, if the LHS is not of the same opcode as the root, return.
1871   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1872   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1873     // Should we apply this transform to the RHS?
1874     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1875
1876     // If not to the RHS, check to see if we should apply to the LHS...
1877     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1878       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1879       ShouldApply = true;
1880     }
1881
1882     // If the functor wants to apply the optimization to the RHS of LHSI,
1883     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1884     if (ShouldApply) {
1885       // Now all of the instructions are in the current basic block, go ahead
1886       // and perform the reassociation.
1887       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1888
1889       // First move the selected RHS to the LHS of the root...
1890       Root.setOperand(0, LHSI->getOperand(1));
1891
1892       // Make what used to be the LHS of the root be the user of the root...
1893       Value *ExtraOperand = TmpLHSI->getOperand(1);
1894       if (&Root == TmpLHSI) {
1895         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1896         return 0;
1897       }
1898       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1899       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1900       BasicBlock::iterator ARI = &Root; ++ARI;
1901       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1902       ARI = Root;
1903
1904       // Now propagate the ExtraOperand down the chain of instructions until we
1905       // get to LHSI.
1906       while (TmpLHSI != LHSI) {
1907         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1908         // Move the instruction to immediately before the chain we are
1909         // constructing to avoid breaking dominance properties.
1910         NextLHSI->moveBefore(ARI);
1911         ARI = NextLHSI;
1912
1913         Value *NextOp = NextLHSI->getOperand(1);
1914         NextLHSI->setOperand(1, ExtraOperand);
1915         TmpLHSI = NextLHSI;
1916         ExtraOperand = NextOp;
1917       }
1918
1919       // Now that the instructions are reassociated, have the functor perform
1920       // the transformation...
1921       return F.apply(Root);
1922     }
1923
1924     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1925   }
1926   return 0;
1927 }
1928
1929 namespace {
1930
1931 // AddRHS - Implements: X + X --> X << 1
1932 struct AddRHS {
1933   Value *RHS;
1934   explicit AddRHS(Value *rhs) : RHS(rhs) {}
1935   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1936   Instruction *apply(BinaryOperator &Add) const {
1937     return BinaryOperator::CreateShl(Add.getOperand(0),
1938                                      ConstantInt::get(Add.getType(), 1));
1939   }
1940 };
1941
1942 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1943 //                 iff C1&C2 == 0
1944 struct AddMaskingAnd {
1945   Constant *C2;
1946   explicit AddMaskingAnd(Constant *c) : C2(c) {}
1947   bool shouldApply(Value *LHS) const {
1948     ConstantInt *C1;
1949     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1950            ConstantExpr::getAnd(C1, C2)->isNullValue();
1951   }
1952   Instruction *apply(BinaryOperator &Add) const {
1953     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1954   }
1955 };
1956
1957 }
1958
1959 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1960                                              InstCombiner *IC) {
1961   if (CastInst *CI = dyn_cast<CastInst>(&I))
1962     return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
1963
1964   // Figure out if the constant is the left or the right argument.
1965   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1966   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1967
1968   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1969     if (ConstIsRHS)
1970       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1971     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1972   }
1973
1974   Value *Op0 = SO, *Op1 = ConstOperand;
1975   if (!ConstIsRHS)
1976     std::swap(Op0, Op1);
1977   
1978   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1979     return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1980                                     SO->getName()+".op");
1981   if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1982     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1983                                    SO->getName()+".cmp");
1984   if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1985     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1986                                    SO->getName()+".cmp");
1987   llvm_unreachable("Unknown binary instruction type!");
1988 }
1989
1990 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1991 // constant as the other operand, try to fold the binary operator into the
1992 // select arguments.  This also works for Cast instructions, which obviously do
1993 // not have a second operand.
1994 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1995                                      InstCombiner *IC) {
1996   // Don't modify shared select instructions
1997   if (!SI->hasOneUse()) return 0;
1998   Value *TV = SI->getOperand(1);
1999   Value *FV = SI->getOperand(2);
2000
2001   if (isa<Constant>(TV) || isa<Constant>(FV)) {
2002     // Bool selects with constant operands can be folded to logical ops.
2003     if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
2004
2005     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2006     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2007
2008     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2009                               SelectFalseVal);
2010   }
2011   return 0;
2012 }
2013
2014
2015 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2016 /// has a PHI node as operand #0, see if we can fold the instruction into the
2017 /// PHI (which is only possible if all operands to the PHI are constants).
2018 ///
2019 /// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2020 /// that would normally be unprofitable because they strongly encourage jump
2021 /// threading.
2022 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2023                                          bool AllowAggressive) {
2024   AllowAggressive = false;
2025   PHINode *PN = cast<PHINode>(I.getOperand(0));
2026   unsigned NumPHIValues = PN->getNumIncomingValues();
2027   if (NumPHIValues == 0 ||
2028       // We normally only transform phis with a single use, unless we're trying
2029       // hard to make jump threading happen.
2030       (!PN->hasOneUse() && !AllowAggressive))
2031     return 0;
2032   
2033   
2034   // Check to see if all of the operands of the PHI are simple constants
2035   // (constantint/constantfp/undef).  If there is one non-constant value,
2036   // remember the BB it is in.  If there is more than one or if *it* is a PHI,
2037   // bail out.  We don't do arbitrary constant expressions here because moving
2038   // their computation can be expensive without a cost model.
2039   BasicBlock *NonConstBB = 0;
2040   for (unsigned i = 0; i != NumPHIValues; ++i)
2041     if (!isa<Constant>(PN->getIncomingValue(i)) ||
2042         isa<ConstantExpr>(PN->getIncomingValue(i))) {
2043       if (NonConstBB) return 0;  // More than one non-const value.
2044       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
2045       NonConstBB = PN->getIncomingBlock(i);
2046       
2047       // If the incoming non-constant value is in I's block, we have an infinite
2048       // loop.
2049       if (NonConstBB == I.getParent())
2050         return 0;
2051     }
2052   
2053   // If there is exactly one non-constant value, we can insert a copy of the
2054   // operation in that block.  However, if this is a critical edge, we would be
2055   // inserting the computation one some other paths (e.g. inside a loop).  Only
2056   // do this if the pred block is unconditionally branching into the phi block.
2057   if (NonConstBB != 0 && !AllowAggressive) {
2058     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2059     if (!BI || !BI->isUnconditional()) return 0;
2060   }
2061
2062   // Okay, we can do the transformation: create the new PHI node.
2063   PHINode *NewPN = PHINode::Create(I.getType(), "");
2064   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2065   InsertNewInstBefore(NewPN, *PN);
2066   NewPN->takeName(PN);
2067
2068   // Next, add all of the operands to the PHI.
2069   if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2070     // We only currently try to fold the condition of a select when it is a phi,
2071     // not the true/false values.
2072     Value *TrueV = SI->getTrueValue();
2073     Value *FalseV = SI->getFalseValue();
2074     BasicBlock *PhiTransBB = PN->getParent();
2075     for (unsigned i = 0; i != NumPHIValues; ++i) {
2076       BasicBlock *ThisBB = PN->getIncomingBlock(i);
2077       Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2078       Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
2079       Value *InV = 0;
2080       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2081         InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
2082       } else {
2083         assert(PN->getIncomingBlock(i) == NonConstBB);
2084         InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2085                                  FalseVInPred,
2086                                  "phitmp", NonConstBB->getTerminator());
2087         Worklist.Add(cast<Instruction>(InV));
2088       }
2089       NewPN->addIncoming(InV, ThisBB);
2090     }
2091   } else if (I.getNumOperands() == 2) {
2092     Constant *C = cast<Constant>(I.getOperand(1));
2093     for (unsigned i = 0; i != NumPHIValues; ++i) {
2094       Value *InV = 0;
2095       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2096         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2097           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2098         else
2099           InV = ConstantExpr::get(I.getOpcode(), InC, C);
2100       } else {
2101         assert(PN->getIncomingBlock(i) == NonConstBB);
2102         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2103           InV = BinaryOperator::Create(BO->getOpcode(),
2104                                        PN->getIncomingValue(i), C, "phitmp",
2105                                        NonConstBB->getTerminator());
2106         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2107           InV = CmpInst::Create(CI->getOpcode(),
2108                                 CI->getPredicate(),
2109                                 PN->getIncomingValue(i), C, "phitmp",
2110                                 NonConstBB->getTerminator());
2111         else
2112           llvm_unreachable("Unknown binop!");
2113         
2114         Worklist.Add(cast<Instruction>(InV));
2115       }
2116       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2117     }
2118   } else { 
2119     CastInst *CI = cast<CastInst>(&I);
2120     const Type *RetTy = CI->getType();
2121     for (unsigned i = 0; i != NumPHIValues; ++i) {
2122       Value *InV;
2123       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2124         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2125       } else {
2126         assert(PN->getIncomingBlock(i) == NonConstBB);
2127         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2128                                I.getType(), "phitmp", 
2129                                NonConstBB->getTerminator());
2130         Worklist.Add(cast<Instruction>(InV));
2131       }
2132       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2133     }
2134   }
2135   return ReplaceInstUsesWith(I, NewPN);
2136 }
2137
2138
2139 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2140 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2141 /// This basically requires proving that the add in the original type would not
2142 /// overflow to change the sign bit or have a carry out.
2143 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2144   // There are different heuristics we can use for this.  Here are some simple
2145   // ones.
2146   
2147   // Add has the property that adding any two 2's complement numbers can only 
2148   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2149   // have at least two sign bits, we know that the addition of the two values will
2150   // sign extend fine.
2151   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2152     return true;
2153   
2154   
2155   // If one of the operands only has one non-zero bit, and if the other operand
2156   // has a known-zero bit in a more significant place than it (not including the
2157   // sign bit) the ripple may go up to and fill the zero, but won't change the
2158   // sign.  For example, (X & ~4) + 1.
2159   
2160   // TODO: Implement.
2161   
2162   return false;
2163 }
2164
2165
2166 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2167   bool Changed = SimplifyCommutative(I);
2168   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2169
2170   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2171     // X + undef -> undef
2172     if (isa<UndefValue>(RHS))
2173       return ReplaceInstUsesWith(I, RHS);
2174
2175     // X + 0 --> X
2176     if (RHSC->isNullValue())
2177       return ReplaceInstUsesWith(I, LHS);
2178
2179     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2180       // X + (signbit) --> X ^ signbit
2181       const APInt& Val = CI->getValue();
2182       uint32_t BitWidth = Val.getBitWidth();
2183       if (Val == APInt::getSignBit(BitWidth))
2184         return BinaryOperator::CreateXor(LHS, RHS);
2185       
2186       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2187       // (X & 254)+1 -> (X&254)|1
2188       if (SimplifyDemandedInstructionBits(I))
2189         return &I;
2190
2191       // zext(bool) + C -> bool ? C + 1 : C
2192       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2193         if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2194           return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2195     }
2196
2197     if (isa<PHINode>(LHS))
2198       if (Instruction *NV = FoldOpIntoPhi(I))
2199         return NV;
2200     
2201     ConstantInt *XorRHS = 0;
2202     Value *XorLHS = 0;
2203     if (isa<ConstantInt>(RHSC) &&
2204         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2205       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2206       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2207       
2208       uint32_t Size = TySizeBits / 2;
2209       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2210       APInt CFF80Val(-C0080Val);
2211       do {
2212         if (TySizeBits > Size) {
2213           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2214           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2215           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2216               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2217             // This is a sign extend if the top bits are known zero.
2218             if (!MaskedValueIsZero(XorLHS, 
2219                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2220               Size = 0;  // Not a sign ext, but can't be any others either.
2221             break;
2222           }
2223         }
2224         Size >>= 1;
2225         C0080Val = APIntOps::lshr(C0080Val, Size);
2226         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2227       } while (Size >= 1);
2228       
2229       // FIXME: This shouldn't be necessary. When the backends can handle types
2230       // with funny bit widths then this switch statement should be removed. It
2231       // is just here to get the size of the "middle" type back up to something
2232       // that the back ends can handle.
2233       const Type *MiddleType = 0;
2234       switch (Size) {
2235         default: break;
2236         case 32: MiddleType = Type::getInt32Ty(*Context); break;
2237         case 16: MiddleType = Type::getInt16Ty(*Context); break;
2238         case  8: MiddleType = Type::getInt8Ty(*Context); break;
2239       }
2240       if (MiddleType) {
2241         Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
2242         return new SExtInst(NewTrunc, I.getType(), I.getName());
2243       }
2244     }
2245   }
2246
2247   if (I.getType() == Type::getInt1Ty(*Context))
2248     return BinaryOperator::CreateXor(LHS, RHS);
2249
2250   // X + X --> X << 1
2251   if (I.getType()->isInteger()) {
2252     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2253       return Result;
2254
2255     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2256       if (RHSI->getOpcode() == Instruction::Sub)
2257         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2258           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2259     }
2260     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2261       if (LHSI->getOpcode() == Instruction::Sub)
2262         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2263           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2264     }
2265   }
2266
2267   // -A + B  -->  B - A
2268   // -A + -B  -->  -(A + B)
2269   if (Value *LHSV = dyn_castNegVal(LHS)) {
2270     if (LHS->getType()->isIntOrIntVector()) {
2271       if (Value *RHSV = dyn_castNegVal(RHS)) {
2272         Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
2273         return BinaryOperator::CreateNeg(NewAdd);
2274       }
2275     }
2276     
2277     return BinaryOperator::CreateSub(RHS, LHSV);
2278   }
2279
2280   // A + -B  -->  A - B
2281   if (!isa<Constant>(RHS))
2282     if (Value *V = dyn_castNegVal(RHS))
2283       return BinaryOperator::CreateSub(LHS, V);
2284
2285
2286   ConstantInt *C2;
2287   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2288     if (X == RHS)   // X*C + X --> X * (C+1)
2289       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2290
2291     // X*C1 + X*C2 --> X * (C1+C2)
2292     ConstantInt *C1;
2293     if (X == dyn_castFoldableMul(RHS, C1))
2294       return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2295   }
2296
2297   // X + X*C --> X * (C+1)
2298   if (dyn_castFoldableMul(RHS, C2) == LHS)
2299     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2300
2301   // X + ~X --> -1   since   ~X = -X-1
2302   if (dyn_castNotVal(LHS) == RHS ||
2303       dyn_castNotVal(RHS) == LHS)
2304     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2305   
2306
2307   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2308   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2309     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2310       return R;
2311   
2312   // A+B --> A|B iff A and B have no bits set in common.
2313   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2314     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2315     APInt LHSKnownOne(IT->getBitWidth(), 0);
2316     APInt LHSKnownZero(IT->getBitWidth(), 0);
2317     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2318     if (LHSKnownZero != 0) {
2319       APInt RHSKnownOne(IT->getBitWidth(), 0);
2320       APInt RHSKnownZero(IT->getBitWidth(), 0);
2321       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2322       
2323       // No bits in common -> bitwise or.
2324       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2325         return BinaryOperator::CreateOr(LHS, RHS);
2326     }
2327   }
2328
2329   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2330   if (I.getType()->isIntOrIntVector()) {
2331     Value *W, *X, *Y, *Z;
2332     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2333         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2334       if (W != Y) {
2335         if (W == Z) {
2336           std::swap(Y, Z);
2337         } else if (Y == X) {
2338           std::swap(W, X);
2339         } else if (X == Z) {
2340           std::swap(Y, Z);
2341           std::swap(W, X);
2342         }
2343       }
2344
2345       if (W == Y) {
2346         Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
2347         return BinaryOperator::CreateMul(W, NewAdd);
2348       }
2349     }
2350   }
2351
2352   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2353     Value *X = 0;
2354     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2355       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2356
2357     // (X & FF00) + xx00  -> (X+xx00) & FF00
2358     if (LHS->hasOneUse() &&
2359         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2360       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2361       if (Anded == CRHS) {
2362         // See if all bits from the first bit set in the Add RHS up are included
2363         // in the mask.  First, get the rightmost bit.
2364         const APInt& AddRHSV = CRHS->getValue();
2365
2366         // Form a mask of all bits from the lowest bit added through the top.
2367         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2368
2369         // See if the and mask includes all of these bits.
2370         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2371
2372         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2373           // Okay, the xform is safe.  Insert the new add pronto.
2374           Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
2375           return BinaryOperator::CreateAnd(NewAdd, C2);
2376         }
2377       }
2378     }
2379
2380     // Try to fold constant add into select arguments.
2381     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2382       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2383         return R;
2384   }
2385
2386   // add (select X 0 (sub n A)) A  -->  select X A n
2387   {
2388     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2389     Value *A = RHS;
2390     if (!SI) {
2391       SI = dyn_cast<SelectInst>(RHS);
2392       A = LHS;
2393     }
2394     if (SI && SI->hasOneUse()) {
2395       Value *TV = SI->getTrueValue();
2396       Value *FV = SI->getFalseValue();
2397       Value *N;
2398
2399       // Can we fold the add into the argument of the select?
2400       // We check both true and false select arguments for a matching subtract.
2401       if (match(FV, m_Zero()) &&
2402           match(TV, m_Sub(m_Value(N), m_Specific(A))))
2403         // Fold the add into the true select value.
2404         return SelectInst::Create(SI->getCondition(), N, A);
2405       if (match(TV, m_Zero()) &&
2406           match(FV, m_Sub(m_Value(N), m_Specific(A))))
2407         // Fold the add into the false select value.
2408         return SelectInst::Create(SI->getCondition(), A, N);
2409     }
2410   }
2411
2412   // Check for (add (sext x), y), see if we can merge this into an
2413   // integer add followed by a sext.
2414   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2415     // (add (sext x), cst) --> (sext (add x, cst'))
2416     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2417       Constant *CI = 
2418         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2419       if (LHSConv->hasOneUse() &&
2420           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2421           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2422         // Insert the new, smaller add.
2423         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0), 
2424                                               CI, "addconv");
2425         return new SExtInst(NewAdd, I.getType());
2426       }
2427     }
2428     
2429     // (add (sext x), (sext y)) --> (sext (add int x, y))
2430     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2431       // Only do this if x/y have the same type, if at last one of them has a
2432       // single use (so we don't increase the number of sexts), and if the
2433       // integer add will not overflow.
2434       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2435           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2436           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2437                                    RHSConv->getOperand(0))) {
2438         // Insert the new integer add.
2439         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0), 
2440                                               RHSConv->getOperand(0), "addconv");
2441         return new SExtInst(NewAdd, I.getType());
2442       }
2443     }
2444   }
2445
2446   return Changed ? &I : 0;
2447 }
2448
2449 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2450   bool Changed = SimplifyCommutative(I);
2451   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2452
2453   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2454     // X + 0 --> X
2455     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2456       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2457                               (I.getType())->getValueAPF()))
2458         return ReplaceInstUsesWith(I, LHS);
2459     }
2460
2461     if (isa<PHINode>(LHS))
2462       if (Instruction *NV = FoldOpIntoPhi(I))
2463         return NV;
2464   }
2465
2466   // -A + B  -->  B - A
2467   // -A + -B  -->  -(A + B)
2468   if (Value *LHSV = dyn_castFNegVal(LHS))
2469     return BinaryOperator::CreateFSub(RHS, LHSV);
2470
2471   // A + -B  -->  A - B
2472   if (!isa<Constant>(RHS))
2473     if (Value *V = dyn_castFNegVal(RHS))
2474       return BinaryOperator::CreateFSub(LHS, V);
2475
2476   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2477   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2478     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2479       return ReplaceInstUsesWith(I, LHS);
2480
2481   // Check for (add double (sitofp x), y), see if we can merge this into an
2482   // integer add followed by a promotion.
2483   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2484     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2485     // ... if the constant fits in the integer value.  This is useful for things
2486     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2487     // requires a constant pool load, and generally allows the add to be better
2488     // instcombined.
2489     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2490       Constant *CI = 
2491       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2492       if (LHSConv->hasOneUse() &&
2493           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2494           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2495         // Insert the new integer add.
2496         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2497                                               CI, "addconv");
2498         return new SIToFPInst(NewAdd, I.getType());
2499       }
2500     }
2501     
2502     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2503     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2504       // Only do this if x/y have the same type, if at last one of them has a
2505       // single use (so we don't increase the number of int->fp conversions),
2506       // and if the integer add will not overflow.
2507       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2508           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2509           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2510                                    RHSConv->getOperand(0))) {
2511         // Insert the new integer add.
2512         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0), 
2513                                               RHSConv->getOperand(0), "addconv");
2514         return new SIToFPInst(NewAdd, I.getType());
2515       }
2516     }
2517   }
2518   
2519   return Changed ? &I : 0;
2520 }
2521
2522 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2523   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2524
2525   if (Op0 == Op1)                        // sub X, X  -> 0
2526     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2527
2528   // If this is a 'B = x-(-A)', change to B = x+A...
2529   if (Value *V = dyn_castNegVal(Op1))
2530     return BinaryOperator::CreateAdd(Op0, V);
2531
2532   if (isa<UndefValue>(Op0))
2533     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2534   if (isa<UndefValue>(Op1))
2535     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2536
2537   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2538     // Replace (-1 - A) with (~A)...
2539     if (C->isAllOnesValue())
2540       return BinaryOperator::CreateNot(Op1);
2541
2542     // C - ~X == X + (1+C)
2543     Value *X = 0;
2544     if (match(Op1, m_Not(m_Value(X))))
2545       return BinaryOperator::CreateAdd(X, AddOne(C));
2546
2547     // -(X >>u 31) -> (X >>s 31)
2548     // -(X >>s 31) -> (X >>u 31)
2549     if (C->isZero()) {
2550       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2551         if (SI->getOpcode() == Instruction::LShr) {
2552           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2553             // Check to see if we are shifting out everything but the sign bit.
2554             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2555                 SI->getType()->getPrimitiveSizeInBits()-1) {
2556               // Ok, the transformation is safe.  Insert AShr.
2557               return BinaryOperator::Create(Instruction::AShr, 
2558                                           SI->getOperand(0), CU, SI->getName());
2559             }
2560           }
2561         }
2562         else if (SI->getOpcode() == Instruction::AShr) {
2563           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2564             // Check to see if we are shifting out everything but the sign bit.
2565             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2566                 SI->getType()->getPrimitiveSizeInBits()-1) {
2567               // Ok, the transformation is safe.  Insert LShr. 
2568               return BinaryOperator::CreateLShr(
2569                                           SI->getOperand(0), CU, SI->getName());
2570             }
2571           }
2572         }
2573       }
2574     }
2575
2576     // Try to fold constant sub into select arguments.
2577     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2578       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2579         return R;
2580
2581     // C - zext(bool) -> bool ? C - 1 : C
2582     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2583       if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2584         return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2585   }
2586
2587   if (I.getType() == Type::getInt1Ty(*Context))
2588     return BinaryOperator::CreateXor(Op0, Op1);
2589
2590   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2591     if (Op1I->getOpcode() == Instruction::Add) {
2592       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2593         return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2594                                          I.getName());
2595       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2596         return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2597                                          I.getName());
2598       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2599         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2600           // C1-(X+C2) --> (C1-C2)-X
2601           return BinaryOperator::CreateSub(
2602             ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2603       }
2604     }
2605
2606     if (Op1I->hasOneUse()) {
2607       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2608       // is not used by anyone else...
2609       //
2610       if (Op1I->getOpcode() == Instruction::Sub) {
2611         // Swap the two operands of the subexpr...
2612         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2613         Op1I->setOperand(0, IIOp1);
2614         Op1I->setOperand(1, IIOp0);
2615
2616         // Create the new top level add instruction...
2617         return BinaryOperator::CreateAdd(Op0, Op1);
2618       }
2619
2620       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2621       //
2622       if (Op1I->getOpcode() == Instruction::And &&
2623           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2624         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2625
2626         Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
2627         return BinaryOperator::CreateAnd(Op0, NewNot);
2628       }
2629
2630       // 0 - (X sdiv C)  -> (X sdiv -C)
2631       if (Op1I->getOpcode() == Instruction::SDiv)
2632         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2633           if (CSI->isZero())
2634             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2635               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2636                                           ConstantExpr::getNeg(DivRHS));
2637
2638       // X - X*C --> X * (1-C)
2639       ConstantInt *C2 = 0;
2640       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2641         Constant *CP1 = 
2642           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2643                                              C2);
2644         return BinaryOperator::CreateMul(Op0, CP1);
2645       }
2646     }
2647   }
2648
2649   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2650     if (Op0I->getOpcode() == Instruction::Add) {
2651       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2652         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2653       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2654         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2655     } else if (Op0I->getOpcode() == Instruction::Sub) {
2656       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2657         return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2658                                          I.getName());
2659     }
2660   }
2661
2662   ConstantInt *C1;
2663   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2664     if (X == Op1)  // X*C - X --> X * (C-1)
2665       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2666
2667     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2668     if (X == dyn_castFoldableMul(Op1, C2))
2669       return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2670   }
2671   return 0;
2672 }
2673
2674 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2675   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2676
2677   // If this is a 'B = x-(-A)', change to B = x+A...
2678   if (Value *V = dyn_castFNegVal(Op1))
2679     return BinaryOperator::CreateFAdd(Op0, V);
2680
2681   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2682     if (Op1I->getOpcode() == Instruction::FAdd) {
2683       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2684         return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
2685                                           I.getName());
2686       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2687         return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
2688                                           I.getName());
2689     }
2690   }
2691
2692   return 0;
2693 }
2694
2695 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2696 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2697 /// TrueIfSigned if the result of the comparison is true when the input value is
2698 /// signed.
2699 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2700                            bool &TrueIfSigned) {
2701   switch (pred) {
2702   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2703     TrueIfSigned = true;
2704     return RHS->isZero();
2705   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2706     TrueIfSigned = true;
2707     return RHS->isAllOnesValue();
2708   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2709     TrueIfSigned = false;
2710     return RHS->isAllOnesValue();
2711   case ICmpInst::ICMP_UGT:
2712     // True if LHS u> RHS and RHS == high-bit-mask - 1
2713     TrueIfSigned = true;
2714     return RHS->getValue() ==
2715       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2716   case ICmpInst::ICMP_UGE: 
2717     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2718     TrueIfSigned = true;
2719     return RHS->getValue().isSignBit();
2720   default:
2721     return false;
2722   }
2723 }
2724
2725 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2726   bool Changed = SimplifyCommutative(I);
2727   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2728
2729   if (isa<UndefValue>(Op1))              // undef * X -> 0
2730     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2731
2732   // Simplify mul instructions with a constant RHS.
2733   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2734     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
2735
2736       // ((X << C1)*C2) == (X * (C2 << C1))
2737       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2738         if (SI->getOpcode() == Instruction::Shl)
2739           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2740             return BinaryOperator::CreateMul(SI->getOperand(0),
2741                                         ConstantExpr::getShl(CI, ShOp));
2742
2743       if (CI->isZero())
2744         return ReplaceInstUsesWith(I, Op1C);  // X * 0  == 0
2745       if (CI->equalsInt(1))                  // X * 1  == X
2746         return ReplaceInstUsesWith(I, Op0);
2747       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2748         return BinaryOperator::CreateNeg(Op0, I.getName());
2749
2750       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2751       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2752         return BinaryOperator::CreateShl(Op0,
2753                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2754       }
2755     } else if (isa<VectorType>(Op1C->getType())) {
2756       if (Op1C->isNullValue())
2757         return ReplaceInstUsesWith(I, Op1C);
2758
2759       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
2760         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2761           return BinaryOperator::CreateNeg(Op0, I.getName());
2762
2763         // As above, vector X*splat(1.0) -> X in all defined cases.
2764         if (Constant *Splat = Op1V->getSplatValue()) {
2765           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2766             if (CI->equalsInt(1))
2767               return ReplaceInstUsesWith(I, Op0);
2768         }
2769       }
2770     }
2771     
2772     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2773       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2774           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
2775         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2776         Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
2777         Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
2778         return BinaryOperator::CreateAdd(Add, C1C2);
2779         
2780       }
2781
2782     // Try to fold constant mul into select arguments.
2783     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2784       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2785         return R;
2786
2787     if (isa<PHINode>(Op0))
2788       if (Instruction *NV = FoldOpIntoPhi(I))
2789         return NV;
2790   }
2791
2792   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2793     if (Value *Op1v = dyn_castNegVal(Op1))
2794       return BinaryOperator::CreateMul(Op0v, Op1v);
2795
2796   // (X / Y) *  Y = X - (X % Y)
2797   // (X / Y) * -Y = (X % Y) - X
2798   {
2799     Value *Op1C = Op1;
2800     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2801     if (!BO ||
2802         (BO->getOpcode() != Instruction::UDiv && 
2803          BO->getOpcode() != Instruction::SDiv)) {
2804       Op1C = Op0;
2805       BO = dyn_cast<BinaryOperator>(Op1);
2806     }
2807     Value *Neg = dyn_castNegVal(Op1C);
2808     if (BO && BO->hasOneUse() &&
2809         (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
2810         (BO->getOpcode() == Instruction::UDiv ||
2811          BO->getOpcode() == Instruction::SDiv)) {
2812       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2813
2814       // If the division is exact, X % Y is zero.
2815       if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2816         if (SDiv->isExact()) {
2817           if (Op1BO == Op1C)
2818             return ReplaceInstUsesWith(I, Op0BO);
2819           return BinaryOperator::CreateNeg(Op0BO);
2820         }
2821
2822       Value *Rem;
2823       if (BO->getOpcode() == Instruction::UDiv)
2824         Rem = Builder->CreateURem(Op0BO, Op1BO);
2825       else
2826         Rem = Builder->CreateSRem(Op0BO, Op1BO);
2827       Rem->takeName(BO);
2828
2829       if (Op1BO == Op1C)
2830         return BinaryOperator::CreateSub(Op0BO, Rem);
2831       return BinaryOperator::CreateSub(Rem, Op0BO);
2832     }
2833   }
2834
2835   /// i1 mul -> i1 and.
2836   if (I.getType() == Type::getInt1Ty(*Context))
2837     return BinaryOperator::CreateAnd(Op0, Op1);
2838
2839   // X*(1 << Y) --> X << Y
2840   // (1 << Y)*X --> X << Y
2841   {
2842     Value *Y;
2843     if (match(Op0, m_Shl(m_One(), m_Value(Y))))
2844       return BinaryOperator::CreateShl(Op1, Y);
2845     if (match(Op1, m_Shl(m_One(), m_Value(Y))))
2846       return BinaryOperator::CreateShl(Op0, Y);
2847   }
2848   
2849   // If one of the operands of the multiply is a cast from a boolean value, then
2850   // we know the bool is either zero or one, so this is a 'masking' multiply.
2851   //   X * Y (where Y is 0 or 1) -> X & (0-Y)
2852   if (!isa<VectorType>(I.getType())) {
2853     // -2 is "-1 << 1" so it is all bits set except the low one.
2854     APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
2855     
2856     Value *BoolCast = 0, *OtherOp = 0;
2857     if (MaskedValueIsZero(Op0, Negative2))
2858       BoolCast = Op0, OtherOp = Op1;
2859     else if (MaskedValueIsZero(Op1, Negative2))
2860       BoolCast = Op1, OtherOp = Op0;
2861
2862     if (BoolCast) {
2863       Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
2864                                     BoolCast, "tmp");
2865       return BinaryOperator::CreateAnd(V, OtherOp);
2866     }
2867   }
2868
2869   return Changed ? &I : 0;
2870 }
2871
2872 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2873   bool Changed = SimplifyCommutative(I);
2874   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2875
2876   // Simplify mul instructions with a constant RHS...
2877   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2878     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
2879       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2880       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2881       if (Op1F->isExactlyValue(1.0))
2882         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2883     } else if (isa<VectorType>(Op1C->getType())) {
2884       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
2885         // As above, vector X*splat(1.0) -> X in all defined cases.
2886         if (Constant *Splat = Op1V->getSplatValue()) {
2887           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2888             if (F->isExactlyValue(1.0))
2889               return ReplaceInstUsesWith(I, Op0);
2890         }
2891       }
2892     }
2893
2894     // Try to fold constant mul into select arguments.
2895     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2896       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2897         return R;
2898
2899     if (isa<PHINode>(Op0))
2900       if (Instruction *NV = FoldOpIntoPhi(I))
2901         return NV;
2902   }
2903
2904   if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
2905     if (Value *Op1v = dyn_castFNegVal(Op1))
2906       return BinaryOperator::CreateFMul(Op0v, Op1v);
2907
2908   return Changed ? &I : 0;
2909 }
2910
2911 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2912 /// instruction.
2913 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2914   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2915   
2916   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2917   int NonNullOperand = -1;
2918   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2919     if (ST->isNullValue())
2920       NonNullOperand = 2;
2921   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2922   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2923     if (ST->isNullValue())
2924       NonNullOperand = 1;
2925   
2926   if (NonNullOperand == -1)
2927     return false;
2928   
2929   Value *SelectCond = SI->getOperand(0);
2930   
2931   // Change the div/rem to use 'Y' instead of the select.
2932   I.setOperand(1, SI->getOperand(NonNullOperand));
2933   
2934   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2935   // problem.  However, the select, or the condition of the select may have
2936   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2937   // propagate the known value for the select into other uses of it, and
2938   // propagate a known value of the condition into its other users.
2939   
2940   // If the select and condition only have a single use, don't bother with this,
2941   // early exit.
2942   if (SI->use_empty() && SelectCond->hasOneUse())
2943     return true;
2944   
2945   // Scan the current block backward, looking for other uses of SI.
2946   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2947   
2948   while (BBI != BBFront) {
2949     --BBI;
2950     // If we found a call to a function, we can't assume it will return, so
2951     // information from below it cannot be propagated above it.
2952     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2953       break;
2954     
2955     // Replace uses of the select or its condition with the known values.
2956     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2957          I != E; ++I) {
2958       if (*I == SI) {
2959         *I = SI->getOperand(NonNullOperand);
2960         Worklist.Add(BBI);
2961       } else if (*I == SelectCond) {
2962         *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2963                                    ConstantInt::getFalse(*Context);
2964         Worklist.Add(BBI);
2965       }
2966     }
2967     
2968     // If we past the instruction, quit looking for it.
2969     if (&*BBI == SI)
2970       SI = 0;
2971     if (&*BBI == SelectCond)
2972       SelectCond = 0;
2973     
2974     // If we ran out of things to eliminate, break out of the loop.
2975     if (SelectCond == 0 && SI == 0)
2976       break;
2977     
2978   }
2979   return true;
2980 }
2981
2982
2983 /// This function implements the transforms on div instructions that work
2984 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2985 /// used by the visitors to those instructions.
2986 /// @brief Transforms common to all three div instructions
2987 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2988   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2989
2990   // undef / X -> 0        for integer.
2991   // undef / X -> undef    for FP (the undef could be a snan).
2992   if (isa<UndefValue>(Op0)) {
2993     if (Op0->getType()->isFPOrFPVector())
2994       return ReplaceInstUsesWith(I, Op0);
2995     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2996   }
2997
2998   // X / undef -> undef
2999   if (isa<UndefValue>(Op1))
3000     return ReplaceInstUsesWith(I, Op1);
3001
3002   return 0;
3003 }
3004
3005 /// This function implements the transforms common to both integer division
3006 /// instructions (udiv and sdiv). It is called by the visitors to those integer
3007 /// division instructions.
3008 /// @brief Common integer divide transforms
3009 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3010   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3011
3012   // (sdiv X, X) --> 1     (udiv X, X) --> 1
3013   if (Op0 == Op1) {
3014     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
3015       Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
3016       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
3017       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
3018     }
3019
3020     Constant *CI = ConstantInt::get(I.getType(), 1);
3021     return ReplaceInstUsesWith(I, CI);
3022   }
3023   
3024   if (Instruction *Common = commonDivTransforms(I))
3025     return Common;
3026   
3027   // Handle cases involving: [su]div X, (select Cond, Y, Z)
3028   // This does not apply for fdiv.
3029   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3030     return &I;
3031
3032   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3033     // div X, 1 == X
3034     if (RHS->equalsInt(1))
3035       return ReplaceInstUsesWith(I, Op0);
3036
3037     // (X / C1) / C2  -> X / (C1*C2)
3038     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3039       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3040         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3041           if (MultiplyOverflows(RHS, LHSRHS,
3042                                 I.getOpcode()==Instruction::SDiv))
3043             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3044           else 
3045             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
3046                                       ConstantExpr::getMul(RHS, LHSRHS));
3047         }
3048
3049     if (!RHS->isZero()) { // avoid X udiv 0
3050       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3051         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3052           return R;
3053       if (isa<PHINode>(Op0))
3054         if (Instruction *NV = FoldOpIntoPhi(I))
3055           return NV;
3056     }
3057   }
3058
3059   // 0 / X == 0, we don't need to preserve faults!
3060   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3061     if (LHS->equalsInt(0))
3062       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3063
3064   // It can't be division by zero, hence it must be division by one.
3065   if (I.getType() == Type::getInt1Ty(*Context))
3066     return ReplaceInstUsesWith(I, Op0);
3067
3068   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3069     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3070       // div X, 1 == X
3071       if (X->isOne())
3072         return ReplaceInstUsesWith(I, Op0);
3073   }
3074
3075   return 0;
3076 }
3077
3078 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3079   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3080
3081   // Handle the integer div common cases
3082   if (Instruction *Common = commonIDivTransforms(I))
3083     return Common;
3084
3085   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3086     // X udiv C^2 -> X >> C
3087     // Check to see if this is an unsigned division with an exact power of 2,
3088     // if so, convert to a right shift.
3089     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3090       return BinaryOperator::CreateLShr(Op0, 
3091             ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3092
3093     // X udiv C, where C >= signbit
3094     if (C->getValue().isNegative()) {
3095       Value *IC = Builder->CreateICmpULT( Op0, C);
3096       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3097                                 ConstantInt::get(I.getType(), 1));
3098     }
3099   }
3100
3101   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3102   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3103     if (RHSI->getOpcode() == Instruction::Shl &&
3104         isa<ConstantInt>(RHSI->getOperand(0))) {
3105       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3106       if (C1.isPowerOf2()) {
3107         Value *N = RHSI->getOperand(1);
3108         const Type *NTy = N->getType();
3109         if (uint32_t C2 = C1.logBase2())
3110           N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
3111         return BinaryOperator::CreateLShr(Op0, N);
3112       }
3113     }
3114   }
3115   
3116   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3117   // where C1&C2 are powers of two.
3118   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3119     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3120       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3121         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3122         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3123           // Compute the shift amounts
3124           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3125           // Construct the "on true" case of the select
3126           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3127           Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
3128   
3129           // Construct the "on false" case of the select
3130           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3131           Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
3132
3133           // construct the select instruction and return it.
3134           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3135         }
3136       }
3137   return 0;
3138 }
3139
3140 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3141   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3142
3143   // Handle the integer div common cases
3144   if (Instruction *Common = commonIDivTransforms(I))
3145     return Common;
3146
3147   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3148     // sdiv X, -1 == -X
3149     if (RHS->isAllOnesValue())
3150       return BinaryOperator::CreateNeg(Op0);
3151
3152     // sdiv X, C  -->  ashr X, log2(C)
3153     if (cast<SDivOperator>(&I)->isExact() &&
3154         RHS->getValue().isNonNegative() &&
3155         RHS->getValue().isPowerOf2()) {
3156       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3157                                             RHS->getValue().exactLogBase2());
3158       return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3159     }
3160
3161     // -X/C  -->  X/-C  provided the negation doesn't overflow.
3162     if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3163       if (isa<Constant>(Sub->getOperand(0)) &&
3164           cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3165           Sub->hasNoSignedWrap())
3166         return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3167                                           ConstantExpr::getNeg(RHS));
3168   }
3169
3170   // If the sign bits of both operands are zero (i.e. we can prove they are
3171   // unsigned inputs), turn this into a udiv.
3172   if (I.getType()->isInteger()) {
3173     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3174     if (MaskedValueIsZero(Op0, Mask)) {
3175       if (MaskedValueIsZero(Op1, Mask)) {
3176         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3177         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3178       }
3179       ConstantInt *ShiftedInt;
3180       if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3181           ShiftedInt->getValue().isPowerOf2()) {
3182         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3183         // Safe because the only negative value (1 << Y) can take on is
3184         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3185         // the sign bit set.
3186         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3187       }
3188     }
3189   }
3190   
3191   return 0;
3192 }
3193
3194 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3195   return commonDivTransforms(I);
3196 }
3197
3198 /// This function implements the transforms on rem instructions that work
3199 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3200 /// is used by the visitors to those instructions.
3201 /// @brief Transforms common to all three rem instructions
3202 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3203   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3204
3205   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3206     if (I.getType()->isFPOrFPVector())
3207       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3208     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3209   }
3210   if (isa<UndefValue>(Op1))
3211     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3212
3213   // Handle cases involving: rem X, (select Cond, Y, Z)
3214   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3215     return &I;
3216
3217   return 0;
3218 }
3219
3220 /// This function implements the transforms common to both integer remainder
3221 /// instructions (urem and srem). It is called by the visitors to those integer
3222 /// remainder instructions.
3223 /// @brief Common integer remainder transforms
3224 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3225   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3226
3227   if (Instruction *common = commonRemTransforms(I))
3228     return common;
3229
3230   // 0 % X == 0 for integer, we don't need to preserve faults!
3231   if (Constant *LHS = dyn_cast<Constant>(Op0))
3232     if (LHS->isNullValue())
3233       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3234
3235   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3236     // X % 0 == undef, we don't need to preserve faults!
3237     if (RHS->equalsInt(0))
3238       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3239     
3240     if (RHS->equalsInt(1))  // X % 1 == 0
3241       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3242
3243     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3244       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3245         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3246           return R;
3247       } else if (isa<PHINode>(Op0I)) {
3248         if (Instruction *NV = FoldOpIntoPhi(I))
3249           return NV;
3250       }
3251
3252       // See if we can fold away this rem instruction.
3253       if (SimplifyDemandedInstructionBits(I))
3254         return &I;
3255     }
3256   }
3257
3258   return 0;
3259 }
3260
3261 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3262   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3263
3264   if (Instruction *common = commonIRemTransforms(I))
3265     return common;
3266   
3267   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3268     // X urem C^2 -> X and C
3269     // Check to see if this is an unsigned remainder with an exact power of 2,
3270     // if so, convert to a bitwise and.
3271     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3272       if (C->getValue().isPowerOf2())
3273         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3274   }
3275
3276   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3277     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3278     if (RHSI->getOpcode() == Instruction::Shl &&
3279         isa<ConstantInt>(RHSI->getOperand(0))) {
3280       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3281         Constant *N1 = Constant::getAllOnesValue(I.getType());
3282         Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
3283         return BinaryOperator::CreateAnd(Op0, Add);
3284       }
3285     }
3286   }
3287
3288   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3289   // where C1&C2 are powers of two.
3290   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3291     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3292       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3293         // STO == 0 and SFO == 0 handled above.
3294         if ((STO->getValue().isPowerOf2()) && 
3295             (SFO->getValue().isPowerOf2())) {
3296           Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3297                                               SI->getName()+".t");
3298           Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3299                                                SI->getName()+".f");
3300           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3301         }
3302       }
3303   }
3304   
3305   return 0;
3306 }
3307
3308 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3309   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3310
3311   // Handle the integer rem common cases
3312   if (Instruction *Common = commonIRemTransforms(I))
3313     return Common;
3314   
3315   if (Value *RHSNeg = dyn_castNegVal(Op1))
3316     if (!isa<Constant>(RHSNeg) ||
3317         (isa<ConstantInt>(RHSNeg) &&
3318          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3319       // X % -Y -> X % Y
3320       Worklist.AddValue(I.getOperand(1));
3321       I.setOperand(1, RHSNeg);
3322       return &I;
3323     }
3324
3325   // If the sign bits of both operands are zero (i.e. we can prove they are
3326   // unsigned inputs), turn this into a urem.
3327   if (I.getType()->isInteger()) {
3328     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3329     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3330       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3331       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3332     }
3333   }
3334
3335   // If it's a constant vector, flip any negative values positive.
3336   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3337     unsigned VWidth = RHSV->getNumOperands();
3338
3339     bool hasNegative = false;
3340     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3341       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3342         if (RHS->getValue().isNegative())
3343           hasNegative = true;
3344
3345     if (hasNegative) {
3346       std::vector<Constant *> Elts(VWidth);
3347       for (unsigned i = 0; i != VWidth; ++i) {
3348         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3349           if (RHS->getValue().isNegative())
3350             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3351           else
3352             Elts[i] = RHS;
3353         }
3354       }
3355
3356       Constant *NewRHSV = ConstantVector::get(Elts);
3357       if (NewRHSV != RHSV) {
3358         Worklist.AddValue(I.getOperand(1));
3359         I.setOperand(1, NewRHSV);
3360         return &I;
3361       }
3362     }
3363   }
3364
3365   return 0;
3366 }
3367
3368 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3369   return commonRemTransforms(I);
3370 }
3371
3372 // isOneBitSet - Return true if there is exactly one bit set in the specified
3373 // constant.
3374 static bool isOneBitSet(const ConstantInt *CI) {
3375   return CI->getValue().isPowerOf2();
3376 }
3377
3378 // isHighOnes - Return true if the constant is of the form 1+0+.
3379 // This is the same as lowones(~X).
3380 static bool isHighOnes(const ConstantInt *CI) {
3381   return (~CI->getValue() + 1).isPowerOf2();
3382 }
3383
3384 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3385 /// are carefully arranged to allow folding of expressions such as:
3386 ///
3387 ///      (A < B) | (A > B) --> (A != B)
3388 ///
3389 /// Note that this is only valid if the first and second predicates have the
3390 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3391 ///
3392 /// Three bits are used to represent the condition, as follows:
3393 ///   0  A > B
3394 ///   1  A == B
3395 ///   2  A < B
3396 ///
3397 /// <=>  Value  Definition
3398 /// 000     0   Always false
3399 /// 001     1   A >  B
3400 /// 010     2   A == B
3401 /// 011     3   A >= B
3402 /// 100     4   A <  B
3403 /// 101     5   A != B
3404 /// 110     6   A <= B
3405 /// 111     7   Always true
3406 ///  
3407 static unsigned getICmpCode(const ICmpInst *ICI) {
3408   switch (ICI->getPredicate()) {
3409     // False -> 0
3410   case ICmpInst::ICMP_UGT: return 1;  // 001
3411   case ICmpInst::ICMP_SGT: return 1;  // 001
3412   case ICmpInst::ICMP_EQ:  return 2;  // 010
3413   case ICmpInst::ICMP_UGE: return 3;  // 011
3414   case ICmpInst::ICMP_SGE: return 3;  // 011
3415   case ICmpInst::ICMP_ULT: return 4;  // 100
3416   case ICmpInst::ICMP_SLT: return 4;  // 100
3417   case ICmpInst::ICMP_NE:  return 5;  // 101
3418   case ICmpInst::ICMP_ULE: return 6;  // 110
3419   case ICmpInst::ICMP_SLE: return 6;  // 110
3420     // True -> 7
3421   default:
3422     llvm_unreachable("Invalid ICmp predicate!");
3423     return 0;
3424   }
3425 }
3426
3427 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3428 /// predicate into a three bit mask. It also returns whether it is an ordered
3429 /// predicate by reference.
3430 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3431   isOrdered = false;
3432   switch (CC) {
3433   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3434   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3435   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3436   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3437   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3438   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3439   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3440   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3441   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3442   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3443   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3444   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3445   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3446   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3447     // True -> 7
3448   default:
3449     // Not expecting FCMP_FALSE and FCMP_TRUE;
3450     llvm_unreachable("Unexpected FCmp predicate!");
3451     return 0;
3452   }
3453 }
3454
3455 /// getICmpValue - This is the complement of getICmpCode, which turns an
3456 /// opcode and two operands into either a constant true or false, or a brand 
3457 /// new ICmp instruction. The sign is passed in to determine which kind
3458 /// of predicate to use in the new icmp instruction.
3459 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3460                            LLVMContext *Context) {
3461   switch (code) {
3462   default: llvm_unreachable("Illegal ICmp code!");
3463   case  0: return ConstantInt::getFalse(*Context);
3464   case  1: 
3465     if (sign)
3466       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3467     else
3468       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3469   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3470   case  3: 
3471     if (sign)
3472       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3473     else
3474       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3475   case  4: 
3476     if (sign)
3477       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3478     else
3479       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3480   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3481   case  6: 
3482     if (sign)
3483       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3484     else
3485       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3486   case  7: return ConstantInt::getTrue(*Context);
3487   }
3488 }
3489
3490 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3491 /// opcode and two operands into either a FCmp instruction. isordered is passed
3492 /// in to determine which kind of predicate to use in the new fcmp instruction.
3493 static Value *getFCmpValue(bool isordered, unsigned code,
3494                            Value *LHS, Value *RHS, LLVMContext *Context) {
3495   switch (code) {
3496   default: llvm_unreachable("Illegal FCmp code!");
3497   case  0:
3498     if (isordered)
3499       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3500     else
3501       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3502   case  1: 
3503     if (isordered)
3504       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3505     else
3506       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3507   case  2: 
3508     if (isordered)
3509       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3510     else
3511       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3512   case  3: 
3513     if (isordered)
3514       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3515     else
3516       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3517   case  4: 
3518     if (isordered)
3519       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3520     else
3521       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3522   case  5: 
3523     if (isordered)
3524       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3525     else
3526       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3527   case  6: 
3528     if (isordered)
3529       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3530     else
3531       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3532   case  7: return ConstantInt::getTrue(*Context);
3533   }
3534 }
3535
3536 /// PredicatesFoldable - Return true if both predicates match sign or if at
3537 /// least one of them is an equality comparison (which is signless).
3538 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3539   return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3540          (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3541          (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
3542 }
3543
3544 namespace { 
3545 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3546 struct FoldICmpLogical {
3547   InstCombiner &IC;
3548   Value *LHS, *RHS;
3549   ICmpInst::Predicate pred;
3550   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3551     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3552       pred(ICI->getPredicate()) {}
3553   bool shouldApply(Value *V) const {
3554     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3555       if (PredicatesFoldable(pred, ICI->getPredicate()))
3556         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3557                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3558     return false;
3559   }
3560   Instruction *apply(Instruction &Log) const {
3561     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3562     if (ICI->getOperand(0) != LHS) {
3563       assert(ICI->getOperand(1) == LHS);
3564       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3565     }
3566
3567     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3568     unsigned LHSCode = getICmpCode(ICI);
3569     unsigned RHSCode = getICmpCode(RHSICI);
3570     unsigned Code;
3571     switch (Log.getOpcode()) {
3572     case Instruction::And: Code = LHSCode & RHSCode; break;
3573     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3574     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3575     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3576     }
3577
3578     bool isSigned = RHSICI->isSigned() || ICI->isSigned();
3579     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3580     if (Instruction *I = dyn_cast<Instruction>(RV))
3581       return I;
3582     // Otherwise, it's a constant boolean value...
3583     return IC.ReplaceInstUsesWith(Log, RV);
3584   }
3585 };
3586 } // end anonymous namespace
3587
3588 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3589 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3590 // guaranteed to be a binary operator.
3591 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3592                                     ConstantInt *OpRHS,
3593                                     ConstantInt *AndRHS,
3594                                     BinaryOperator &TheAnd) {
3595   Value *X = Op->getOperand(0);
3596   Constant *Together = 0;
3597   if (!Op->isShift())
3598     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3599
3600   switch (Op->getOpcode()) {
3601   case Instruction::Xor:
3602     if (Op->hasOneUse()) {
3603       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3604       Value *And = Builder->CreateAnd(X, AndRHS);
3605       And->takeName(Op);
3606       return BinaryOperator::CreateXor(And, Together);
3607     }
3608     break;
3609   case Instruction::Or:
3610     if (Together == AndRHS) // (X | C) & C --> C
3611       return ReplaceInstUsesWith(TheAnd, AndRHS);
3612
3613     if (Op->hasOneUse() && Together != OpRHS) {
3614       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3615       Value *Or = Builder->CreateOr(X, Together);
3616       Or->takeName(Op);
3617       return BinaryOperator::CreateAnd(Or, AndRHS);
3618     }
3619     break;
3620   case Instruction::Add:
3621     if (Op->hasOneUse()) {
3622       // Adding a one to a single bit bit-field should be turned into an XOR
3623       // of the bit.  First thing to check is to see if this AND is with a
3624       // single bit constant.
3625       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3626
3627       // If there is only one bit set...
3628       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3629         // Ok, at this point, we know that we are masking the result of the
3630         // ADD down to exactly one bit.  If the constant we are adding has
3631         // no bits set below this bit, then we can eliminate the ADD.
3632         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3633
3634         // Check to see if any bits below the one bit set in AndRHSV are set.
3635         if ((AddRHS & (AndRHSV-1)) == 0) {
3636           // If not, the only thing that can effect the output of the AND is
3637           // the bit specified by AndRHSV.  If that bit is set, the effect of
3638           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3639           // no effect.
3640           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3641             TheAnd.setOperand(0, X);
3642             return &TheAnd;
3643           } else {
3644             // Pull the XOR out of the AND.
3645             Value *NewAnd = Builder->CreateAnd(X, AndRHS);
3646             NewAnd->takeName(Op);
3647             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3648           }
3649         }
3650       }
3651     }
3652     break;
3653
3654   case Instruction::Shl: {
3655     // We know that the AND will not produce any of the bits shifted in, so if
3656     // the anded constant includes them, clear them now!
3657     //
3658     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3659     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3660     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3661     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3662
3663     if (CI->getValue() == ShlMask) { 
3664     // Masking out bits that the shift already masks
3665       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3666     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3667       TheAnd.setOperand(1, CI);
3668       return &TheAnd;
3669     }
3670     break;
3671   }
3672   case Instruction::LShr:
3673   {
3674     // We know that the AND will not produce any of the bits shifted in, so if
3675     // the anded constant includes them, clear them now!  This only applies to
3676     // unsigned shifts, because a signed shr may bring in set bits!
3677     //
3678     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3679     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3680     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3681     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3682
3683     if (CI->getValue() == ShrMask) {   
3684     // Masking out bits that the shift already masks.
3685       return ReplaceInstUsesWith(TheAnd, Op);
3686     } else if (CI != AndRHS) {
3687       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3688       return &TheAnd;
3689     }
3690     break;
3691   }
3692   case Instruction::AShr:
3693     // Signed shr.
3694     // See if this is shifting in some sign extension, then masking it out
3695     // with an and.
3696     if (Op->hasOneUse()) {
3697       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3698       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3699       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3700       Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3701       if (C == AndRHS) {          // Masking out bits shifted in.
3702         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3703         // Make the argument unsigned.
3704         Value *ShVal = Op->getOperand(0);
3705         ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
3706         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3707       }
3708     }
3709     break;
3710   }
3711   return 0;
3712 }
3713
3714
3715 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3716 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3717 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3718 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3719 /// insert new instructions.
3720 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3721                                            bool isSigned, bool Inside, 
3722                                            Instruction &IB) {
3723   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3724             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3725          "Lo is not <= Hi in range emission code!");
3726     
3727   if (Inside) {
3728     if (Lo == Hi)  // Trivially false.
3729       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3730
3731     // V >= Min && V < Hi --> V < Hi
3732     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3733       ICmpInst::Predicate pred = (isSigned ? 
3734         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3735       return new ICmpInst(pred, V, Hi);
3736     }
3737
3738     // Emit V-Lo <u Hi-Lo
3739     Constant *NegLo = ConstantExpr::getNeg(Lo);
3740     Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3741     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3742     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3743   }
3744
3745   if (Lo == Hi)  // Trivially true.
3746     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3747
3748   // V < Min || V >= Hi -> V > Hi-1
3749   Hi = SubOne(cast<ConstantInt>(Hi));
3750   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3751     ICmpInst::Predicate pred = (isSigned ? 
3752         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3753     return new ICmpInst(pred, V, Hi);
3754   }
3755
3756   // Emit V-Lo >u Hi-1-Lo
3757   // Note that Hi has already had one subtracted from it, above.
3758   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3759   Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3760   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3761   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3762 }
3763
3764 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3765 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3766 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3767 // not, since all 1s are not contiguous.
3768 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3769   const APInt& V = Val->getValue();
3770   uint32_t BitWidth = Val->getType()->getBitWidth();
3771   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3772
3773   // look for the first zero bit after the run of ones
3774   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3775   // look for the first non-zero bit
3776   ME = V.getActiveBits(); 
3777   return true;
3778 }
3779
3780 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3781 /// where isSub determines whether the operator is a sub.  If we can fold one of
3782 /// the following xforms:
3783 /// 
3784 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3785 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3786 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3787 ///
3788 /// return (A +/- B).
3789 ///
3790 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3791                                         ConstantInt *Mask, bool isSub,
3792                                         Instruction &I) {
3793   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3794   if (!LHSI || LHSI->getNumOperands() != 2 ||
3795       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3796
3797   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3798
3799   switch (LHSI->getOpcode()) {
3800   default: return 0;
3801   case Instruction::And:
3802     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3803       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3804       if ((Mask->getValue().countLeadingZeros() + 
3805            Mask->getValue().countPopulation()) == 
3806           Mask->getValue().getBitWidth())
3807         break;
3808
3809       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3810       // part, we don't need any explicit masks to take them out of A.  If that
3811       // is all N is, ignore it.
3812       uint32_t MB = 0, ME = 0;
3813       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3814         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3815         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3816         if (MaskedValueIsZero(RHS, Mask))
3817           break;
3818       }
3819     }
3820     return 0;
3821   case Instruction::Or:
3822   case Instruction::Xor:
3823     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3824     if ((Mask->getValue().countLeadingZeros() + 
3825          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3826         && ConstantExpr::getAnd(N, Mask)->isNullValue())
3827       break;
3828     return 0;
3829   }
3830   
3831   if (isSub)
3832     return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3833   return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
3834 }
3835
3836 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3837 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3838                                           ICmpInst *LHS, ICmpInst *RHS) {
3839   Value *Val, *Val2;
3840   ConstantInt *LHSCst, *RHSCst;
3841   ICmpInst::Predicate LHSCC, RHSCC;
3842   
3843   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3844   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3845                          m_ConstantInt(LHSCst))) ||
3846       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3847                          m_ConstantInt(RHSCst))))
3848     return 0;
3849   
3850   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3851   // where C is a power of 2
3852   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3853       LHSCst->getValue().isPowerOf2()) {
3854     Value *NewOr = Builder->CreateOr(Val, Val2);
3855     return new ICmpInst(LHSCC, NewOr, LHSCst);
3856   }
3857   
3858   // From here on, we only handle:
3859   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3860   if (Val != Val2) return 0;
3861   
3862   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3863   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3864       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3865       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3866       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3867     return 0;
3868   
3869   // We can't fold (ugt x, C) & (sgt x, C2).
3870   if (!PredicatesFoldable(LHSCC, RHSCC))
3871     return 0;
3872     
3873   // Ensure that the larger constant is on the RHS.
3874   bool ShouldSwap;
3875   if (CmpInst::isSigned(LHSCC) ||
3876       (ICmpInst::isEquality(LHSCC) && 
3877        CmpInst::isSigned(RHSCC)))
3878     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3879   else
3880     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3881     
3882   if (ShouldSwap) {
3883     std::swap(LHS, RHS);
3884     std::swap(LHSCst, RHSCst);
3885     std::swap(LHSCC, RHSCC);
3886   }
3887
3888   // At this point, we know we have have two icmp instructions
3889   // comparing a value against two constants and and'ing the result
3890   // together.  Because of the above check, we know that we only have
3891   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3892   // (from the FoldICmpLogical check above), that the two constants 
3893   // are not equal and that the larger constant is on the RHS
3894   assert(LHSCst != RHSCst && "Compares not folded above?");
3895
3896   switch (LHSCC) {
3897   default: llvm_unreachable("Unknown integer condition code!");
3898   case ICmpInst::ICMP_EQ:
3899     switch (RHSCC) {
3900     default: llvm_unreachable("Unknown integer condition code!");
3901     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3902     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3903     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3904       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3905     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3906     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3907     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3908       return ReplaceInstUsesWith(I, LHS);
3909     }
3910   case ICmpInst::ICMP_NE:
3911     switch (RHSCC) {
3912     default: llvm_unreachable("Unknown integer condition code!");
3913     case ICmpInst::ICMP_ULT:
3914       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3915         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3916       break;                        // (X != 13 & X u< 15) -> no change
3917     case ICmpInst::ICMP_SLT:
3918       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3919         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3920       break;                        // (X != 13 & X s< 15) -> no change
3921     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3922     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3923     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3924       return ReplaceInstUsesWith(I, RHS);
3925     case ICmpInst::ICMP_NE:
3926       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3927         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3928         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
3929         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3930                             ConstantInt::get(Add->getType(), 1));
3931       }
3932       break;                        // (X != 13 & X != 15) -> no change
3933     }
3934     break;
3935   case ICmpInst::ICMP_ULT:
3936     switch (RHSCC) {
3937     default: llvm_unreachable("Unknown integer condition code!");
3938     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3939     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3940       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3941     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3942       break;
3943     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3944     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3945       return ReplaceInstUsesWith(I, LHS);
3946     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3947       break;
3948     }
3949     break;
3950   case ICmpInst::ICMP_SLT:
3951     switch (RHSCC) {
3952     default: llvm_unreachable("Unknown integer condition code!");
3953     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3954     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3955       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3956     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3957       break;
3958     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3959     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3960       return ReplaceInstUsesWith(I, LHS);
3961     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3962       break;
3963     }
3964     break;
3965   case ICmpInst::ICMP_UGT:
3966     switch (RHSCC) {
3967     default: llvm_unreachable("Unknown integer condition code!");
3968     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3969     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3970       return ReplaceInstUsesWith(I, RHS);
3971     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3972       break;
3973     case ICmpInst::ICMP_NE:
3974       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3975         return new ICmpInst(LHSCC, Val, RHSCst);
3976       break;                        // (X u> 13 & X != 15) -> no change
3977     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3978       return InsertRangeTest(Val, AddOne(LHSCst),
3979                              RHSCst, false, true, I);
3980     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3981       break;
3982     }
3983     break;
3984   case ICmpInst::ICMP_SGT:
3985     switch (RHSCC) {
3986     default: llvm_unreachable("Unknown integer condition code!");
3987     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3988     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3989       return ReplaceInstUsesWith(I, RHS);
3990     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3991       break;
3992     case ICmpInst::ICMP_NE:
3993       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3994         return new ICmpInst(LHSCC, Val, RHSCst);
3995       break;                        // (X s> 13 & X != 15) -> no change
3996     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3997       return InsertRangeTest(Val, AddOne(LHSCst),
3998                              RHSCst, true, true, I);
3999     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
4000       break;
4001     }
4002     break;
4003   }
4004  
4005   return 0;
4006 }
4007
4008 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4009                                           FCmpInst *RHS) {
4010   
4011   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4012       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4013     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4014     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4015       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4016         // If either of the constants are nans, then the whole thing returns
4017         // false.
4018         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4019           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4020         return new FCmpInst(FCmpInst::FCMP_ORD,
4021                             LHS->getOperand(0), RHS->getOperand(0));
4022       }
4023     
4024     // Handle vector zeros.  This occurs because the canonical form of
4025     // "fcmp ord x,x" is "fcmp ord x, 0".
4026     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4027         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4028       return new FCmpInst(FCmpInst::FCMP_ORD,
4029                           LHS->getOperand(0), RHS->getOperand(0));
4030     return 0;
4031   }
4032   
4033   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4034   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4035   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4036   
4037   
4038   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4039     // Swap RHS operands to match LHS.
4040     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4041     std::swap(Op1LHS, Op1RHS);
4042   }
4043   
4044   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4045     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4046     if (Op0CC == Op1CC)
4047       return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4048     
4049     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
4050       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4051     if (Op0CC == FCmpInst::FCMP_TRUE)
4052       return ReplaceInstUsesWith(I, RHS);
4053     if (Op1CC == FCmpInst::FCMP_TRUE)
4054       return ReplaceInstUsesWith(I, LHS);
4055     
4056     bool Op0Ordered;
4057     bool Op1Ordered;
4058     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4059     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4060     if (Op1Pred == 0) {
4061       std::swap(LHS, RHS);
4062       std::swap(Op0Pred, Op1Pred);
4063       std::swap(Op0Ordered, Op1Ordered);
4064     }
4065     if (Op0Pred == 0) {
4066       // uno && ueq -> uno && (uno || eq) -> ueq
4067       // ord && olt -> ord && (ord && lt) -> olt
4068       if (Op0Ordered == Op1Ordered)
4069         return ReplaceInstUsesWith(I, RHS);
4070       
4071       // uno && oeq -> uno && (ord && eq) -> false
4072       // uno && ord -> false
4073       if (!Op0Ordered)
4074         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4075       // ord && ueq -> ord && (uno || eq) -> oeq
4076       return cast<Instruction>(getFCmpValue(true, Op1Pred,
4077                                             Op0LHS, Op0RHS, Context));
4078     }
4079   }
4080
4081   return 0;
4082 }
4083
4084
4085 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4086   bool Changed = SimplifyCommutative(I);
4087   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4088
4089   if (isa<UndefValue>(Op1))                         // X & undef -> 0
4090     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4091
4092   // and X, X = X
4093   if (Op0 == Op1)
4094     return ReplaceInstUsesWith(I, Op1);
4095
4096   // See if we can simplify any instructions used by the instruction whose sole 
4097   // purpose is to compute bits we don't care about.
4098   if (SimplifyDemandedInstructionBits(I))
4099     return &I;
4100   if (isa<VectorType>(I.getType())) {
4101     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4102       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
4103         return ReplaceInstUsesWith(I, I.getOperand(0));
4104     } else if (isa<ConstantAggregateZero>(Op1)) {
4105       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
4106     }
4107   }
4108
4109   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4110     const APInt &AndRHSMask = AndRHS->getValue();
4111     APInt NotAndRHS(~AndRHSMask);
4112
4113     // Optimize a variety of ((val OP C1) & C2) combinations...
4114     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4115       Value *Op0LHS = Op0I->getOperand(0);
4116       Value *Op0RHS = Op0I->getOperand(1);
4117       switch (Op0I->getOpcode()) {
4118       default: break;
4119       case Instruction::Xor:
4120       case Instruction::Or:
4121         // If the mask is only needed on one incoming arm, push it up.
4122         if (!Op0I->hasOneUse()) break;
4123           
4124         if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4125           // Not masking anything out for the LHS, move to RHS.
4126           Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4127                                              Op0RHS->getName()+".masked");
4128           return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4129         }
4130         if (!isa<Constant>(Op0RHS) &&
4131             MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4132           // Not masking anything out for the RHS, move to LHS.
4133           Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4134                                              Op0LHS->getName()+".masked");
4135           return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
4136         }
4137
4138         break;
4139       case Instruction::Add:
4140         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4141         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4142         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4143         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4144           return BinaryOperator::CreateAnd(V, AndRHS);
4145         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4146           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4147         break;
4148
4149       case Instruction::Sub:
4150         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4151         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4152         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4153         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4154           return BinaryOperator::CreateAnd(V, AndRHS);
4155
4156         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4157         // has 1's for all bits that the subtraction with A might affect.
4158         if (Op0I->hasOneUse()) {
4159           uint32_t BitWidth = AndRHSMask.getBitWidth();
4160           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4161           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4162
4163           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4164           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4165               MaskedValueIsZero(Op0LHS, Mask)) {
4166             Value *NewNeg = Builder->CreateNeg(Op0RHS);
4167             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4168           }
4169         }
4170         break;
4171
4172       case Instruction::Shl:
4173       case Instruction::LShr:
4174         // (1 << x) & 1 --> zext(x == 0)
4175         // (1 >> x) & 1 --> zext(x == 0)
4176         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4177           Value *NewICmp =
4178             Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
4179           return new ZExtInst(NewICmp, I.getType());
4180         }
4181         break;
4182       }
4183
4184       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4185         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4186           return Res;
4187     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4188       // If this is an integer truncation or change from signed-to-unsigned, and
4189       // if the source is an and/or with immediate, transform it.  This
4190       // frequently occurs for bitfield accesses.
4191       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4192         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4193             CastOp->getNumOperands() == 2)
4194           if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
4195             if (CastOp->getOpcode() == Instruction::And) {
4196               // Change: and (cast (and X, C1) to T), C2
4197               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4198               // This will fold the two constants together, which may allow 
4199               // other simplifications.
4200               Value *NewCast = Builder->CreateTruncOrBitCast(
4201                 CastOp->getOperand(0), I.getType(), 
4202                 CastOp->getName()+".shrunk");
4203               // trunc_or_bitcast(C1)&C2
4204               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4205               C3 = ConstantExpr::getAnd(C3, AndRHS);
4206               return BinaryOperator::CreateAnd(NewCast, C3);
4207             } else if (CastOp->getOpcode() == Instruction::Or) {
4208               // Change: and (cast (or X, C1) to T), C2
4209               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4210               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4211               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4212                 // trunc(C1)&C2
4213                 return ReplaceInstUsesWith(I, AndRHS);
4214             }
4215           }
4216       }
4217     }
4218
4219     // Try to fold constant and into select arguments.
4220     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4221       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4222         return R;
4223     if (isa<PHINode>(Op0))
4224       if (Instruction *NV = FoldOpIntoPhi(I))
4225         return NV;
4226   }
4227
4228   Value *Op0NotVal = dyn_castNotVal(Op0);
4229   Value *Op1NotVal = dyn_castNotVal(Op1);
4230
4231   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4232     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4233
4234   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4235   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4236     Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4237                                   I.getName()+".demorgan");
4238     return BinaryOperator::CreateNot(Or);
4239   }
4240   
4241   {
4242     Value *A = 0, *B = 0, *C = 0, *D = 0;
4243     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4244       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4245         return ReplaceInstUsesWith(I, Op1);
4246     
4247       // (A|B) & ~(A&B) -> A^B
4248       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4249         if ((A == C && B == D) || (A == D && B == C))
4250           return BinaryOperator::CreateXor(A, B);
4251       }
4252     }
4253     
4254     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4255       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4256         return ReplaceInstUsesWith(I, Op0);
4257
4258       // ~(A&B) & (A|B) -> A^B
4259       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4260         if ((A == C && B == D) || (A == D && B == C))
4261           return BinaryOperator::CreateXor(A, B);
4262       }
4263     }
4264     
4265     if (Op0->hasOneUse() &&
4266         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4267       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4268         I.swapOperands();     // Simplify below
4269         std::swap(Op0, Op1);
4270       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4271         cast<BinaryOperator>(Op0)->swapOperands();
4272         I.swapOperands();     // Simplify below
4273         std::swap(Op0, Op1);
4274       }
4275     }
4276
4277     if (Op1->hasOneUse() &&
4278         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4279       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4280         cast<BinaryOperator>(Op1)->swapOperands();
4281         std::swap(A, B);
4282       }
4283       if (A == Op0)                                // A&(A^B) -> A & ~B
4284         return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
4285     }
4286
4287     // (A&((~A)|B)) -> A&B
4288     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4289         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4290       return BinaryOperator::CreateAnd(A, Op1);
4291     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4292         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4293       return BinaryOperator::CreateAnd(A, Op0);
4294   }
4295   
4296   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4297     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4298     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4299       return R;
4300
4301     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4302       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4303         return Res;
4304   }
4305
4306   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4307   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4308     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4309       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4310         const Type *SrcTy = Op0C->getOperand(0)->getType();
4311         if (SrcTy == Op1C->getOperand(0)->getType() &&
4312             SrcTy->isIntOrIntVector() &&
4313             // Only do this if the casts both really cause code to be generated.
4314             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4315                               I.getType(), TD) &&
4316             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4317                               I.getType(), TD)) {
4318           Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4319                                             Op1C->getOperand(0), I.getName());
4320           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4321         }
4322       }
4323     
4324   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4325   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4326     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4327       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4328           SI0->getOperand(1) == SI1->getOperand(1) &&
4329           (SI0->hasOneUse() || SI1->hasOneUse())) {
4330         Value *NewOp =
4331           Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4332                              SI0->getName());
4333         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4334                                       SI1->getOperand(1));
4335       }
4336   }
4337
4338   // If and'ing two fcmp, try combine them into one.
4339   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4340     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4341       if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4342         return Res;
4343   }
4344
4345   return Changed ? &I : 0;
4346 }
4347
4348 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4349 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4350 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4351 /// the expression came from the corresponding "byte swapped" byte in some other
4352 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4353 /// we know that the expression deposits the low byte of %X into the high byte
4354 /// of the bswap result and that all other bytes are zero.  This expression is
4355 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4356 /// match.
4357 ///
4358 /// This function returns true if the match was unsuccessful and false if so.
4359 /// On entry to the function the "OverallLeftShift" is a signed integer value
4360 /// indicating the number of bytes that the subexpression is later shifted.  For
4361 /// example, if the expression is later right shifted by 16 bits, the
4362 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4363 /// byte of ByteValues is actually being set.
4364 ///
4365 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4366 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4367 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4368 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4369 /// always in the local (OverallLeftShift) coordinate space.
4370 ///
4371 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4372                               SmallVector<Value*, 8> &ByteValues) {
4373   if (Instruction *I = dyn_cast<Instruction>(V)) {
4374     // If this is an or instruction, it may be an inner node of the bswap.
4375     if (I->getOpcode() == Instruction::Or) {
4376       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4377                                ByteValues) ||
4378              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4379                                ByteValues);
4380     }
4381   
4382     // If this is a logical shift by a constant multiple of 8, recurse with
4383     // OverallLeftShift and ByteMask adjusted.
4384     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4385       unsigned ShAmt = 
4386         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4387       // Ensure the shift amount is defined and of a byte value.
4388       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4389         return true;
4390
4391       unsigned ByteShift = ShAmt >> 3;
4392       if (I->getOpcode() == Instruction::Shl) {
4393         // X << 2 -> collect(X, +2)
4394         OverallLeftShift += ByteShift;
4395         ByteMask >>= ByteShift;
4396       } else {
4397         // X >>u 2 -> collect(X, -2)
4398         OverallLeftShift -= ByteShift;
4399         ByteMask <<= ByteShift;
4400         ByteMask &= (~0U >> (32-ByteValues.size()));
4401       }
4402
4403       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4404       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4405
4406       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4407                                ByteValues);
4408     }
4409
4410     // If this is a logical 'and' with a mask that clears bytes, clear the
4411     // corresponding bytes in ByteMask.
4412     if (I->getOpcode() == Instruction::And &&
4413         isa<ConstantInt>(I->getOperand(1))) {
4414       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4415       unsigned NumBytes = ByteValues.size();
4416       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4417       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4418       
4419       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4420         // If this byte is masked out by a later operation, we don't care what
4421         // the and mask is.
4422         if ((ByteMask & (1 << i)) == 0)
4423           continue;
4424         
4425         // If the AndMask is all zeros for this byte, clear the bit.
4426         APInt MaskB = AndMask & Byte;
4427         if (MaskB == 0) {
4428           ByteMask &= ~(1U << i);
4429           continue;
4430         }
4431         
4432         // If the AndMask is not all ones for this byte, it's not a bytezap.
4433         if (MaskB != Byte)
4434           return true;
4435
4436         // Otherwise, this byte is kept.
4437       }
4438
4439       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4440                                ByteValues);
4441     }
4442   }
4443   
4444   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4445   // the input value to the bswap.  Some observations: 1) if more than one byte
4446   // is demanded from this input, then it could not be successfully assembled
4447   // into a byteswap.  At least one of the two bytes would not be aligned with
4448   // their ultimate destination.
4449   if (!isPowerOf2_32(ByteMask)) return true;
4450   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4451   
4452   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4453   // is demanded, it needs to go into byte 0 of the result.  This means that the
4454   // byte needs to be shifted until it lands in the right byte bucket.  The
4455   // shift amount depends on the position: if the byte is coming from the high
4456   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4457   // low part, it must be shifted left.
4458   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4459   if (InputByteNo < ByteValues.size()/2) {
4460     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4461       return true;
4462   } else {
4463     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4464       return true;
4465   }
4466   
4467   // If the destination byte value is already defined, the values are or'd
4468   // together, which isn't a bswap (unless it's an or of the same bits).
4469   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4470     return true;
4471   ByteValues[DestByteNo] = V;
4472   return false;
4473 }
4474
4475 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4476 /// If so, insert the new bswap intrinsic and return it.
4477 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4478   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4479   if (!ITy || ITy->getBitWidth() % 16 || 
4480       // ByteMask only allows up to 32-byte values.
4481       ITy->getBitWidth() > 32*8) 
4482     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4483   
4484   /// ByteValues - For each byte of the result, we keep track of which value
4485   /// defines each byte.
4486   SmallVector<Value*, 8> ByteValues;
4487   ByteValues.resize(ITy->getBitWidth()/8);
4488     
4489   // Try to find all the pieces corresponding to the bswap.
4490   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4491   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4492     return 0;
4493   
4494   // Check to see if all of the bytes come from the same value.
4495   Value *V = ByteValues[0];
4496   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4497   
4498   // Check to make sure that all of the bytes come from the same value.
4499   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4500     if (ByteValues[i] != V)
4501       return 0;
4502   const Type *Tys[] = { ITy };
4503   Module *M = I.getParent()->getParent()->getParent();
4504   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4505   return CallInst::Create(F, V);
4506 }
4507
4508 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4509 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4510 /// we can simplify this expression to "cond ? C : D or B".
4511 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4512                                          Value *C, Value *D,
4513                                          LLVMContext *Context) {
4514   // If A is not a select of -1/0, this cannot match.
4515   Value *Cond = 0;
4516   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4517     return 0;
4518
4519   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4520   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4521     return SelectInst::Create(Cond, C, B);
4522   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4523     return SelectInst::Create(Cond, C, B);
4524   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4525   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4526     return SelectInst::Create(Cond, C, D);
4527   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4528     return SelectInst::Create(Cond, C, D);
4529   return 0;
4530 }
4531
4532 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4533 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4534                                          ICmpInst *LHS, ICmpInst *RHS) {
4535   Value *Val, *Val2;
4536   ConstantInt *LHSCst, *RHSCst;
4537   ICmpInst::Predicate LHSCC, RHSCC;
4538   
4539   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4540   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4541              m_ConstantInt(LHSCst))) ||
4542       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4543              m_ConstantInt(RHSCst))))
4544     return 0;
4545   
4546   // From here on, we only handle:
4547   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4548   if (Val != Val2) return 0;
4549   
4550   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4551   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4552       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4553       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4554       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4555     return 0;
4556   
4557   // We can't fold (ugt x, C) | (sgt x, C2).
4558   if (!PredicatesFoldable(LHSCC, RHSCC))
4559     return 0;
4560   
4561   // Ensure that the larger constant is on the RHS.
4562   bool ShouldSwap;
4563   if (CmpInst::isSigned(LHSCC) ||
4564       (ICmpInst::isEquality(LHSCC) && 
4565        CmpInst::isSigned(RHSCC)))
4566     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4567   else
4568     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4569   
4570   if (ShouldSwap) {
4571     std::swap(LHS, RHS);
4572     std::swap(LHSCst, RHSCst);
4573     std::swap(LHSCC, RHSCC);
4574   }
4575   
4576   // At this point, we know we have have two icmp instructions
4577   // comparing a value against two constants and or'ing the result
4578   // together.  Because of the above check, we know that we only have
4579   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4580   // FoldICmpLogical check above), that the two constants are not
4581   // equal.
4582   assert(LHSCst != RHSCst && "Compares not folded above?");
4583
4584   switch (LHSCC) {
4585   default: llvm_unreachable("Unknown integer condition code!");
4586   case ICmpInst::ICMP_EQ:
4587     switch (RHSCC) {
4588     default: llvm_unreachable("Unknown integer condition code!");
4589     case ICmpInst::ICMP_EQ:
4590       if (LHSCst == SubOne(RHSCst)) {
4591         // (X == 13 | X == 14) -> X-13 <u 2
4592         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4593         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4594         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4595         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4596       }
4597       break;                         // (X == 13 | X == 15) -> no change
4598     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4599     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4600       break;
4601     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4602     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4603     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4604       return ReplaceInstUsesWith(I, RHS);
4605     }
4606     break;
4607   case ICmpInst::ICMP_NE:
4608     switch (RHSCC) {
4609     default: llvm_unreachable("Unknown integer condition code!");
4610     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4611     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4612     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4613       return ReplaceInstUsesWith(I, LHS);
4614     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4615     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4616     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4617       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4618     }
4619     break;
4620   case ICmpInst::ICMP_ULT:
4621     switch (RHSCC) {
4622     default: llvm_unreachable("Unknown integer condition code!");
4623     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4624       break;
4625     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4626       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4627       // this can cause overflow.
4628       if (RHSCst->isMaxValue(false))
4629         return ReplaceInstUsesWith(I, LHS);
4630       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4631                              false, false, I);
4632     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4633       break;
4634     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4635     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4636       return ReplaceInstUsesWith(I, RHS);
4637     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4638       break;
4639     }
4640     break;
4641   case ICmpInst::ICMP_SLT:
4642     switch (RHSCC) {
4643     default: llvm_unreachable("Unknown integer condition code!");
4644     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4645       break;
4646     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4647       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4648       // this can cause overflow.
4649       if (RHSCst->isMaxValue(true))
4650         return ReplaceInstUsesWith(I, LHS);
4651       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4652                              true, false, I);
4653     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4654       break;
4655     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4656     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4657       return ReplaceInstUsesWith(I, RHS);
4658     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4659       break;
4660     }
4661     break;
4662   case ICmpInst::ICMP_UGT:
4663     switch (RHSCC) {
4664     default: llvm_unreachable("Unknown integer condition code!");
4665     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4666     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4667       return ReplaceInstUsesWith(I, LHS);
4668     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4669       break;
4670     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4671     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4672       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4673     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4674       break;
4675     }
4676     break;
4677   case ICmpInst::ICMP_SGT:
4678     switch (RHSCC) {
4679     default: llvm_unreachable("Unknown integer condition code!");
4680     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4681     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4682       return ReplaceInstUsesWith(I, LHS);
4683     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4684       break;
4685     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4686     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4687       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4688     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4689       break;
4690     }
4691     break;
4692   }
4693   return 0;
4694 }
4695
4696 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4697                                          FCmpInst *RHS) {
4698   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4699       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4700       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4701     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4702       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4703         // If either of the constants are nans, then the whole thing returns
4704         // true.
4705         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4706           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4707         
4708         // Otherwise, no need to compare the two constants, compare the
4709         // rest.
4710         return new FCmpInst(FCmpInst::FCMP_UNO,
4711                             LHS->getOperand(0), RHS->getOperand(0));
4712       }
4713     
4714     // Handle vector zeros.  This occurs because the canonical form of
4715     // "fcmp uno x,x" is "fcmp uno x, 0".
4716     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4717         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4718       return new FCmpInst(FCmpInst::FCMP_UNO,
4719                           LHS->getOperand(0), RHS->getOperand(0));
4720     
4721     return 0;
4722   }
4723   
4724   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4725   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4726   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4727   
4728   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4729     // Swap RHS operands to match LHS.
4730     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4731     std::swap(Op1LHS, Op1RHS);
4732   }
4733   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4734     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4735     if (Op0CC == Op1CC)
4736       return new FCmpInst((FCmpInst::Predicate)Op0CC,
4737                           Op0LHS, Op0RHS);
4738     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4739       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4740     if (Op0CC == FCmpInst::FCMP_FALSE)
4741       return ReplaceInstUsesWith(I, RHS);
4742     if (Op1CC == FCmpInst::FCMP_FALSE)
4743       return ReplaceInstUsesWith(I, LHS);
4744     bool Op0Ordered;
4745     bool Op1Ordered;
4746     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4747     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4748     if (Op0Ordered == Op1Ordered) {
4749       // If both are ordered or unordered, return a new fcmp with
4750       // or'ed predicates.
4751       Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4752                                Op0LHS, Op0RHS, Context);
4753       if (Instruction *I = dyn_cast<Instruction>(RV))
4754         return I;
4755       // Otherwise, it's a constant boolean value...
4756       return ReplaceInstUsesWith(I, RV);
4757     }
4758   }
4759   return 0;
4760 }
4761
4762 /// FoldOrWithConstants - This helper function folds:
4763 ///
4764 ///     ((A | B) & C1) | (B & C2)
4765 ///
4766 /// into:
4767 /// 
4768 ///     (A & C1) | B
4769 ///
4770 /// when the XOR of the two constants is "all ones" (-1).
4771 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4772                                                Value *A, Value *B, Value *C) {
4773   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4774   if (!CI1) return 0;
4775
4776   Value *V1 = 0;
4777   ConstantInt *CI2 = 0;
4778   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4779
4780   APInt Xor = CI1->getValue() ^ CI2->getValue();
4781   if (!Xor.isAllOnesValue()) return 0;
4782
4783   if (V1 == A || V1 == B) {
4784     Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
4785     return BinaryOperator::CreateOr(NewOp, V1);
4786   }
4787
4788   return 0;
4789 }
4790
4791 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4792   bool Changed = SimplifyCommutative(I);
4793   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4794
4795   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4796     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4797
4798   // or X, X = X
4799   if (Op0 == Op1)
4800     return ReplaceInstUsesWith(I, Op0);
4801
4802   // See if we can simplify any instructions used by the instruction whose sole 
4803   // purpose is to compute bits we don't care about.
4804   if (SimplifyDemandedInstructionBits(I))
4805     return &I;
4806   if (isa<VectorType>(I.getType())) {
4807     if (isa<ConstantAggregateZero>(Op1)) {
4808       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4809     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4810       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4811         return ReplaceInstUsesWith(I, I.getOperand(1));
4812     }
4813   }
4814
4815   // or X, -1 == -1
4816   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4817     ConstantInt *C1 = 0; Value *X = 0;
4818     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4819     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
4820         isOnlyUse(Op0)) {
4821       Value *Or = Builder->CreateOr(X, RHS);
4822       Or->takeName(Op0);
4823       return BinaryOperator::CreateAnd(Or, 
4824                ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
4825     }
4826
4827     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4828     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
4829         isOnlyUse(Op0)) {
4830       Value *Or = Builder->CreateOr(X, RHS);
4831       Or->takeName(Op0);
4832       return BinaryOperator::CreateXor(Or,
4833                  ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
4834     }
4835
4836     // Try to fold constant and into select arguments.
4837     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4838       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4839         return R;
4840     if (isa<PHINode>(Op0))
4841       if (Instruction *NV = FoldOpIntoPhi(I))
4842         return NV;
4843   }
4844
4845   Value *A = 0, *B = 0;
4846   ConstantInt *C1 = 0, *C2 = 0;
4847
4848   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4849     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4850       return ReplaceInstUsesWith(I, Op1);
4851   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4852     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4853       return ReplaceInstUsesWith(I, Op0);
4854
4855   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4856   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4857   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4858       match(Op1, m_Or(m_Value(), m_Value())) ||
4859       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4860        match(Op1, m_Shift(m_Value(), m_Value())))) {
4861     if (Instruction *BSwap = MatchBSwap(I))
4862       return BSwap;
4863   }
4864   
4865   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4866   if (Op0->hasOneUse() &&
4867       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4868       MaskedValueIsZero(Op1, C1->getValue())) {
4869     Value *NOr = Builder->CreateOr(A, Op1);
4870     NOr->takeName(Op0);
4871     return BinaryOperator::CreateXor(NOr, C1);
4872   }
4873
4874   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4875   if (Op1->hasOneUse() &&
4876       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4877       MaskedValueIsZero(Op0, C1->getValue())) {
4878     Value *NOr = Builder->CreateOr(A, Op0);
4879     NOr->takeName(Op0);
4880     return BinaryOperator::CreateXor(NOr, C1);
4881   }
4882
4883   // (A & C)|(B & D)
4884   Value *C = 0, *D = 0;
4885   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4886       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4887     Value *V1 = 0, *V2 = 0, *V3 = 0;
4888     C1 = dyn_cast<ConstantInt>(C);
4889     C2 = dyn_cast<ConstantInt>(D);
4890     if (C1 && C2) {  // (A & C1)|(B & C2)
4891       // If we have: ((V + N) & C1) | (V & C2)
4892       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4893       // replace with V+N.
4894       if (C1->getValue() == ~C2->getValue()) {
4895         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4896             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4897           // Add commutes, try both ways.
4898           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4899             return ReplaceInstUsesWith(I, A);
4900           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4901             return ReplaceInstUsesWith(I, A);
4902         }
4903         // Or commutes, try both ways.
4904         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4905             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4906           // Add commutes, try both ways.
4907           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4908             return ReplaceInstUsesWith(I, B);
4909           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4910             return ReplaceInstUsesWith(I, B);
4911         }
4912       }
4913       V1 = 0; V2 = 0; V3 = 0;
4914     }
4915     
4916     // Check to see if we have any common things being and'ed.  If so, find the
4917     // terms for V1 & (V2|V3).
4918     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4919       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4920         V1 = A, V2 = C, V3 = D;
4921       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4922         V1 = A, V2 = B, V3 = C;
4923       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4924         V1 = C, V2 = A, V3 = D;
4925       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4926         V1 = C, V2 = A, V3 = B;
4927       
4928       if (V1) {
4929         Value *Or = Builder->CreateOr(V2, V3, "tmp");
4930         return BinaryOperator::CreateAnd(V1, Or);
4931       }
4932     }
4933
4934     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4935     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4936       return Match;
4937     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4938       return Match;
4939     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4940       return Match;
4941     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4942       return Match;
4943
4944     // ((A&~B)|(~A&B)) -> A^B
4945     if ((match(C, m_Not(m_Specific(D))) &&
4946          match(B, m_Not(m_Specific(A)))))
4947       return BinaryOperator::CreateXor(A, D);
4948     // ((~B&A)|(~A&B)) -> A^B
4949     if ((match(A, m_Not(m_Specific(D))) &&
4950          match(B, m_Not(m_Specific(C)))))
4951       return BinaryOperator::CreateXor(C, D);
4952     // ((A&~B)|(B&~A)) -> A^B
4953     if ((match(C, m_Not(m_Specific(B))) &&
4954          match(D, m_Not(m_Specific(A)))))
4955       return BinaryOperator::CreateXor(A, B);
4956     // ((~B&A)|(B&~A)) -> A^B
4957     if ((match(A, m_Not(m_Specific(B))) &&
4958          match(D, m_Not(m_Specific(C)))))
4959       return BinaryOperator::CreateXor(C, B);
4960   }
4961   
4962   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4963   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4964     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4965       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4966           SI0->getOperand(1) == SI1->getOperand(1) &&
4967           (SI0->hasOneUse() || SI1->hasOneUse())) {
4968         Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4969                                          SI0->getName());
4970         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4971                                       SI1->getOperand(1));
4972       }
4973   }
4974
4975   // ((A|B)&1)|(B&-2) -> (A&1) | B
4976   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4977       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4978     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4979     if (Ret) return Ret;
4980   }
4981   // (B&-2)|((A|B)&1) -> (A&1) | B
4982   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4983       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4984     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4985     if (Ret) return Ret;
4986   }
4987
4988   if ((A = dyn_castNotVal(Op0))) {   // ~A | Op1
4989     if (A == Op1)   // ~A | A == -1
4990       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4991   } else {
4992     A = 0;
4993   }
4994   // Note, A is still live here!
4995   if ((B = dyn_castNotVal(Op1))) {   // Op0 | ~B
4996     if (Op0 == B)
4997       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4998
4999     // (~A | ~B) == (~(A & B)) - De Morgan's Law
5000     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
5001       Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
5002       return BinaryOperator::CreateNot(And);
5003     }
5004   }
5005
5006   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5007   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
5008     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5009       return R;
5010
5011     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5012       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5013         return Res;
5014   }
5015     
5016   // fold (or (cast A), (cast B)) -> (cast (or A, B))
5017   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5018     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5019       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
5020         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5021             !isa<ICmpInst>(Op1C->getOperand(0))) {
5022           const Type *SrcTy = Op0C->getOperand(0)->getType();
5023           if (SrcTy == Op1C->getOperand(0)->getType() &&
5024               SrcTy->isIntOrIntVector() &&
5025               // Only do this if the casts both really cause code to be
5026               // generated.
5027               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5028                                 I.getType(), TD) &&
5029               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5030                                 I.getType(), TD)) {
5031             Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5032                                              Op1C->getOperand(0), I.getName());
5033             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5034           }
5035         }
5036       }
5037   }
5038   
5039     
5040   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
5041   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
5042     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5043       if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5044         return Res;
5045   }
5046
5047   return Changed ? &I : 0;
5048 }
5049
5050 namespace {
5051
5052 // XorSelf - Implements: X ^ X --> 0
5053 struct XorSelf {
5054   Value *RHS;
5055   XorSelf(Value *rhs) : RHS(rhs) {}
5056   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5057   Instruction *apply(BinaryOperator &Xor) const {
5058     return &Xor;
5059   }
5060 };
5061
5062 }
5063
5064 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5065   bool Changed = SimplifyCommutative(I);
5066   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5067
5068   if (isa<UndefValue>(Op1)) {
5069     if (isa<UndefValue>(Op0))
5070       // Handle undef ^ undef -> 0 special case. This is a common
5071       // idiom (misuse).
5072       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5073     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5074   }
5075
5076   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5077   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
5078     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5079     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5080   }
5081   
5082   // See if we can simplify any instructions used by the instruction whose sole 
5083   // purpose is to compute bits we don't care about.
5084   if (SimplifyDemandedInstructionBits(I))
5085     return &I;
5086   if (isa<VectorType>(I.getType()))
5087     if (isa<ConstantAggregateZero>(Op1))
5088       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5089
5090   // Is this a ~ operation?
5091   if (Value *NotOp = dyn_castNotVal(&I)) {
5092     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5093       if (Op0I->getOpcode() == Instruction::And || 
5094           Op0I->getOpcode() == Instruction::Or) {
5095         // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5096         // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5097         if (dyn_castNotVal(Op0I->getOperand(1)))
5098           Op0I->swapOperands();
5099         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5100           Value *NotY =
5101             Builder->CreateNot(Op0I->getOperand(1),
5102                                Op0I->getOperand(1)->getName()+".not");
5103           if (Op0I->getOpcode() == Instruction::And)
5104             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5105           return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5106         }
5107         
5108         // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5109         // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5110         if (isFreeToInvert(Op0I->getOperand(0)) && 
5111             isFreeToInvert(Op0I->getOperand(1))) {
5112           Value *NotX =
5113             Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5114           Value *NotY =
5115             Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5116           if (Op0I->getOpcode() == Instruction::And)
5117             return BinaryOperator::CreateOr(NotX, NotY);
5118           return BinaryOperator::CreateAnd(NotX, NotY);
5119         }
5120       }
5121     }
5122   }
5123   
5124   
5125   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5126     if (RHS->isOne() && Op0->hasOneUse()) {
5127       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5128       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5129         return new ICmpInst(ICI->getInversePredicate(),
5130                             ICI->getOperand(0), ICI->getOperand(1));
5131
5132       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5133         return new FCmpInst(FCI->getInversePredicate(),
5134                             FCI->getOperand(0), FCI->getOperand(1));
5135     }
5136
5137     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5138     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5139       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5140         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5141           Instruction::CastOps Opcode = Op0C->getOpcode();
5142           if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5143               (RHS == ConstantExpr::getCast(Opcode, 
5144                                             ConstantInt::getTrue(*Context),
5145                                             Op0C->getDestTy()))) {
5146             CI->setPredicate(CI->getInversePredicate());
5147             return CastInst::Create(Opcode, CI, Op0C->getType());
5148           }
5149         }
5150       }
5151     }
5152
5153     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5154       // ~(c-X) == X-c-1 == X+(-c-1)
5155       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5156         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5157           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5158           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5159                                       ConstantInt::get(I.getType(), 1));
5160           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5161         }
5162           
5163       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5164         if (Op0I->getOpcode() == Instruction::Add) {
5165           // ~(X-c) --> (-c-1)-X
5166           if (RHS->isAllOnesValue()) {
5167             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5168             return BinaryOperator::CreateSub(
5169                            ConstantExpr::getSub(NegOp0CI,
5170                                       ConstantInt::get(I.getType(), 1)),
5171                                       Op0I->getOperand(0));
5172           } else if (RHS->getValue().isSignBit()) {
5173             // (X + C) ^ signbit -> (X + C + signbit)
5174             Constant *C = ConstantInt::get(*Context,
5175                                            RHS->getValue() + Op0CI->getValue());
5176             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5177
5178           }
5179         } else if (Op0I->getOpcode() == Instruction::Or) {
5180           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5181           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5182             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5183             // Anything in both C1 and C2 is known to be zero, remove it from
5184             // NewRHS.
5185             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5186             NewRHS = ConstantExpr::getAnd(NewRHS, 
5187                                        ConstantExpr::getNot(CommonBits));
5188             Worklist.Add(Op0I);
5189             I.setOperand(0, Op0I->getOperand(0));
5190             I.setOperand(1, NewRHS);
5191             return &I;
5192           }
5193         }
5194       }
5195     }
5196
5197     // Try to fold constant and into select arguments.
5198     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5199       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5200         return R;
5201     if (isa<PHINode>(Op0))
5202       if (Instruction *NV = FoldOpIntoPhi(I))
5203         return NV;
5204   }
5205
5206   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5207     if (X == Op1)
5208       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5209
5210   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5211     if (X == Op0)
5212       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5213
5214   
5215   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5216   if (Op1I) {
5217     Value *A, *B;
5218     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5219       if (A == Op0) {              // B^(B|A) == (A|B)^B
5220         Op1I->swapOperands();
5221         I.swapOperands();
5222         std::swap(Op0, Op1);
5223       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5224         I.swapOperands();     // Simplified below.
5225         std::swap(Op0, Op1);
5226       }
5227     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5228       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5229     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5230       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5231     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && 
5232                Op1I->hasOneUse()){
5233       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5234         Op1I->swapOperands();
5235         std::swap(A, B);
5236       }
5237       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5238         I.swapOperands();     // Simplified below.
5239         std::swap(Op0, Op1);
5240       }
5241     }
5242   }
5243   
5244   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5245   if (Op0I) {
5246     Value *A, *B;
5247     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5248         Op0I->hasOneUse()) {
5249       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5250         std::swap(A, B);
5251       if (B == Op1)                                  // (A|B)^B == A & ~B
5252         return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
5253     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5254       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5255     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5256       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5257     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && 
5258                Op0I->hasOneUse()){
5259       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5260         std::swap(A, B);
5261       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5262           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5263         return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
5264       }
5265     }
5266   }
5267   
5268   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5269   if (Op0I && Op1I && Op0I->isShift() && 
5270       Op0I->getOpcode() == Op1I->getOpcode() && 
5271       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5272       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5273     Value *NewOp =
5274       Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5275                          Op0I->getName());
5276     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5277                                   Op1I->getOperand(1));
5278   }
5279     
5280   if (Op0I && Op1I) {
5281     Value *A, *B, *C, *D;
5282     // (A & B)^(A | B) -> A ^ B
5283     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5284         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5285       if ((A == C && B == D) || (A == D && B == C)) 
5286         return BinaryOperator::CreateXor(A, B);
5287     }
5288     // (A | B)^(A & B) -> A ^ B
5289     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5290         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5291       if ((A == C && B == D) || (A == D && B == C)) 
5292         return BinaryOperator::CreateXor(A, B);
5293     }
5294     
5295     // (A & B)^(C & D)
5296     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5297         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5298         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5299       // (X & Y)^(X & Y) -> (Y^Z) & X
5300       Value *X = 0, *Y = 0, *Z = 0;
5301       if (A == C)
5302         X = A, Y = B, Z = D;
5303       else if (A == D)
5304         X = A, Y = B, Z = C;
5305       else if (B == C)
5306         X = B, Y = A, Z = D;
5307       else if (B == D)
5308         X = B, Y = A, Z = C;
5309       
5310       if (X) {
5311         Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
5312         return BinaryOperator::CreateAnd(NewOp, X);
5313       }
5314     }
5315   }
5316     
5317   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5318   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5319     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5320       return R;
5321
5322   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5323   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5324     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5325       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5326         const Type *SrcTy = Op0C->getOperand(0)->getType();
5327         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5328             // Only do this if the casts both really cause code to be generated.
5329             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5330                               I.getType(), TD) &&
5331             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5332                               I.getType(), TD)) {
5333           Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5334                                             Op1C->getOperand(0), I.getName());
5335           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5336         }
5337       }
5338   }
5339
5340   return Changed ? &I : 0;
5341 }
5342
5343 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5344                                    LLVMContext *Context) {
5345   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5346 }
5347
5348 static bool HasAddOverflow(ConstantInt *Result,
5349                            ConstantInt *In1, ConstantInt *In2,
5350                            bool IsSigned) {
5351   if (IsSigned)
5352     if (In2->getValue().isNegative())
5353       return Result->getValue().sgt(In1->getValue());
5354     else
5355       return Result->getValue().slt(In1->getValue());
5356   else
5357     return Result->getValue().ult(In1->getValue());
5358 }
5359
5360 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5361 /// overflowed for this type.
5362 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5363                             Constant *In2, LLVMContext *Context,
5364                             bool IsSigned = false) {
5365   Result = ConstantExpr::getAdd(In1, In2);
5366
5367   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5368     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5369       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5370       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5371                          ExtractElement(In1, Idx, Context),
5372                          ExtractElement(In2, Idx, Context),
5373                          IsSigned))
5374         return true;
5375     }
5376     return false;
5377   }
5378
5379   return HasAddOverflow(cast<ConstantInt>(Result),
5380                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5381                         IsSigned);
5382 }
5383
5384 static bool HasSubOverflow(ConstantInt *Result,
5385                            ConstantInt *In1, ConstantInt *In2,
5386                            bool IsSigned) {
5387   if (IsSigned)
5388     if (In2->getValue().isNegative())
5389       return Result->getValue().slt(In1->getValue());
5390     else
5391       return Result->getValue().sgt(In1->getValue());
5392   else
5393     return Result->getValue().ugt(In1->getValue());
5394 }
5395
5396 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5397 /// overflowed for this type.
5398 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5399                             Constant *In2, LLVMContext *Context,
5400                             bool IsSigned = false) {
5401   Result = ConstantExpr::getSub(In1, In2);
5402
5403   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5404     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5405       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5406       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5407                          ExtractElement(In1, Idx, Context),
5408                          ExtractElement(In2, Idx, Context),
5409                          IsSigned))
5410         return true;
5411     }
5412     return false;
5413   }
5414
5415   return HasSubOverflow(cast<ConstantInt>(Result),
5416                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5417                         IsSigned);
5418 }
5419
5420 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5421 /// code necessary to compute the offset from the base pointer (without adding
5422 /// in the base pointer).  Return the result as a signed integer of intptr size.
5423 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5424   TargetData &TD = *IC.getTargetData();
5425   gep_type_iterator GTI = gep_type_begin(GEP);
5426   const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
5427   Value *Result = Constant::getNullValue(IntPtrTy);
5428
5429   // Build a mask for high order bits.
5430   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5431   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5432
5433   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5434        ++i, ++GTI) {
5435     Value *Op = *i;
5436     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5437     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5438       if (OpC->isZero()) continue;
5439       
5440       // Handle a struct index, which adds its field offset to the pointer.
5441       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5442         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5443         
5444         Result = IC.Builder->CreateAdd(Result,
5445                                        ConstantInt::get(IntPtrTy, Size),
5446                                        GEP->getName()+".offs");
5447         continue;
5448       }
5449       
5450       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5451       Constant *OC =
5452               ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5453       Scale = ConstantExpr::getMul(OC, Scale);
5454       // Emit an add instruction.
5455       Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
5456       continue;
5457     }
5458     // Convert to correct type.
5459     if (Op->getType() != IntPtrTy)
5460       Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
5461     if (Size != 1) {
5462       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5463       // We'll let instcombine(mul) convert this to a shl if possible.
5464       Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
5465     }
5466
5467     // Emit an add instruction.
5468     Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
5469   }
5470   return Result;
5471 }
5472
5473
5474 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5475 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
5476 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
5477 /// be complex, and scales are involved.  The above expression would also be
5478 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5479 /// This later form is less amenable to optimization though, and we are allowed
5480 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5481 ///
5482 /// If we can't emit an optimized form for this expression, this returns null.
5483 /// 
5484 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5485                                           InstCombiner &IC) {
5486   TargetData &TD = *IC.getTargetData();
5487   gep_type_iterator GTI = gep_type_begin(GEP);
5488
5489   // Check to see if this gep only has a single variable index.  If so, and if
5490   // any constant indices are a multiple of its scale, then we can compute this
5491   // in terms of the scale of the variable index.  For example, if the GEP
5492   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5493   // because the expression will cross zero at the same point.
5494   unsigned i, e = GEP->getNumOperands();
5495   int64_t Offset = 0;
5496   for (i = 1; i != e; ++i, ++GTI) {
5497     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5498       // Compute the aggregate offset of constant indices.
5499       if (CI->isZero()) continue;
5500
5501       // Handle a struct index, which adds its field offset to the pointer.
5502       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5503         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5504       } else {
5505         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5506         Offset += Size*CI->getSExtValue();
5507       }
5508     } else {
5509       // Found our variable index.
5510       break;
5511     }
5512   }
5513   
5514   // If there are no variable indices, we must have a constant offset, just
5515   // evaluate it the general way.
5516   if (i == e) return 0;
5517   
5518   Value *VariableIdx = GEP->getOperand(i);
5519   // Determine the scale factor of the variable element.  For example, this is
5520   // 4 if the variable index is into an array of i32.
5521   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5522   
5523   // Verify that there are no other variable indices.  If so, emit the hard way.
5524   for (++i, ++GTI; i != e; ++i, ++GTI) {
5525     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5526     if (!CI) return 0;
5527    
5528     // Compute the aggregate offset of constant indices.
5529     if (CI->isZero()) continue;
5530     
5531     // Handle a struct index, which adds its field offset to the pointer.
5532     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5533       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5534     } else {
5535       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5536       Offset += Size*CI->getSExtValue();
5537     }
5538   }
5539   
5540   // Okay, we know we have a single variable index, which must be a
5541   // pointer/array/vector index.  If there is no offset, life is simple, return
5542   // the index.
5543   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5544   if (Offset == 0) {
5545     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5546     // we don't need to bother extending: the extension won't affect where the
5547     // computation crosses zero.
5548     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5549       VariableIdx = new TruncInst(VariableIdx, 
5550                                   TD.getIntPtrType(VariableIdx->getContext()),
5551                                   VariableIdx->getName(), &I);
5552     return VariableIdx;
5553   }
5554   
5555   // Otherwise, there is an index.  The computation we will do will be modulo
5556   // the pointer size, so get it.
5557   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5558   
5559   Offset &= PtrSizeMask;
5560   VariableScale &= PtrSizeMask;
5561
5562   // To do this transformation, any constant index must be a multiple of the
5563   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5564   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5565   // multiple of the variable scale.
5566   int64_t NewOffs = Offset / (int64_t)VariableScale;
5567   if (Offset != NewOffs*(int64_t)VariableScale)
5568     return 0;
5569
5570   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5571   const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
5572   if (VariableIdx->getType() != IntPtrTy)
5573     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5574                                               true /*SExt*/, 
5575                                               VariableIdx->getName(), &I);
5576   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5577   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5578 }
5579
5580
5581 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5582 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5583 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5584                                        ICmpInst::Predicate Cond,
5585                                        Instruction &I) {
5586   // Look through bitcasts.
5587   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5588     RHS = BCI->getOperand(0);
5589
5590   Value *PtrBase = GEPLHS->getOperand(0);
5591   if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5592     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5593     // This transformation (ignoring the base and scales) is valid because we
5594     // know pointers can't overflow since the gep is inbounds.  See if we can
5595     // output an optimized form.
5596     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5597     
5598     // If not, synthesize the offset the hard way.
5599     if (Offset == 0)
5600       Offset = EmitGEPOffset(GEPLHS, I, *this);
5601     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5602                         Constant::getNullValue(Offset->getType()));
5603   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5604     // If the base pointers are different, but the indices are the same, just
5605     // compare the base pointer.
5606     if (PtrBase != GEPRHS->getOperand(0)) {
5607       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5608       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5609                         GEPRHS->getOperand(0)->getType();
5610       if (IndicesTheSame)
5611         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5612           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5613             IndicesTheSame = false;
5614             break;
5615           }
5616
5617       // If all indices are the same, just compare the base pointers.
5618       if (IndicesTheSame)
5619         return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5620                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5621
5622       // Otherwise, the base pointers are different and the indices are
5623       // different, bail out.
5624       return 0;
5625     }
5626
5627     // If one of the GEPs has all zero indices, recurse.
5628     bool AllZeros = true;
5629     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5630       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5631           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5632         AllZeros = false;
5633         break;
5634       }
5635     if (AllZeros)
5636       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5637                           ICmpInst::getSwappedPredicate(Cond), I);
5638
5639     // If the other GEP has all zero indices, recurse.
5640     AllZeros = true;
5641     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5642       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5643           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5644         AllZeros = false;
5645         break;
5646       }
5647     if (AllZeros)
5648       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5649
5650     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5651       // If the GEPs only differ by one index, compare it.
5652       unsigned NumDifferences = 0;  // Keep track of # differences.
5653       unsigned DiffOperand = 0;     // The operand that differs.
5654       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5655         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5656           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5657                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5658             // Irreconcilable differences.
5659             NumDifferences = 2;
5660             break;
5661           } else {
5662             if (NumDifferences++) break;
5663             DiffOperand = i;
5664           }
5665         }
5666
5667       if (NumDifferences == 0)   // SAME GEP?
5668         return ReplaceInstUsesWith(I, // No comparison is needed here.
5669                                    ConstantInt::get(Type::getInt1Ty(*Context),
5670                                              ICmpInst::isTrueWhenEqual(Cond)));
5671
5672       else if (NumDifferences == 1) {
5673         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5674         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5675         // Make sure we do a signed comparison here.
5676         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5677       }
5678     }
5679
5680     // Only lower this if the icmp is the only user of the GEP or if we expect
5681     // the result to fold to a constant!
5682     if (TD &&
5683         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5684         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5685       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5686       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5687       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5688       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5689     }
5690   }
5691   return 0;
5692 }
5693
5694 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5695 ///
5696 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5697                                                 Instruction *LHSI,
5698                                                 Constant *RHSC) {
5699   if (!isa<ConstantFP>(RHSC)) return 0;
5700   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5701   
5702   // Get the width of the mantissa.  We don't want to hack on conversions that
5703   // might lose information from the integer, e.g. "i64 -> float"
5704   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5705   if (MantissaWidth == -1) return 0;  // Unknown.
5706   
5707   // Check to see that the input is converted from an integer type that is small
5708   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5709   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5710   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5711   
5712   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5713   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5714   if (LHSUnsigned)
5715     ++InputSize;
5716   
5717   // If the conversion would lose info, don't hack on this.
5718   if ((int)InputSize > MantissaWidth)
5719     return 0;
5720   
5721   // Otherwise, we can potentially simplify the comparison.  We know that it
5722   // will always come through as an integer value and we know the constant is
5723   // not a NAN (it would have been previously simplified).
5724   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5725   
5726   ICmpInst::Predicate Pred;
5727   switch (I.getPredicate()) {
5728   default: llvm_unreachable("Unexpected predicate!");
5729   case FCmpInst::FCMP_UEQ:
5730   case FCmpInst::FCMP_OEQ:
5731     Pred = ICmpInst::ICMP_EQ;
5732     break;
5733   case FCmpInst::FCMP_UGT:
5734   case FCmpInst::FCMP_OGT:
5735     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5736     break;
5737   case FCmpInst::FCMP_UGE:
5738   case FCmpInst::FCMP_OGE:
5739     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5740     break;
5741   case FCmpInst::FCMP_ULT:
5742   case FCmpInst::FCMP_OLT:
5743     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5744     break;
5745   case FCmpInst::FCMP_ULE:
5746   case FCmpInst::FCMP_OLE:
5747     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5748     break;
5749   case FCmpInst::FCMP_UNE:
5750   case FCmpInst::FCMP_ONE:
5751     Pred = ICmpInst::ICMP_NE;
5752     break;
5753   case FCmpInst::FCMP_ORD:
5754     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5755   case FCmpInst::FCMP_UNO:
5756     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5757   }
5758   
5759   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5760   
5761   // Now we know that the APFloat is a normal number, zero or inf.
5762   
5763   // See if the FP constant is too large for the integer.  For example,
5764   // comparing an i8 to 300.0.
5765   unsigned IntWidth = IntTy->getScalarSizeInBits();
5766   
5767   if (!LHSUnsigned) {
5768     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5769     // and large values.
5770     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5771     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5772                           APFloat::rmNearestTiesToEven);
5773     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5774       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5775           Pred == ICmpInst::ICMP_SLE)
5776         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5777       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5778     }
5779   } else {
5780     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5781     // +INF and large values.
5782     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5783     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5784                           APFloat::rmNearestTiesToEven);
5785     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5786       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5787           Pred == ICmpInst::ICMP_ULE)
5788         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5789       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5790     }
5791   }
5792   
5793   if (!LHSUnsigned) {
5794     // See if the RHS value is < SignedMin.
5795     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5796     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5797                           APFloat::rmNearestTiesToEven);
5798     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5799       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5800           Pred == ICmpInst::ICMP_SGE)
5801         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5802       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5803     }
5804   }
5805
5806   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5807   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5808   // casting the FP value to the integer value and back, checking for equality.
5809   // Don't do this for zero, because -0.0 is not fractional.
5810   Constant *RHSInt = LHSUnsigned
5811     ? ConstantExpr::getFPToUI(RHSC, IntTy)
5812     : ConstantExpr::getFPToSI(RHSC, IntTy);
5813   if (!RHS.isZero()) {
5814     bool Equal = LHSUnsigned
5815       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5816       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5817     if (!Equal) {
5818       // If we had a comparison against a fractional value, we have to adjust
5819       // the compare predicate and sometimes the value.  RHSC is rounded towards
5820       // zero at this point.
5821       switch (Pred) {
5822       default: llvm_unreachable("Unexpected integer comparison!");
5823       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5824         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5825       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5826         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5827       case ICmpInst::ICMP_ULE:
5828         // (float)int <= 4.4   --> int <= 4
5829         // (float)int <= -4.4  --> false
5830         if (RHS.isNegative())
5831           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5832         break;
5833       case ICmpInst::ICMP_SLE:
5834         // (float)int <= 4.4   --> int <= 4
5835         // (float)int <= -4.4  --> int < -4
5836         if (RHS.isNegative())
5837           Pred = ICmpInst::ICMP_SLT;
5838         break;
5839       case ICmpInst::ICMP_ULT:
5840         // (float)int < -4.4   --> false
5841         // (float)int < 4.4    --> int <= 4
5842         if (RHS.isNegative())
5843           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5844         Pred = ICmpInst::ICMP_ULE;
5845         break;
5846       case ICmpInst::ICMP_SLT:
5847         // (float)int < -4.4   --> int < -4
5848         // (float)int < 4.4    --> int <= 4
5849         if (!RHS.isNegative())
5850           Pred = ICmpInst::ICMP_SLE;
5851         break;
5852       case ICmpInst::ICMP_UGT:
5853         // (float)int > 4.4    --> int > 4
5854         // (float)int > -4.4   --> true
5855         if (RHS.isNegative())
5856           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5857         break;
5858       case ICmpInst::ICMP_SGT:
5859         // (float)int > 4.4    --> int > 4
5860         // (float)int > -4.4   --> int >= -4
5861         if (RHS.isNegative())
5862           Pred = ICmpInst::ICMP_SGE;
5863         break;
5864       case ICmpInst::ICMP_UGE:
5865         // (float)int >= -4.4   --> true
5866         // (float)int >= 4.4    --> int > 4
5867         if (!RHS.isNegative())
5868           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5869         Pred = ICmpInst::ICMP_UGT;
5870         break;
5871       case ICmpInst::ICMP_SGE:
5872         // (float)int >= -4.4   --> int >= -4
5873         // (float)int >= 4.4    --> int > 4
5874         if (!RHS.isNegative())
5875           Pred = ICmpInst::ICMP_SGT;
5876         break;
5877       }
5878     }
5879   }
5880
5881   // Lower this FP comparison into an appropriate integer version of the
5882   // comparison.
5883   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5884 }
5885
5886 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5887   bool Changed = SimplifyCompare(I);
5888   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5889
5890   // Fold trivial predicates.
5891   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5892     return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
5893   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5894     return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
5895   
5896   // Simplify 'fcmp pred X, X'
5897   if (Op0 == Op1) {
5898     switch (I.getPredicate()) {
5899     default: llvm_unreachable("Unknown predicate!");
5900     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5901     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5902     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5903       return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
5904     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5905     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5906     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5907       return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
5908       
5909     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5910     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5911     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5912     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5913       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5914       I.setPredicate(FCmpInst::FCMP_UNO);
5915       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5916       return &I;
5917       
5918     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5919     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5920     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5921     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5922       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5923       I.setPredicate(FCmpInst::FCMP_ORD);
5924       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5925       return &I;
5926     }
5927   }
5928     
5929   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5930     return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
5931
5932   // Handle fcmp with constant RHS
5933   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5934     // If the constant is a nan, see if we can fold the comparison based on it.
5935     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5936       if (CFP->getValueAPF().isNaN()) {
5937         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5938           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5939         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5940                "Comparison must be either ordered or unordered!");
5941         // True if unordered.
5942         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5943       }
5944     }
5945     
5946     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5947       switch (LHSI->getOpcode()) {
5948       case Instruction::PHI:
5949         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5950         // block.  If in the same block, we're encouraging jump threading.  If
5951         // not, we are just pessimizing the code by making an i1 phi.
5952         if (LHSI->getParent() == I.getParent())
5953           if (Instruction *NV = FoldOpIntoPhi(I, true))
5954             return NV;
5955         break;
5956       case Instruction::SIToFP:
5957       case Instruction::UIToFP:
5958         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5959           return NV;
5960         break;
5961       case Instruction::Select:
5962         // If either operand of the select is a constant, we can fold the
5963         // comparison into the select arms, which will cause one to be
5964         // constant folded and the select turned into a bitwise or.
5965         Value *Op1 = 0, *Op2 = 0;
5966         if (LHSI->hasOneUse()) {
5967           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5968             // Fold the known value into the constant operand.
5969             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5970             // Insert a new FCmp of the other select operand.
5971             Op2 = Builder->CreateFCmp(I.getPredicate(),
5972                                       LHSI->getOperand(2), RHSC, I.getName());
5973           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5974             // Fold the known value into the constant operand.
5975             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5976             // Insert a new FCmp of the other select operand.
5977             Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5978                                       RHSC, I.getName());
5979           }
5980         }
5981
5982         if (Op1)
5983           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5984         break;
5985       }
5986   }
5987
5988   return Changed ? &I : 0;
5989 }
5990
5991 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5992   bool Changed = SimplifyCompare(I);
5993   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5994   const Type *Ty = Op0->getType();
5995
5996   // icmp X, X
5997   if (Op0 == Op1)
5998     return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
5999                                                    I.isTrueWhenEqual()));
6000
6001   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
6002     return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
6003   
6004   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
6005   // addresses never equal each other!  We already know that Op0 != Op1.
6006   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) || 
6007        isa<ConstantPointerNull>(Op0)) &&
6008       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) || 
6009        isa<ConstantPointerNull>(Op1)))
6010     return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context), 
6011                                                    !I.isTrueWhenEqual()));
6012
6013   // icmp's with boolean values can always be turned into bitwise operations
6014   if (Ty == Type::getInt1Ty(*Context)) {
6015     switch (I.getPredicate()) {
6016     default: llvm_unreachable("Invalid icmp instruction!");
6017     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
6018       Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
6019       return BinaryOperator::CreateNot(Xor);
6020     }
6021     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
6022       return BinaryOperator::CreateXor(Op0, Op1);
6023
6024     case ICmpInst::ICMP_UGT:
6025       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
6026       // FALL THROUGH
6027     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
6028       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
6029       return BinaryOperator::CreateAnd(Not, Op1);
6030     }
6031     case ICmpInst::ICMP_SGT:
6032       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
6033       // FALL THROUGH
6034     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
6035       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
6036       return BinaryOperator::CreateAnd(Not, Op0);
6037     }
6038     case ICmpInst::ICMP_UGE:
6039       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6040       // FALL THROUGH
6041     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6042       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
6043       return BinaryOperator::CreateOr(Not, Op1);
6044     }
6045     case ICmpInst::ICMP_SGE:
6046       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6047       // FALL THROUGH
6048     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6049       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
6050       return BinaryOperator::CreateOr(Not, Op0);
6051     }
6052     }
6053   }
6054
6055   unsigned BitWidth = 0;
6056   if (TD)
6057     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6058   else if (Ty->isIntOrIntVector())
6059     BitWidth = Ty->getScalarSizeInBits();
6060
6061   bool isSignBit = false;
6062
6063   // See if we are doing a comparison with a constant.
6064   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6065     Value *A = 0, *B = 0;
6066     
6067     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6068     if (I.isEquality() && CI->isNullValue() &&
6069         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
6070       // (icmp cond A B) if cond is equality
6071       return new ICmpInst(I.getPredicate(), A, B);
6072     }
6073     
6074     // If we have an icmp le or icmp ge instruction, turn it into the
6075     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6076     // them being folded in the code below.
6077     switch (I.getPredicate()) {
6078     default: break;
6079     case ICmpInst::ICMP_ULE:
6080       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6081         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6082       return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
6083                           AddOne(CI));
6084     case ICmpInst::ICMP_SLE:
6085       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6086         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6087       return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6088                           AddOne(CI));
6089     case ICmpInst::ICMP_UGE:
6090       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6091         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6092       return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
6093                           SubOne(CI));
6094     case ICmpInst::ICMP_SGE:
6095       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6096         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6097       return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6098                           SubOne(CI));
6099     }
6100     
6101     // If this comparison is a normal comparison, it demands all
6102     // bits, if it is a sign bit comparison, it only demands the sign bit.
6103     bool UnusedBit;
6104     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6105   }
6106
6107   // See if we can fold the comparison based on range information we can get
6108   // by checking whether bits are known to be zero or one in the input.
6109   if (BitWidth != 0) {
6110     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6111     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6112
6113     if (SimplifyDemandedBits(I.getOperandUse(0),
6114                              isSignBit ? APInt::getSignBit(BitWidth)
6115                                        : APInt::getAllOnesValue(BitWidth),
6116                              Op0KnownZero, Op0KnownOne, 0))
6117       return &I;
6118     if (SimplifyDemandedBits(I.getOperandUse(1),
6119                              APInt::getAllOnesValue(BitWidth),
6120                              Op1KnownZero, Op1KnownOne, 0))
6121       return &I;
6122
6123     // Given the known and unknown bits, compute a range that the LHS could be
6124     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6125     // EQ and NE we use unsigned values.
6126     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6127     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6128     if (I.isSigned()) {
6129       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6130                                              Op0Min, Op0Max);
6131       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6132                                              Op1Min, Op1Max);
6133     } else {
6134       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6135                                                Op0Min, Op0Max);
6136       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6137                                                Op1Min, Op1Max);
6138     }
6139
6140     // If Min and Max are known to be the same, then SimplifyDemandedBits
6141     // figured out that the LHS is a constant.  Just constant fold this now so
6142     // that code below can assume that Min != Max.
6143     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6144       return new ICmpInst(I.getPredicate(),
6145                           ConstantInt::get(*Context, Op0Min), Op1);
6146     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6147       return new ICmpInst(I.getPredicate(), Op0,
6148                           ConstantInt::get(*Context, Op1Min));
6149
6150     // Based on the range information we know about the LHS, see if we can
6151     // simplify this comparison.  For example, (x&4) < 8  is always true.
6152     switch (I.getPredicate()) {
6153     default: llvm_unreachable("Unknown icmp opcode!");
6154     case ICmpInst::ICMP_EQ:
6155       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6156         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6157       break;
6158     case ICmpInst::ICMP_NE:
6159       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6160         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6161       break;
6162     case ICmpInst::ICMP_ULT:
6163       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6164         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6165       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6166         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6167       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6168         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6169       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6170         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6171           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6172                               SubOne(CI));
6173
6174         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6175         if (CI->isMinValue(true))
6176           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6177                            Constant::getAllOnesValue(Op0->getType()));
6178       }
6179       break;
6180     case ICmpInst::ICMP_UGT:
6181       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6182         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6183       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6184         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6185
6186       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6187         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6188       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6189         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6190           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6191                               AddOne(CI));
6192
6193         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6194         if (CI->isMaxValue(true))
6195           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6196                               Constant::getNullValue(Op0->getType()));
6197       }
6198       break;
6199     case ICmpInst::ICMP_SLT:
6200       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6201         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6202       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6203         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6204       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6205         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6206       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6207         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6208           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6209                               SubOne(CI));
6210       }
6211       break;
6212     case ICmpInst::ICMP_SGT:
6213       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6214         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6215       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6216         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6217
6218       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6219         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6220       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6221         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6222           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6223                               AddOne(CI));
6224       }
6225       break;
6226     case ICmpInst::ICMP_SGE:
6227       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6228       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6229         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6230       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6231         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6232       break;
6233     case ICmpInst::ICMP_SLE:
6234       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6235       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6236         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6237       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6238         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6239       break;
6240     case ICmpInst::ICMP_UGE:
6241       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6242       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6243         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6244       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6245         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6246       break;
6247     case ICmpInst::ICMP_ULE:
6248       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6249       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6250         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6251       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6252         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6253       break;
6254     }
6255
6256     // Turn a signed comparison into an unsigned one if both operands
6257     // are known to have the same sign.
6258     if (I.isSigned() &&
6259         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6260          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6261       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6262   }
6263
6264   // Test if the ICmpInst instruction is used exclusively by a select as
6265   // part of a minimum or maximum operation. If so, refrain from doing
6266   // any other folding. This helps out other analyses which understand
6267   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6268   // and CodeGen. And in this case, at least one of the comparison
6269   // operands has at least one user besides the compare (the select),
6270   // which would often largely negate the benefit of folding anyway.
6271   if (I.hasOneUse())
6272     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6273       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6274           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6275         return 0;
6276
6277   // See if we are doing a comparison between a constant and an instruction that
6278   // can be folded into the comparison.
6279   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6280     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6281     // instruction, see if that instruction also has constants so that the 
6282     // instruction can be folded into the icmp 
6283     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6284       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6285         return Res;
6286   }
6287
6288   // Handle icmp with constant (but not simple integer constant) RHS
6289   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6290     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6291       switch (LHSI->getOpcode()) {
6292       case Instruction::GetElementPtr:
6293         if (RHSC->isNullValue()) {
6294           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6295           bool isAllZeros = true;
6296           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6297             if (!isa<Constant>(LHSI->getOperand(i)) ||
6298                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6299               isAllZeros = false;
6300               break;
6301             }
6302           if (isAllZeros)
6303             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6304                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6305         }
6306         break;
6307
6308       case Instruction::PHI:
6309         // Only fold icmp into the PHI if the phi and icmp are in the same
6310         // block.  If in the same block, we're encouraging jump threading.  If
6311         // not, we are just pessimizing the code by making an i1 phi.
6312         if (LHSI->getParent() == I.getParent())
6313           if (Instruction *NV = FoldOpIntoPhi(I, true))
6314             return NV;
6315         break;
6316       case Instruction::Select: {
6317         // If either operand of the select is a constant, we can fold the
6318         // comparison into the select arms, which will cause one to be
6319         // constant folded and the select turned into a bitwise or.
6320         Value *Op1 = 0, *Op2 = 0;
6321         if (LHSI->hasOneUse()) {
6322           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6323             // Fold the known value into the constant operand.
6324             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6325             // Insert a new ICmp of the other select operand.
6326             Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6327                                       RHSC, I.getName());
6328           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6329             // Fold the known value into the constant operand.
6330             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6331             // Insert a new ICmp of the other select operand.
6332             Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6333                                       RHSC, I.getName());
6334           }
6335         }
6336
6337         if (Op1)
6338           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6339         break;
6340       }
6341       case Instruction::Call:
6342         // If we have (malloc != null), and if the malloc has a single use, we
6343         // can assume it is successful and remove the malloc.
6344         if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6345             isa<ConstantPointerNull>(RHSC)) {
6346           // Need to explicitly erase malloc call here, instead of adding it to
6347           // Worklist, because it won't get DCE'd from the Worklist since
6348           // isInstructionTriviallyDead() returns false for function calls.
6349           // It is OK to replace LHSI/MallocCall with Undef because the 
6350           // instruction that uses it will be erased via Worklist.
6351           if (extractMallocCall(LHSI)) {
6352             LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6353             EraseInstFromFunction(*LHSI);
6354             return ReplaceInstUsesWith(I,
6355                                      ConstantInt::get(Type::getInt1Ty(*Context),
6356                                                       !I.isTrueWhenEqual()));
6357           }
6358           if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6359             if (MallocCall->hasOneUse()) {
6360               MallocCall->replaceAllUsesWith(
6361                                         UndefValue::get(MallocCall->getType()));
6362               EraseInstFromFunction(*MallocCall);
6363               Worklist.Add(LHSI); // The malloc's bitcast use.
6364               return ReplaceInstUsesWith(I,
6365                                      ConstantInt::get(Type::getInt1Ty(*Context),
6366                                                       !I.isTrueWhenEqual()));
6367             }
6368         }
6369         break;
6370       }
6371   }
6372
6373   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6374   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6375     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6376       return NI;
6377   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6378     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6379                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6380       return NI;
6381
6382   // Test to see if the operands of the icmp are casted versions of other
6383   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6384   // now.
6385   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6386     if (isa<PointerType>(Op0->getType()) && 
6387         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6388       // We keep moving the cast from the left operand over to the right
6389       // operand, where it can often be eliminated completely.
6390       Op0 = CI->getOperand(0);
6391
6392       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6393       // so eliminate it as well.
6394       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6395         Op1 = CI2->getOperand(0);
6396
6397       // If Op1 is a constant, we can fold the cast into the constant.
6398       if (Op0->getType() != Op1->getType()) {
6399         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6400           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6401         } else {
6402           // Otherwise, cast the RHS right before the icmp
6403           Op1 = Builder->CreateBitCast(Op1, Op0->getType());
6404         }
6405       }
6406       return new ICmpInst(I.getPredicate(), Op0, Op1);
6407     }
6408   }
6409   
6410   if (isa<CastInst>(Op0)) {
6411     // Handle the special case of: icmp (cast bool to X), <cst>
6412     // This comes up when you have code like
6413     //   int X = A < B;
6414     //   if (X) ...
6415     // For generality, we handle any zero-extension of any operand comparison
6416     // with a constant or another cast from the same type.
6417     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6418       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6419         return R;
6420   }
6421   
6422   // See if it's the same type of instruction on the left and right.
6423   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6424     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6425       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6426           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6427         switch (Op0I->getOpcode()) {
6428         default: break;
6429         case Instruction::Add:
6430         case Instruction::Sub:
6431         case Instruction::Xor:
6432           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6433             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6434                                 Op1I->getOperand(0));
6435           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6436           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6437             if (CI->getValue().isSignBit()) {
6438               ICmpInst::Predicate Pred = I.isSigned()
6439                                              ? I.getUnsignedPredicate()
6440                                              : I.getSignedPredicate();
6441               return new ICmpInst(Pred, Op0I->getOperand(0),
6442                                   Op1I->getOperand(0));
6443             }
6444             
6445             if (CI->getValue().isMaxSignedValue()) {
6446               ICmpInst::Predicate Pred = I.isSigned()
6447                                              ? I.getUnsignedPredicate()
6448                                              : I.getSignedPredicate();
6449               Pred = I.getSwappedPredicate(Pred);
6450               return new ICmpInst(Pred, Op0I->getOperand(0),
6451                                   Op1I->getOperand(0));
6452             }
6453           }
6454           break;
6455         case Instruction::Mul:
6456           if (!I.isEquality())
6457             break;
6458
6459           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6460             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6461             // Mask = -1 >> count-trailing-zeros(Cst).
6462             if (!CI->isZero() && !CI->isOne()) {
6463               const APInt &AP = CI->getValue();
6464               ConstantInt *Mask = ConstantInt::get(*Context, 
6465                                       APInt::getLowBitsSet(AP.getBitWidth(),
6466                                                            AP.getBitWidth() -
6467                                                       AP.countTrailingZeros()));
6468               Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6469               Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
6470               return new ICmpInst(I.getPredicate(), And1, And2);
6471             }
6472           }
6473           break;
6474         }
6475       }
6476     }
6477   }
6478   
6479   // ~x < ~y --> y < x
6480   { Value *A, *B;
6481     if (match(Op0, m_Not(m_Value(A))) &&
6482         match(Op1, m_Not(m_Value(B))))
6483       return new ICmpInst(I.getPredicate(), B, A);
6484   }
6485   
6486   if (I.isEquality()) {
6487     Value *A, *B, *C, *D;
6488     
6489     // -x == -y --> x == y
6490     if (match(Op0, m_Neg(m_Value(A))) &&
6491         match(Op1, m_Neg(m_Value(B))))
6492       return new ICmpInst(I.getPredicate(), A, B);
6493     
6494     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6495       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6496         Value *OtherVal = A == Op1 ? B : A;
6497         return new ICmpInst(I.getPredicate(), OtherVal,
6498                             Constant::getNullValue(A->getType()));
6499       }
6500
6501       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6502         // A^c1 == C^c2 --> A == C^(c1^c2)
6503         ConstantInt *C1, *C2;
6504         if (match(B, m_ConstantInt(C1)) &&
6505             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6506           Constant *NC = 
6507                    ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6508           Value *Xor = Builder->CreateXor(C, NC, "tmp");
6509           return new ICmpInst(I.getPredicate(), A, Xor);
6510         }
6511         
6512         // A^B == A^D -> B == D
6513         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6514         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6515         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6516         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6517       }
6518     }
6519     
6520     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6521         (A == Op0 || B == Op0)) {
6522       // A == (A^B)  ->  B == 0
6523       Value *OtherVal = A == Op0 ? B : A;
6524       return new ICmpInst(I.getPredicate(), OtherVal,
6525                           Constant::getNullValue(A->getType()));
6526     }
6527
6528     // (A-B) == A  ->  B == 0
6529     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6530       return new ICmpInst(I.getPredicate(), B, 
6531                           Constant::getNullValue(B->getType()));
6532
6533     // A == (A-B)  ->  B == 0
6534     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6535       return new ICmpInst(I.getPredicate(), B,
6536                           Constant::getNullValue(B->getType()));
6537     
6538     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6539     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6540         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6541         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6542       Value *X = 0, *Y = 0, *Z = 0;
6543       
6544       if (A == C) {
6545         X = B; Y = D; Z = A;
6546       } else if (A == D) {
6547         X = B; Y = C; Z = A;
6548       } else if (B == C) {
6549         X = A; Y = D; Z = B;
6550       } else if (B == D) {
6551         X = A; Y = C; Z = B;
6552       }
6553       
6554       if (X) {   // Build (X^Y) & Z
6555         Op1 = Builder->CreateXor(X, Y, "tmp");
6556         Op1 = Builder->CreateAnd(Op1, Z, "tmp");
6557         I.setOperand(0, Op1);
6558         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6559         return &I;
6560       }
6561     }
6562   }
6563   return Changed ? &I : 0;
6564 }
6565
6566
6567 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6568 /// and CmpRHS are both known to be integer constants.
6569 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6570                                           ConstantInt *DivRHS) {
6571   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6572   const APInt &CmpRHSV = CmpRHS->getValue();
6573   
6574   // FIXME: If the operand types don't match the type of the divide 
6575   // then don't attempt this transform. The code below doesn't have the
6576   // logic to deal with a signed divide and an unsigned compare (and
6577   // vice versa). This is because (x /s C1) <s C2  produces different 
6578   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6579   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6580   // work. :(  The if statement below tests that condition and bails 
6581   // if it finds it. 
6582   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6583   if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
6584     return 0;
6585   if (DivRHS->isZero())
6586     return 0; // The ProdOV computation fails on divide by zero.
6587   if (DivIsSigned && DivRHS->isAllOnesValue())
6588     return 0; // The overflow computation also screws up here
6589   if (DivRHS->isOne())
6590     return 0; // Not worth bothering, and eliminates some funny cases
6591               // with INT_MIN.
6592
6593   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6594   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6595   // C2 (CI). By solving for X we can turn this into a range check 
6596   // instead of computing a divide. 
6597   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6598
6599   // Determine if the product overflows by seeing if the product is
6600   // not equal to the divide. Make sure we do the same kind of divide
6601   // as in the LHS instruction that we're folding. 
6602   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6603                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6604
6605   // Get the ICmp opcode
6606   ICmpInst::Predicate Pred = ICI.getPredicate();
6607
6608   // Figure out the interval that is being checked.  For example, a comparison
6609   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6610   // Compute this interval based on the constants involved and the signedness of
6611   // the compare/divide.  This computes a half-open interval, keeping track of
6612   // whether either value in the interval overflows.  After analysis each
6613   // overflow variable is set to 0 if it's corresponding bound variable is valid
6614   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6615   int LoOverflow = 0, HiOverflow = 0;
6616   Constant *LoBound = 0, *HiBound = 0;
6617   
6618   if (!DivIsSigned) {  // udiv
6619     // e.g. X/5 op 3  --> [15, 20)
6620     LoBound = Prod;
6621     HiOverflow = LoOverflow = ProdOV;
6622     if (!HiOverflow)
6623       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6624   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6625     if (CmpRHSV == 0) {       // (X / pos) op 0
6626       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6627       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6628       HiBound = DivRHS;
6629     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6630       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6631       HiOverflow = LoOverflow = ProdOV;
6632       if (!HiOverflow)
6633         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6634     } else {                       // (X / pos) op neg
6635       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6636       HiBound = AddOne(Prod);
6637       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6638       if (!LoOverflow) {
6639         ConstantInt* DivNeg =
6640                          cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6641         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6642                                      true) ? -1 : 0;
6643        }
6644     }
6645   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6646     if (CmpRHSV == 0) {       // (X / neg) op 0
6647       // e.g. X/-5 op 0  --> [-4, 5)
6648       LoBound = AddOne(DivRHS);
6649       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6650       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6651         HiOverflow = 1;            // [INTMIN+1, overflow)
6652         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6653       }
6654     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6655       // e.g. X/-5 op 3  --> [-19, -14)
6656       HiBound = AddOne(Prod);
6657       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6658       if (!LoOverflow)
6659         LoOverflow = AddWithOverflow(LoBound, HiBound,
6660                                      DivRHS, Context, true) ? -1 : 0;
6661     } else {                       // (X / neg) op neg
6662       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6663       LoOverflow = HiOverflow = ProdOV;
6664       if (!HiOverflow)
6665         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6666     }
6667     
6668     // Dividing by a negative swaps the condition.  LT <-> GT
6669     Pred = ICmpInst::getSwappedPredicate(Pred);
6670   }
6671
6672   Value *X = DivI->getOperand(0);
6673   switch (Pred) {
6674   default: llvm_unreachable("Unhandled icmp opcode!");
6675   case ICmpInst::ICMP_EQ:
6676     if (LoOverflow && HiOverflow)
6677       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6678     else if (HiOverflow)
6679       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6680                           ICmpInst::ICMP_UGE, X, LoBound);
6681     else if (LoOverflow)
6682       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6683                           ICmpInst::ICMP_ULT, X, HiBound);
6684     else
6685       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6686   case ICmpInst::ICMP_NE:
6687     if (LoOverflow && HiOverflow)
6688       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6689     else if (HiOverflow)
6690       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6691                           ICmpInst::ICMP_ULT, X, LoBound);
6692     else if (LoOverflow)
6693       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6694                           ICmpInst::ICMP_UGE, X, HiBound);
6695     else
6696       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6697   case ICmpInst::ICMP_ULT:
6698   case ICmpInst::ICMP_SLT:
6699     if (LoOverflow == +1)   // Low bound is greater than input range.
6700       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6701     if (LoOverflow == -1)   // Low bound is less than input range.
6702       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6703     return new ICmpInst(Pred, X, LoBound);
6704   case ICmpInst::ICMP_UGT:
6705   case ICmpInst::ICMP_SGT:
6706     if (HiOverflow == +1)       // High bound greater than input range.
6707       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6708     else if (HiOverflow == -1)  // High bound less than input range.
6709       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6710     if (Pred == ICmpInst::ICMP_UGT)
6711       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6712     else
6713       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6714   }
6715 }
6716
6717
6718 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6719 ///
6720 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6721                                                           Instruction *LHSI,
6722                                                           ConstantInt *RHS) {
6723   const APInt &RHSV = RHS->getValue();
6724   
6725   switch (LHSI->getOpcode()) {
6726   case Instruction::Trunc:
6727     if (ICI.isEquality() && LHSI->hasOneUse()) {
6728       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6729       // of the high bits truncated out of x are known.
6730       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6731              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6732       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6733       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6734       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6735       
6736       // If all the high bits are known, we can do this xform.
6737       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6738         // Pull in the high bits from known-ones set.
6739         APInt NewRHS(RHS->getValue());
6740         NewRHS.zext(SrcBits);
6741         NewRHS |= KnownOne;
6742         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6743                             ConstantInt::get(*Context, NewRHS));
6744       }
6745     }
6746     break;
6747       
6748   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6749     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6750       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6751       // fold the xor.
6752       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6753           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6754         Value *CompareVal = LHSI->getOperand(0);
6755         
6756         // If the sign bit of the XorCST is not set, there is no change to
6757         // the operation, just stop using the Xor.
6758         if (!XorCST->getValue().isNegative()) {
6759           ICI.setOperand(0, CompareVal);
6760           Worklist.Add(LHSI);
6761           return &ICI;
6762         }
6763         
6764         // Was the old condition true if the operand is positive?
6765         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6766         
6767         // If so, the new one isn't.
6768         isTrueIfPositive ^= true;
6769         
6770         if (isTrueIfPositive)
6771           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
6772                               SubOne(RHS));
6773         else
6774           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
6775                               AddOne(RHS));
6776       }
6777
6778       if (LHSI->hasOneUse()) {
6779         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6780         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6781           const APInt &SignBit = XorCST->getValue();
6782           ICmpInst::Predicate Pred = ICI.isSigned()
6783                                          ? ICI.getUnsignedPredicate()
6784                                          : ICI.getSignedPredicate();
6785           return new ICmpInst(Pred, LHSI->getOperand(0),
6786                               ConstantInt::get(*Context, RHSV ^ SignBit));
6787         }
6788
6789         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6790         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6791           const APInt &NotSignBit = XorCST->getValue();
6792           ICmpInst::Predicate Pred = ICI.isSigned()
6793                                          ? ICI.getUnsignedPredicate()
6794                                          : ICI.getSignedPredicate();
6795           Pred = ICI.getSwappedPredicate(Pred);
6796           return new ICmpInst(Pred, LHSI->getOperand(0),
6797                               ConstantInt::get(*Context, RHSV ^ NotSignBit));
6798         }
6799       }
6800     }
6801     break;
6802   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6803     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6804         LHSI->getOperand(0)->hasOneUse()) {
6805       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6806       
6807       // If the LHS is an AND of a truncating cast, we can widen the
6808       // and/compare to be the input width without changing the value
6809       // produced, eliminating a cast.
6810       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6811         // We can do this transformation if either the AND constant does not
6812         // have its sign bit set or if it is an equality comparison. 
6813         // Extending a relational comparison when we're checking the sign
6814         // bit would not work.
6815         if (Cast->hasOneUse() &&
6816             (ICI.isEquality() ||
6817              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6818           uint32_t BitWidth = 
6819             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6820           APInt NewCST = AndCST->getValue();
6821           NewCST.zext(BitWidth);
6822           APInt NewCI = RHSV;
6823           NewCI.zext(BitWidth);
6824           Value *NewAnd = 
6825             Builder->CreateAnd(Cast->getOperand(0),
6826                            ConstantInt::get(*Context, NewCST), LHSI->getName());
6827           return new ICmpInst(ICI.getPredicate(), NewAnd,
6828                               ConstantInt::get(*Context, NewCI));
6829         }
6830       }
6831       
6832       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6833       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6834       // happens a LOT in code produced by the C front-end, for bitfield
6835       // access.
6836       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6837       if (Shift && !Shift->isShift())
6838         Shift = 0;
6839       
6840       ConstantInt *ShAmt;
6841       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6842       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6843       const Type *AndTy = AndCST->getType();          // Type of the and.
6844       
6845       // We can fold this as long as we can't shift unknown bits
6846       // into the mask.  This can only happen with signed shift
6847       // rights, as they sign-extend.
6848       if (ShAmt) {
6849         bool CanFold = Shift->isLogicalShift();
6850         if (!CanFold) {
6851           // To test for the bad case of the signed shr, see if any
6852           // of the bits shifted in could be tested after the mask.
6853           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6854           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6855           
6856           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6857           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6858                AndCST->getValue()) == 0)
6859             CanFold = true;
6860         }
6861         
6862         if (CanFold) {
6863           Constant *NewCst;
6864           if (Shift->getOpcode() == Instruction::Shl)
6865             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6866           else
6867             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6868           
6869           // Check to see if we are shifting out any of the bits being
6870           // compared.
6871           if (ConstantExpr::get(Shift->getOpcode(),
6872                                        NewCst, ShAmt) != RHS) {
6873             // If we shifted bits out, the fold is not going to work out.
6874             // As a special case, check to see if this means that the
6875             // result is always true or false now.
6876             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6877               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6878             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6879               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6880           } else {
6881             ICI.setOperand(1, NewCst);
6882             Constant *NewAndCST;
6883             if (Shift->getOpcode() == Instruction::Shl)
6884               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6885             else
6886               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6887             LHSI->setOperand(1, NewAndCST);
6888             LHSI->setOperand(0, Shift->getOperand(0));
6889             Worklist.Add(Shift); // Shift is dead.
6890             return &ICI;
6891           }
6892         }
6893       }
6894       
6895       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6896       // preferable because it allows the C<<Y expression to be hoisted out
6897       // of a loop if Y is invariant and X is not.
6898       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6899           ICI.isEquality() && !Shift->isArithmeticShift() &&
6900           !isa<Constant>(Shift->getOperand(0))) {
6901         // Compute C << Y.
6902         Value *NS;
6903         if (Shift->getOpcode() == Instruction::LShr) {
6904           NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
6905         } else {
6906           // Insert a logical shift.
6907           NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
6908         }
6909         
6910         // Compute X & (C << Y).
6911         Value *NewAnd = 
6912           Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6913         
6914         ICI.setOperand(0, NewAnd);
6915         return &ICI;
6916       }
6917     }
6918     break;
6919     
6920   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6921     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6922     if (!ShAmt) break;
6923     
6924     uint32_t TypeBits = RHSV.getBitWidth();
6925     
6926     // Check that the shift amount is in range.  If not, don't perform
6927     // undefined shifts.  When the shift is visited it will be
6928     // simplified.
6929     if (ShAmt->uge(TypeBits))
6930       break;
6931     
6932     if (ICI.isEquality()) {
6933       // If we are comparing against bits always shifted out, the
6934       // comparison cannot succeed.
6935       Constant *Comp =
6936         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
6937                                                                  ShAmt);
6938       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6939         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6940         Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6941         return ReplaceInstUsesWith(ICI, Cst);
6942       }
6943       
6944       if (LHSI->hasOneUse()) {
6945         // Otherwise strength reduce the shift into an and.
6946         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6947         Constant *Mask =
6948           ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits, 
6949                                                        TypeBits-ShAmtVal));
6950         
6951         Value *And =
6952           Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
6953         return new ICmpInst(ICI.getPredicate(), And,
6954                             ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
6955       }
6956     }
6957     
6958     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6959     bool TrueIfSigned = false;
6960     if (LHSI->hasOneUse() &&
6961         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6962       // (X << 31) <s 0  --> (X&1) != 0
6963       Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
6964                                            (TypeBits-ShAmt->getZExtValue()-1));
6965       Value *And =
6966         Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
6967       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6968                           And, Constant::getNullValue(And->getType()));
6969     }
6970     break;
6971   }
6972     
6973   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6974   case Instruction::AShr: {
6975     // Only handle equality comparisons of shift-by-constant.
6976     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6977     if (!ShAmt || !ICI.isEquality()) break;
6978
6979     // Check that the shift amount is in range.  If not, don't perform
6980     // undefined shifts.  When the shift is visited it will be
6981     // simplified.
6982     uint32_t TypeBits = RHSV.getBitWidth();
6983     if (ShAmt->uge(TypeBits))
6984       break;
6985     
6986     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6987       
6988     // If we are comparing against bits always shifted out, the
6989     // comparison cannot succeed.
6990     APInt Comp = RHSV << ShAmtVal;
6991     if (LHSI->getOpcode() == Instruction::LShr)
6992       Comp = Comp.lshr(ShAmtVal);
6993     else
6994       Comp = Comp.ashr(ShAmtVal);
6995     
6996     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6997       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6998       Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6999       return ReplaceInstUsesWith(ICI, Cst);
7000     }
7001     
7002     // Otherwise, check to see if the bits shifted out are known to be zero.
7003     // If so, we can compare against the unshifted value:
7004     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
7005     if (LHSI->hasOneUse() &&
7006         MaskedValueIsZero(LHSI->getOperand(0), 
7007                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
7008       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
7009                           ConstantExpr::getShl(RHS, ShAmt));
7010     }
7011       
7012     if (LHSI->hasOneUse()) {
7013       // Otherwise strength reduce the shift into an and.
7014       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7015       Constant *Mask = ConstantInt::get(*Context, Val);
7016       
7017       Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7018                                       Mask, LHSI->getName()+".mask");
7019       return new ICmpInst(ICI.getPredicate(), And,
7020                           ConstantExpr::getShl(RHS, ShAmt));
7021     }
7022     break;
7023   }
7024     
7025   case Instruction::SDiv:
7026   case Instruction::UDiv:
7027     // Fold: icmp pred ([us]div X, C1), C2 -> range test
7028     // Fold this div into the comparison, producing a range check. 
7029     // Determine, based on the divide type, what the range is being 
7030     // checked.  If there is an overflow on the low or high side, remember 
7031     // it, otherwise compute the range [low, hi) bounding the new value.
7032     // See: InsertRangeTest above for the kinds of replacements possible.
7033     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7034       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7035                                           DivRHS))
7036         return R;
7037     break;
7038
7039   case Instruction::Add:
7040     // Fold: icmp pred (add, X, C1), C2
7041
7042     if (!ICI.isEquality()) {
7043       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7044       if (!LHSC) break;
7045       const APInt &LHSV = LHSC->getValue();
7046
7047       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7048                             .subtract(LHSV);
7049
7050       if (ICI.isSigned()) {
7051         if (CR.getLower().isSignBit()) {
7052           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7053                               ConstantInt::get(*Context, CR.getUpper()));
7054         } else if (CR.getUpper().isSignBit()) {
7055           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7056                               ConstantInt::get(*Context, CR.getLower()));
7057         }
7058       } else {
7059         if (CR.getLower().isMinValue()) {
7060           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7061                               ConstantInt::get(*Context, CR.getUpper()));
7062         } else if (CR.getUpper().isMinValue()) {
7063           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7064                               ConstantInt::get(*Context, CR.getLower()));
7065         }
7066       }
7067     }
7068     break;
7069   }
7070   
7071   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7072   if (ICI.isEquality()) {
7073     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7074     
7075     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7076     // the second operand is a constant, simplify a bit.
7077     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7078       switch (BO->getOpcode()) {
7079       case Instruction::SRem:
7080         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7081         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7082           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7083           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7084             Value *NewRem =
7085               Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7086                                   BO->getName());
7087             return new ICmpInst(ICI.getPredicate(), NewRem,
7088                                 Constant::getNullValue(BO->getType()));
7089           }
7090         }
7091         break;
7092       case Instruction::Add:
7093         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7094         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7095           if (BO->hasOneUse())
7096             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7097                                 ConstantExpr::getSub(RHS, BOp1C));
7098         } else if (RHSV == 0) {
7099           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7100           // efficiently invertible, or if the add has just this one use.
7101           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7102           
7103           if (Value *NegVal = dyn_castNegVal(BOp1))
7104             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
7105           else if (Value *NegVal = dyn_castNegVal(BOp0))
7106             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
7107           else if (BO->hasOneUse()) {
7108             Value *Neg = Builder->CreateNeg(BOp1);
7109             Neg->takeName(BO);
7110             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
7111           }
7112         }
7113         break;
7114       case Instruction::Xor:
7115         // For the xor case, we can xor two constants together, eliminating
7116         // the explicit xor.
7117         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7118           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
7119                               ConstantExpr::getXor(RHS, BOC));
7120         
7121         // FALLTHROUGH
7122       case Instruction::Sub:
7123         // Replace (([sub|xor] A, B) != 0) with (A != B)
7124         if (RHSV == 0)
7125           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7126                               BO->getOperand(1));
7127         break;
7128         
7129       case Instruction::Or:
7130         // If bits are being or'd in that are not present in the constant we
7131         // are comparing against, then the comparison could never succeed!
7132         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7133           Constant *NotCI = ConstantExpr::getNot(RHS);
7134           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7135             return ReplaceInstUsesWith(ICI,
7136                                        ConstantInt::get(Type::getInt1Ty(*Context), 
7137                                        isICMP_NE));
7138         }
7139         break;
7140         
7141       case Instruction::And:
7142         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7143           // If bits are being compared against that are and'd out, then the
7144           // comparison can never succeed!
7145           if ((RHSV & ~BOC->getValue()) != 0)
7146             return ReplaceInstUsesWith(ICI,
7147                                        ConstantInt::get(Type::getInt1Ty(*Context),
7148                                        isICMP_NE));
7149           
7150           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7151           if (RHS == BOC && RHSV.isPowerOf2())
7152             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7153                                 ICmpInst::ICMP_NE, LHSI,
7154                                 Constant::getNullValue(RHS->getType()));
7155           
7156           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7157           if (BOC->getValue().isSignBit()) {
7158             Value *X = BO->getOperand(0);
7159             Constant *Zero = Constant::getNullValue(X->getType());
7160             ICmpInst::Predicate pred = isICMP_NE ? 
7161               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7162             return new ICmpInst(pred, X, Zero);
7163           }
7164           
7165           // ((X & ~7) == 0) --> X < 8
7166           if (RHSV == 0 && isHighOnes(BOC)) {
7167             Value *X = BO->getOperand(0);
7168             Constant *NegX = ConstantExpr::getNeg(BOC);
7169             ICmpInst::Predicate pred = isICMP_NE ? 
7170               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7171             return new ICmpInst(pred, X, NegX);
7172           }
7173         }
7174       default: break;
7175       }
7176     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7177       // Handle icmp {eq|ne} <intrinsic>, intcst.
7178       if (II->getIntrinsicID() == Intrinsic::bswap) {
7179         Worklist.Add(II);
7180         ICI.setOperand(0, II->getOperand(1));
7181         ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7182         return &ICI;
7183       }
7184     }
7185   }
7186   return 0;
7187 }
7188
7189 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7190 /// We only handle extending casts so far.
7191 ///
7192 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7193   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7194   Value *LHSCIOp        = LHSCI->getOperand(0);
7195   const Type *SrcTy     = LHSCIOp->getType();
7196   const Type *DestTy    = LHSCI->getType();
7197   Value *RHSCIOp;
7198
7199   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7200   // integer type is the same size as the pointer type.
7201   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7202       TD->getPointerSizeInBits() ==
7203          cast<IntegerType>(DestTy)->getBitWidth()) {
7204     Value *RHSOp = 0;
7205     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7206       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7207     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7208       RHSOp = RHSC->getOperand(0);
7209       // If the pointer types don't match, insert a bitcast.
7210       if (LHSCIOp->getType() != RHSOp->getType())
7211         RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
7212     }
7213
7214     if (RHSOp)
7215       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7216   }
7217   
7218   // The code below only handles extension cast instructions, so far.
7219   // Enforce this.
7220   if (LHSCI->getOpcode() != Instruction::ZExt &&
7221       LHSCI->getOpcode() != Instruction::SExt)
7222     return 0;
7223
7224   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7225   bool isSignedCmp = ICI.isSigned();
7226
7227   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7228     // Not an extension from the same type?
7229     RHSCIOp = CI->getOperand(0);
7230     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7231       return 0;
7232     
7233     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7234     // and the other is a zext), then we can't handle this.
7235     if (CI->getOpcode() != LHSCI->getOpcode())
7236       return 0;
7237
7238     // Deal with equality cases early.
7239     if (ICI.isEquality())
7240       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7241
7242     // A signed comparison of sign extended values simplifies into a
7243     // signed comparison.
7244     if (isSignedCmp && isSignedExt)
7245       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7246
7247     // The other three cases all fold into an unsigned comparison.
7248     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7249   }
7250
7251   // If we aren't dealing with a constant on the RHS, exit early
7252   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7253   if (!CI)
7254     return 0;
7255
7256   // Compute the constant that would happen if we truncated to SrcTy then
7257   // reextended to DestTy.
7258   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7259   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7260                                                 Res1, DestTy);
7261
7262   // If the re-extended constant didn't change...
7263   if (Res2 == CI) {
7264     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7265     // For example, we might have:
7266     //    %A = sext i16 %X to i32
7267     //    %B = icmp ugt i32 %A, 1330
7268     // It is incorrect to transform this into 
7269     //    %B = icmp ugt i16 %X, 1330
7270     // because %A may have negative value. 
7271     //
7272     // However, we allow this when the compare is EQ/NE, because they are
7273     // signless.
7274     if (isSignedExt == isSignedCmp || ICI.isEquality())
7275       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7276     return 0;
7277   }
7278
7279   // The re-extended constant changed so the constant cannot be represented 
7280   // in the shorter type. Consequently, we cannot emit a simple comparison.
7281
7282   // First, handle some easy cases. We know the result cannot be equal at this
7283   // point so handle the ICI.isEquality() cases
7284   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7285     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7286   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7287     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7288
7289   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7290   // should have been folded away previously and not enter in here.
7291   Value *Result;
7292   if (isSignedCmp) {
7293     // We're performing a signed comparison.
7294     if (cast<ConstantInt>(CI)->getValue().isNegative())
7295       Result = ConstantInt::getFalse(*Context);          // X < (small) --> false
7296     else
7297       Result = ConstantInt::getTrue(*Context);           // X < (large) --> true
7298   } else {
7299     // We're performing an unsigned comparison.
7300     if (isSignedExt) {
7301       // We're performing an unsigned comp with a sign extended value.
7302       // This is true if the input is >= 0. [aka >s -1]
7303       Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7304       Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
7305     } else {
7306       // Unsigned extend & unsigned compare -> always true.
7307       Result = ConstantInt::getTrue(*Context);
7308     }
7309   }
7310
7311   // Finally, return the value computed.
7312   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7313       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7314     return ReplaceInstUsesWith(ICI, Result);
7315
7316   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7317           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7318          "ICmp should be folded!");
7319   if (Constant *CI = dyn_cast<Constant>(Result))
7320     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7321   return BinaryOperator::CreateNot(Result);
7322 }
7323
7324 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7325   return commonShiftTransforms(I);
7326 }
7327
7328 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7329   return commonShiftTransforms(I);
7330 }
7331
7332 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7333   if (Instruction *R = commonShiftTransforms(I))
7334     return R;
7335   
7336   Value *Op0 = I.getOperand(0);
7337   
7338   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7339   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7340     if (CSI->isAllOnesValue())
7341       return ReplaceInstUsesWith(I, CSI);
7342
7343   // See if we can turn a signed shr into an unsigned shr.
7344   if (MaskedValueIsZero(Op0,
7345                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7346     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7347
7348   // Arithmetic shifting an all-sign-bit value is a no-op.
7349   unsigned NumSignBits = ComputeNumSignBits(Op0);
7350   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7351     return ReplaceInstUsesWith(I, Op0);
7352
7353   return 0;
7354 }
7355
7356 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7357   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7358   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7359
7360   // shl X, 0 == X and shr X, 0 == X
7361   // shl 0, X == 0 and shr 0, X == 0
7362   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7363       Op0 == Constant::getNullValue(Op0->getType()))
7364     return ReplaceInstUsesWith(I, Op0);
7365   
7366   if (isa<UndefValue>(Op0)) {            
7367     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7368       return ReplaceInstUsesWith(I, Op0);
7369     else                                    // undef << X -> 0, undef >>u X -> 0
7370       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7371   }
7372   if (isa<UndefValue>(Op1)) {
7373     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7374       return ReplaceInstUsesWith(I, Op0);          
7375     else                                     // X << undef, X >>u undef -> 0
7376       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7377   }
7378
7379   // See if we can fold away this shift.
7380   if (SimplifyDemandedInstructionBits(I))
7381     return &I;
7382
7383   // Try to fold constant and into select arguments.
7384   if (isa<Constant>(Op0))
7385     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7386       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7387         return R;
7388
7389   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7390     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7391       return Res;
7392   return 0;
7393 }
7394
7395 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7396                                                BinaryOperator &I) {
7397   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7398
7399   // See if we can simplify any instructions used by the instruction whose sole 
7400   // purpose is to compute bits we don't care about.
7401   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7402   
7403   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7404   // a signed shift.
7405   //
7406   if (Op1->uge(TypeBits)) {
7407     if (I.getOpcode() != Instruction::AShr)
7408       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7409     else {
7410       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7411       return &I;
7412     }
7413   }
7414   
7415   // ((X*C1) << C2) == (X * (C1 << C2))
7416   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7417     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7418       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7419         return BinaryOperator::CreateMul(BO->getOperand(0),
7420                                         ConstantExpr::getShl(BOOp, Op1));
7421   
7422   // Try to fold constant and into select arguments.
7423   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7424     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7425       return R;
7426   if (isa<PHINode>(Op0))
7427     if (Instruction *NV = FoldOpIntoPhi(I))
7428       return NV;
7429   
7430   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7431   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7432     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7433     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7434     // place.  Don't try to do this transformation in this case.  Also, we
7435     // require that the input operand is a shift-by-constant so that we have
7436     // confidence that the shifts will get folded together.  We could do this
7437     // xform in more cases, but it is unlikely to be profitable.
7438     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7439         isa<ConstantInt>(TrOp->getOperand(1))) {
7440       // Okay, we'll do this xform.  Make the shift of shift.
7441       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7442       // (shift2 (shift1 & 0x00FF), c2)
7443       Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
7444
7445       // For logical shifts, the truncation has the effect of making the high
7446       // part of the register be zeros.  Emulate this by inserting an AND to
7447       // clear the top bits as needed.  This 'and' will usually be zapped by
7448       // other xforms later if dead.
7449       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7450       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7451       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7452       
7453       // The mask we constructed says what the trunc would do if occurring
7454       // between the shifts.  We want to know the effect *after* the second
7455       // shift.  We know that it is a logical shift by a constant, so adjust the
7456       // mask as appropriate.
7457       if (I.getOpcode() == Instruction::Shl)
7458         MaskV <<= Op1->getZExtValue();
7459       else {
7460         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7461         MaskV = MaskV.lshr(Op1->getZExtValue());
7462       }
7463
7464       // shift1 & 0x00FF
7465       Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7466                                       TI->getName());
7467
7468       // Return the value truncated to the interesting size.
7469       return new TruncInst(And, I.getType());
7470     }
7471   }
7472   
7473   if (Op0->hasOneUse()) {
7474     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7475       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7476       Value *V1, *V2;
7477       ConstantInt *CC;
7478       switch (Op0BO->getOpcode()) {
7479         default: break;
7480         case Instruction::Add:
7481         case Instruction::And:
7482         case Instruction::Or:
7483         case Instruction::Xor: {
7484           // These operators commute.
7485           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7486           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7487               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7488                     m_Specific(Op1)))) {
7489             Value *YS =         // (Y << C)
7490               Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7491             // (X + (Y << C))
7492             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7493                                             Op0BO->getOperand(1)->getName());
7494             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7495             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7496                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7497           }
7498           
7499           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7500           Value *Op0BOOp1 = Op0BO->getOperand(1);
7501           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7502               match(Op0BOOp1, 
7503                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7504                           m_ConstantInt(CC))) &&
7505               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7506             Value *YS =   // (Y << C)
7507               Builder->CreateShl(Op0BO->getOperand(0), Op1,
7508                                            Op0BO->getName());
7509             // X & (CC << C)
7510             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7511                                            V1->getName()+".mask");
7512             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7513           }
7514         }
7515           
7516         // FALL THROUGH.
7517         case Instruction::Sub: {
7518           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7519           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7520               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7521                     m_Specific(Op1)))) {
7522             Value *YS =  // (Y << C)
7523               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7524             // (X + (Y << C))
7525             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7526                                             Op0BO->getOperand(0)->getName());
7527             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7528             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7529                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7530           }
7531           
7532           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7533           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7534               match(Op0BO->getOperand(0),
7535                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7536                           m_ConstantInt(CC))) && V2 == Op1 &&
7537               cast<BinaryOperator>(Op0BO->getOperand(0))
7538                   ->getOperand(0)->hasOneUse()) {
7539             Value *YS = // (Y << C)
7540               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7541             // X & (CC << C)
7542             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7543                                            V1->getName()+".mask");
7544             
7545             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7546           }
7547           
7548           break;
7549         }
7550       }
7551       
7552       
7553       // If the operand is an bitwise operator with a constant RHS, and the
7554       // shift is the only use, we can pull it out of the shift.
7555       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7556         bool isValid = true;     // Valid only for And, Or, Xor
7557         bool highBitSet = false; // Transform if high bit of constant set?
7558         
7559         switch (Op0BO->getOpcode()) {
7560           default: isValid = false; break;   // Do not perform transform!
7561           case Instruction::Add:
7562             isValid = isLeftShift;
7563             break;
7564           case Instruction::Or:
7565           case Instruction::Xor:
7566             highBitSet = false;
7567             break;
7568           case Instruction::And:
7569             highBitSet = true;
7570             break;
7571         }
7572         
7573         // If this is a signed shift right, and the high bit is modified
7574         // by the logical operation, do not perform the transformation.
7575         // The highBitSet boolean indicates the value of the high bit of
7576         // the constant which would cause it to be modified for this
7577         // operation.
7578         //
7579         if (isValid && I.getOpcode() == Instruction::AShr)
7580           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7581         
7582         if (isValid) {
7583           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7584           
7585           Value *NewShift =
7586             Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
7587           NewShift->takeName(Op0BO);
7588           
7589           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7590                                         NewRHS);
7591         }
7592       }
7593     }
7594   }
7595   
7596   // Find out if this is a shift of a shift by a constant.
7597   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7598   if (ShiftOp && !ShiftOp->isShift())
7599     ShiftOp = 0;
7600   
7601   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7602     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7603     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7604     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7605     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7606     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7607     Value *X = ShiftOp->getOperand(0);
7608     
7609     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7610     
7611     const IntegerType *Ty = cast<IntegerType>(I.getType());
7612     
7613     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7614     if (I.getOpcode() == ShiftOp->getOpcode()) {
7615       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7616       // saturates.
7617       if (AmtSum >= TypeBits) {
7618         if (I.getOpcode() != Instruction::AShr)
7619           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7620         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7621       }
7622       
7623       return BinaryOperator::Create(I.getOpcode(), X,
7624                                     ConstantInt::get(Ty, AmtSum));
7625     }
7626     
7627     if (ShiftOp->getOpcode() == Instruction::LShr &&
7628         I.getOpcode() == Instruction::AShr) {
7629       if (AmtSum >= TypeBits)
7630         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7631       
7632       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7633       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7634     }
7635     
7636     if (ShiftOp->getOpcode() == Instruction::AShr &&
7637         I.getOpcode() == Instruction::LShr) {
7638       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7639       if (AmtSum >= TypeBits)
7640         AmtSum = TypeBits-1;
7641       
7642       Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7643
7644       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7645       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7646     }
7647     
7648     // Okay, if we get here, one shift must be left, and the other shift must be
7649     // right.  See if the amounts are equal.
7650     if (ShiftAmt1 == ShiftAmt2) {
7651       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7652       if (I.getOpcode() == Instruction::Shl) {
7653         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7654         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7655       }
7656       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7657       if (I.getOpcode() == Instruction::LShr) {
7658         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7659         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7660       }
7661       // We can simplify ((X << C) >>s C) into a trunc + sext.
7662       // NOTE: we could do this for any C, but that would make 'unusual' integer
7663       // types.  For now, just stick to ones well-supported by the code
7664       // generators.
7665       const Type *SExtType = 0;
7666       switch (Ty->getBitWidth() - ShiftAmt1) {
7667       case 1  :
7668       case 8  :
7669       case 16 :
7670       case 32 :
7671       case 64 :
7672       case 128:
7673         SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
7674         break;
7675       default: break;
7676       }
7677       if (SExtType)
7678         return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
7679       // Otherwise, we can't handle it yet.
7680     } else if (ShiftAmt1 < ShiftAmt2) {
7681       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7682       
7683       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7684       if (I.getOpcode() == Instruction::Shl) {
7685         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7686                ShiftOp->getOpcode() == Instruction::AShr);
7687         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7688         
7689         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7690         return BinaryOperator::CreateAnd(Shift,
7691                                          ConstantInt::get(*Context, Mask));
7692       }
7693       
7694       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7695       if (I.getOpcode() == Instruction::LShr) {
7696         assert(ShiftOp->getOpcode() == Instruction::Shl);
7697         Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7698         
7699         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7700         return BinaryOperator::CreateAnd(Shift,
7701                                          ConstantInt::get(*Context, Mask));
7702       }
7703       
7704       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7705     } else {
7706       assert(ShiftAmt2 < ShiftAmt1);
7707       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7708
7709       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7710       if (I.getOpcode() == Instruction::Shl) {
7711         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7712                ShiftOp->getOpcode() == Instruction::AShr);
7713         Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7714                                             ConstantInt::get(Ty, ShiftDiff));
7715         
7716         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7717         return BinaryOperator::CreateAnd(Shift,
7718                                          ConstantInt::get(*Context, Mask));
7719       }
7720       
7721       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7722       if (I.getOpcode() == Instruction::LShr) {
7723         assert(ShiftOp->getOpcode() == Instruction::Shl);
7724         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7725         
7726         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7727         return BinaryOperator::CreateAnd(Shift,
7728                                          ConstantInt::get(*Context, Mask));
7729       }
7730       
7731       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7732     }
7733   }
7734   return 0;
7735 }
7736
7737
7738 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7739 /// expression.  If so, decompose it, returning some value X, such that Val is
7740 /// X*Scale+Offset.
7741 ///
7742 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7743                                         int &Offset, LLVMContext *Context) {
7744   assert(Val->getType() == Type::getInt32Ty(*Context) && 
7745          "Unexpected allocation size type!");
7746   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7747     Offset = CI->getZExtValue();
7748     Scale  = 0;
7749     return ConstantInt::get(Type::getInt32Ty(*Context), 0);
7750   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7751     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7752       if (I->getOpcode() == Instruction::Shl) {
7753         // This is a value scaled by '1 << the shift amt'.
7754         Scale = 1U << RHS->getZExtValue();
7755         Offset = 0;
7756         return I->getOperand(0);
7757       } else if (I->getOpcode() == Instruction::Mul) {
7758         // This value is scaled by 'RHS'.
7759         Scale = RHS->getZExtValue();
7760         Offset = 0;
7761         return I->getOperand(0);
7762       } else if (I->getOpcode() == Instruction::Add) {
7763         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7764         // where C1 is divisible by C2.
7765         unsigned SubScale;
7766         Value *SubVal = 
7767           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7768                                     Offset, Context);
7769         Offset += RHS->getZExtValue();
7770         Scale = SubScale;
7771         return SubVal;
7772       }
7773     }
7774   }
7775
7776   // Otherwise, we can't look past this.
7777   Scale = 1;
7778   Offset = 0;
7779   return Val;
7780 }
7781
7782
7783 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7784 /// try to eliminate the cast by moving the type information into the alloc.
7785 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7786                                                    AllocaInst &AI) {
7787   const PointerType *PTy = cast<PointerType>(CI.getType());
7788   
7789   BuilderTy AllocaBuilder(*Builder);
7790   AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7791   
7792   // Remove any uses of AI that are dead.
7793   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7794   
7795   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7796     Instruction *User = cast<Instruction>(*UI++);
7797     if (isInstructionTriviallyDead(User)) {
7798       while (UI != E && *UI == User)
7799         ++UI; // If this instruction uses AI more than once, don't break UI.
7800       
7801       ++NumDeadInst;
7802       DEBUG(errs() << "IC: DCE: " << *User << '\n');
7803       EraseInstFromFunction(*User);
7804     }
7805   }
7806
7807   // This requires TargetData to get the alloca alignment and size information.
7808   if (!TD) return 0;
7809
7810   // Get the type really allocated and the type casted to.
7811   const Type *AllocElTy = AI.getAllocatedType();
7812   const Type *CastElTy = PTy->getElementType();
7813   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7814
7815   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7816   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7817   if (CastElTyAlign < AllocElTyAlign) return 0;
7818
7819   // If the allocation has multiple uses, only promote it if we are strictly
7820   // increasing the alignment of the resultant allocation.  If we keep it the
7821   // same, we open the door to infinite loops of various kinds.  (A reference
7822   // from a dbg.declare doesn't count as a use for this purpose.)
7823   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7824       CastElTyAlign == AllocElTyAlign) return 0;
7825
7826   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7827   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7828   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7829
7830   // See if we can satisfy the modulus by pulling a scale out of the array
7831   // size argument.
7832   unsigned ArraySizeScale;
7833   int ArrayOffset;
7834   Value *NumElements = // See if the array size is a decomposable linear expr.
7835     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7836                               ArrayOffset, Context);
7837  
7838   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7839   // do the xform.
7840   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7841       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7842
7843   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7844   Value *Amt = 0;
7845   if (Scale == 1) {
7846     Amt = NumElements;
7847   } else {
7848     Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
7849     // Insert before the alloca, not before the cast.
7850     Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
7851   }
7852   
7853   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7854     Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
7855     Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
7856   }
7857   
7858   AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7859   New->setAlignment(AI.getAlignment());
7860   New->takeName(&AI);
7861   
7862   // If the allocation has one real use plus a dbg.declare, just remove the
7863   // declare.
7864   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7865     EraseInstFromFunction(*DI);
7866   }
7867   // If the allocation has multiple real uses, insert a cast and change all
7868   // things that used it to use the new cast.  This will also hack on CI, but it
7869   // will die soon.
7870   else if (!AI.hasOneUse()) {
7871     // New is the allocation instruction, pointer typed. AI is the original
7872     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7873     Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
7874     AI.replaceAllUsesWith(NewCast);
7875   }
7876   return ReplaceInstUsesWith(CI, New);
7877 }
7878
7879 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7880 /// and return it as type Ty without inserting any new casts and without
7881 /// changing the computed value.  This is used by code that tries to decide
7882 /// whether promoting or shrinking integer operations to wider or smaller types
7883 /// will allow us to eliminate a truncate or extend.
7884 ///
7885 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7886 /// extension operation if Ty is larger.
7887 ///
7888 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7889 /// should return true if trunc(V) can be computed by computing V in the smaller
7890 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7891 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7892 /// efficiently truncated.
7893 ///
7894 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7895 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7896 /// the final result.
7897 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7898                                               unsigned CastOpc,
7899                                               int &NumCastsRemoved){
7900   // We can always evaluate constants in another type.
7901   if (isa<Constant>(V))
7902     return true;
7903   
7904   Instruction *I = dyn_cast<Instruction>(V);
7905   if (!I) return false;
7906   
7907   const Type *OrigTy = V->getType();
7908   
7909   // If this is an extension or truncate, we can often eliminate it.
7910   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7911     // If this is a cast from the destination type, we can trivially eliminate
7912     // it, and this will remove a cast overall.
7913     if (I->getOperand(0)->getType() == Ty) {
7914       // If the first operand is itself a cast, and is eliminable, do not count
7915       // this as an eliminable cast.  We would prefer to eliminate those two
7916       // casts first.
7917       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7918         ++NumCastsRemoved;
7919       return true;
7920     }
7921   }
7922
7923   // We can't extend or shrink something that has multiple uses: doing so would
7924   // require duplicating the instruction in general, which isn't profitable.
7925   if (!I->hasOneUse()) return false;
7926
7927   unsigned Opc = I->getOpcode();
7928   switch (Opc) {
7929   case Instruction::Add:
7930   case Instruction::Sub:
7931   case Instruction::Mul:
7932   case Instruction::And:
7933   case Instruction::Or:
7934   case Instruction::Xor:
7935     // These operators can all arbitrarily be extended or truncated.
7936     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7937                                       NumCastsRemoved) &&
7938            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7939                                       NumCastsRemoved);
7940
7941   case Instruction::UDiv:
7942   case Instruction::URem: {
7943     // UDiv and URem can be truncated if all the truncated bits are zero.
7944     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7945     uint32_t BitWidth = Ty->getScalarSizeInBits();
7946     if (BitWidth < OrigBitWidth) {
7947       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7948       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7949           MaskedValueIsZero(I->getOperand(1), Mask)) {
7950         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7951                                           NumCastsRemoved) &&
7952                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7953                                           NumCastsRemoved);
7954       }
7955     }
7956     break;
7957   }
7958   case Instruction::Shl:
7959     // If we are truncating the result of this SHL, and if it's a shift of a
7960     // constant amount, we can always perform a SHL in a smaller type.
7961     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7962       uint32_t BitWidth = Ty->getScalarSizeInBits();
7963       if (BitWidth < OrigTy->getScalarSizeInBits() &&
7964           CI->getLimitedValue(BitWidth) < BitWidth)
7965         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7966                                           NumCastsRemoved);
7967     }
7968     break;
7969   case Instruction::LShr:
7970     // If this is a truncate of a logical shr, we can truncate it to a smaller
7971     // lshr iff we know that the bits we would otherwise be shifting in are
7972     // already zeros.
7973     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7974       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7975       uint32_t BitWidth = Ty->getScalarSizeInBits();
7976       if (BitWidth < OrigBitWidth &&
7977           MaskedValueIsZero(I->getOperand(0),
7978             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7979           CI->getLimitedValue(BitWidth) < BitWidth) {
7980         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7981                                           NumCastsRemoved);
7982       }
7983     }
7984     break;
7985   case Instruction::ZExt:
7986   case Instruction::SExt:
7987   case Instruction::Trunc:
7988     // If this is the same kind of case as our original (e.g. zext+zext), we
7989     // can safely replace it.  Note that replacing it does not reduce the number
7990     // of casts in the input.
7991     if (Opc == CastOpc)
7992       return true;
7993
7994     // sext (zext ty1), ty2 -> zext ty2
7995     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7996       return true;
7997     break;
7998   case Instruction::Select: {
7999     SelectInst *SI = cast<SelectInst>(I);
8000     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8001                                       NumCastsRemoved) &&
8002            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8003                                       NumCastsRemoved);
8004   }
8005   case Instruction::PHI: {
8006     // We can change a phi if we can change all operands.
8007     PHINode *PN = cast<PHINode>(I);
8008     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8009       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8010                                       NumCastsRemoved))
8011         return false;
8012     return true;
8013   }
8014   default:
8015     // TODO: Can handle more cases here.
8016     break;
8017   }
8018   
8019   return false;
8020 }
8021
8022 /// EvaluateInDifferentType - Given an expression that 
8023 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8024 /// evaluate the expression.
8025 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
8026                                              bool isSigned) {
8027   if (Constant *C = dyn_cast<Constant>(V))
8028     return ConstantExpr::getIntegerCast(C, Ty,
8029                                                isSigned /*Sext or ZExt*/);
8030
8031   // Otherwise, it must be an instruction.
8032   Instruction *I = cast<Instruction>(V);
8033   Instruction *Res = 0;
8034   unsigned Opc = I->getOpcode();
8035   switch (Opc) {
8036   case Instruction::Add:
8037   case Instruction::Sub:
8038   case Instruction::Mul:
8039   case Instruction::And:
8040   case Instruction::Or:
8041   case Instruction::Xor:
8042   case Instruction::AShr:
8043   case Instruction::LShr:
8044   case Instruction::Shl:
8045   case Instruction::UDiv:
8046   case Instruction::URem: {
8047     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8048     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8049     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8050     break;
8051   }    
8052   case Instruction::Trunc:
8053   case Instruction::ZExt:
8054   case Instruction::SExt:
8055     // If the source type of the cast is the type we're trying for then we can
8056     // just return the source.  There's no need to insert it because it is not
8057     // new.
8058     if (I->getOperand(0)->getType() == Ty)
8059       return I->getOperand(0);
8060     
8061     // Otherwise, must be the same type of cast, so just reinsert a new one.
8062     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8063                            Ty);
8064     break;
8065   case Instruction::Select: {
8066     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8067     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8068     Res = SelectInst::Create(I->getOperand(0), True, False);
8069     break;
8070   }
8071   case Instruction::PHI: {
8072     PHINode *OPN = cast<PHINode>(I);
8073     PHINode *NPN = PHINode::Create(Ty);
8074     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8075       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8076       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8077     }
8078     Res = NPN;
8079     break;
8080   }
8081   default: 
8082     // TODO: Can handle more cases here.
8083     llvm_unreachable("Unreachable!");
8084     break;
8085   }
8086   
8087   Res->takeName(I);
8088   return InsertNewInstBefore(Res, *I);
8089 }
8090
8091 /// @brief Implement the transforms common to all CastInst visitors.
8092 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8093   Value *Src = CI.getOperand(0);
8094
8095   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8096   // eliminate it now.
8097   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8098     if (Instruction::CastOps opc = 
8099         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8100       // The first cast (CSrc) is eliminable so we need to fix up or replace
8101       // the second cast (CI). CSrc will then have a good chance of being dead.
8102       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8103     }
8104   }
8105
8106   // If we are casting a select then fold the cast into the select
8107   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8108     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8109       return NV;
8110
8111   // If we are casting a PHI then fold the cast into the PHI
8112   if (isa<PHINode>(Src))
8113     if (Instruction *NV = FoldOpIntoPhi(CI))
8114       return NV;
8115   
8116   return 0;
8117 }
8118
8119 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8120 /// or not there is a sequence of GEP indices into the type that will land us at
8121 /// the specified offset.  If so, fill them into NewIndices and return the
8122 /// resultant element type, otherwise return null.
8123 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8124                                        SmallVectorImpl<Value*> &NewIndices,
8125                                        const TargetData *TD,
8126                                        LLVMContext *Context) {
8127   if (!TD) return 0;
8128   if (!Ty->isSized()) return 0;
8129   
8130   // Start with the index over the outer type.  Note that the type size
8131   // might be zero (even if the offset isn't zero) if the indexed type
8132   // is something like [0 x {int, int}]
8133   const Type *IntPtrTy = TD->getIntPtrType(*Context);
8134   int64_t FirstIdx = 0;
8135   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8136     FirstIdx = Offset/TySize;
8137     Offset -= FirstIdx*TySize;
8138     
8139     // Handle hosts where % returns negative instead of values [0..TySize).
8140     if (Offset < 0) {
8141       --FirstIdx;
8142       Offset += TySize;
8143       assert(Offset >= 0);
8144     }
8145     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8146   }
8147   
8148   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8149     
8150   // Index into the types.  If we fail, set OrigBase to null.
8151   while (Offset) {
8152     // Indexing into tail padding between struct/array elements.
8153     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8154       return 0;
8155     
8156     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8157       const StructLayout *SL = TD->getStructLayout(STy);
8158       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8159              "Offset must stay within the indexed type");
8160       
8161       unsigned Elt = SL->getElementContainingOffset(Offset);
8162       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8163       
8164       Offset -= SL->getElementOffset(Elt);
8165       Ty = STy->getElementType(Elt);
8166     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8167       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8168       assert(EltSize && "Cannot index into a zero-sized array");
8169       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8170       Offset %= EltSize;
8171       Ty = AT->getElementType();
8172     } else {
8173       // Otherwise, we can't index into the middle of this atomic type, bail.
8174       return 0;
8175     }
8176   }
8177   
8178   return Ty;
8179 }
8180
8181 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8182 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8183   Value *Src = CI.getOperand(0);
8184   
8185   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8186     // If casting the result of a getelementptr instruction with no offset, turn
8187     // this into a cast of the original pointer!
8188     if (GEP->hasAllZeroIndices()) {
8189       // Changing the cast operand is usually not a good idea but it is safe
8190       // here because the pointer operand is being replaced with another 
8191       // pointer operand so the opcode doesn't need to change.
8192       Worklist.Add(GEP);
8193       CI.setOperand(0, GEP->getOperand(0));
8194       return &CI;
8195     }
8196     
8197     // If the GEP has a single use, and the base pointer is a bitcast, and the
8198     // GEP computes a constant offset, see if we can convert these three
8199     // instructions into fewer.  This typically happens with unions and other
8200     // non-type-safe code.
8201     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8202       if (GEP->hasAllConstantIndices()) {
8203         // We are guaranteed to get a constant from EmitGEPOffset.
8204         ConstantInt *OffsetV =
8205                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8206         int64_t Offset = OffsetV->getSExtValue();
8207         
8208         // Get the base pointer input of the bitcast, and the type it points to.
8209         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8210         const Type *GEPIdxTy =
8211           cast<PointerType>(OrigBase->getType())->getElementType();
8212         SmallVector<Value*, 8> NewIndices;
8213         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8214           // If we were able to index down into an element, create the GEP
8215           // and bitcast the result.  This eliminates one bitcast, potentially
8216           // two.
8217           Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8218             Builder->CreateInBoundsGEP(OrigBase,
8219                                        NewIndices.begin(), NewIndices.end()) :
8220             Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
8221           NGEP->takeName(GEP);
8222           
8223           if (isa<BitCastInst>(CI))
8224             return new BitCastInst(NGEP, CI.getType());
8225           assert(isa<PtrToIntInst>(CI));
8226           return new PtrToIntInst(NGEP, CI.getType());
8227         }
8228       }      
8229     }
8230   }
8231     
8232   return commonCastTransforms(CI);
8233 }
8234
8235 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8236 /// type like i42.  We don't want to introduce operations on random non-legal
8237 /// integer types where they don't already exist in the code.  In the future,
8238 /// we should consider making this based off target-data, so that 32-bit targets
8239 /// won't get i64 operations etc.
8240 static bool isSafeIntegerType(const Type *Ty) {
8241   switch (Ty->getPrimitiveSizeInBits()) {
8242   case 8:
8243   case 16:
8244   case 32:
8245   case 64:
8246     return true;
8247   default: 
8248     return false;
8249   }
8250 }
8251
8252 /// commonIntCastTransforms - This function implements the common transforms
8253 /// for trunc, zext, and sext.
8254 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8255   if (Instruction *Result = commonCastTransforms(CI))
8256     return Result;
8257
8258   Value *Src = CI.getOperand(0);
8259   const Type *SrcTy = Src->getType();
8260   const Type *DestTy = CI.getType();
8261   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8262   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8263
8264   // See if we can simplify any instructions used by the LHS whose sole 
8265   // purpose is to compute bits we don't care about.
8266   if (SimplifyDemandedInstructionBits(CI))
8267     return &CI;
8268
8269   // If the source isn't an instruction or has more than one use then we
8270   // can't do anything more. 
8271   Instruction *SrcI = dyn_cast<Instruction>(Src);
8272   if (!SrcI || !Src->hasOneUse())
8273     return 0;
8274
8275   // Attempt to propagate the cast into the instruction for int->int casts.
8276   int NumCastsRemoved = 0;
8277   // Only do this if the dest type is a simple type, don't convert the
8278   // expression tree to something weird like i93 unless the source is also
8279   // strange.
8280   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8281        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8282       CanEvaluateInDifferentType(SrcI, DestTy,
8283                                  CI.getOpcode(), NumCastsRemoved)) {
8284     // If this cast is a truncate, evaluting in a different type always
8285     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8286     // we need to do an AND to maintain the clear top-part of the computation,
8287     // so we require that the input have eliminated at least one cast.  If this
8288     // is a sign extension, we insert two new casts (to do the extension) so we
8289     // require that two casts have been eliminated.
8290     bool DoXForm = false;
8291     bool JustReplace = false;
8292     switch (CI.getOpcode()) {
8293     default:
8294       // All the others use floating point so we shouldn't actually 
8295       // get here because of the check above.
8296       llvm_unreachable("Unknown cast type");
8297     case Instruction::Trunc:
8298       DoXForm = true;
8299       break;
8300     case Instruction::ZExt: {
8301       DoXForm = NumCastsRemoved >= 1;
8302       if (!DoXForm && 0) {
8303         // If it's unnecessary to issue an AND to clear the high bits, it's
8304         // always profitable to do this xform.
8305         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8306         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8307         if (MaskedValueIsZero(TryRes, Mask))
8308           return ReplaceInstUsesWith(CI, TryRes);
8309         
8310         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8311           if (TryI->use_empty())
8312             EraseInstFromFunction(*TryI);
8313       }
8314       break;
8315     }
8316     case Instruction::SExt: {
8317       DoXForm = NumCastsRemoved >= 2;
8318       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8319         // If we do not have to emit the truncate + sext pair, then it's always
8320         // profitable to do this xform.
8321         //
8322         // It's not safe to eliminate the trunc + sext pair if one of the
8323         // eliminated cast is a truncate. e.g.
8324         // t2 = trunc i32 t1 to i16
8325         // t3 = sext i16 t2 to i32
8326         // !=
8327         // i32 t1
8328         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8329         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8330         if (NumSignBits > (DestBitSize - SrcBitSize))
8331           return ReplaceInstUsesWith(CI, TryRes);
8332         
8333         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8334           if (TryI->use_empty())
8335             EraseInstFromFunction(*TryI);
8336       }
8337       break;
8338     }
8339     }
8340     
8341     if (DoXForm) {
8342       DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8343             " to avoid cast: " << CI);
8344       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8345                                            CI.getOpcode() == Instruction::SExt);
8346       if (JustReplace)
8347         // Just replace this cast with the result.
8348         return ReplaceInstUsesWith(CI, Res);
8349
8350       assert(Res->getType() == DestTy);
8351       switch (CI.getOpcode()) {
8352       default: llvm_unreachable("Unknown cast type!");
8353       case Instruction::Trunc:
8354         // Just replace this cast with the result.
8355         return ReplaceInstUsesWith(CI, Res);
8356       case Instruction::ZExt: {
8357         assert(SrcBitSize < DestBitSize && "Not a zext?");
8358
8359         // If the high bits are already zero, just replace this cast with the
8360         // result.
8361         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8362         if (MaskedValueIsZero(Res, Mask))
8363           return ReplaceInstUsesWith(CI, Res);
8364
8365         // We need to emit an AND to clear the high bits.
8366         Constant *C = ConstantInt::get(*Context, 
8367                                  APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8368         return BinaryOperator::CreateAnd(Res, C);
8369       }
8370       case Instruction::SExt: {
8371         // If the high bits are already filled with sign bit, just replace this
8372         // cast with the result.
8373         unsigned NumSignBits = ComputeNumSignBits(Res);
8374         if (NumSignBits > (DestBitSize - SrcBitSize))
8375           return ReplaceInstUsesWith(CI, Res);
8376
8377         // We need to emit a cast to truncate, then a cast to sext.
8378         return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
8379       }
8380       }
8381     }
8382   }
8383   
8384   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8385   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8386
8387   switch (SrcI->getOpcode()) {
8388   case Instruction::Add:
8389   case Instruction::Mul:
8390   case Instruction::And:
8391   case Instruction::Or:
8392   case Instruction::Xor:
8393     // If we are discarding information, rewrite.
8394     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8395       // Don't insert two casts unless at least one can be eliminated.
8396       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8397           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8398         Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8399         Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8400         return BinaryOperator::Create(
8401             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8402       }
8403     }
8404
8405     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8406     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8407         SrcI->getOpcode() == Instruction::Xor &&
8408         Op1 == ConstantInt::getTrue(*Context) &&
8409         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8410       Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
8411       return BinaryOperator::CreateXor(New,
8412                                       ConstantInt::get(CI.getType(), 1));
8413     }
8414     break;
8415
8416   case Instruction::Shl: {
8417     // Canonicalize trunc inside shl, if we can.
8418     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8419     if (CI && DestBitSize < SrcBitSize &&
8420         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8421       Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8422       Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8423       return BinaryOperator::CreateShl(Op0c, Op1c);
8424     }
8425     break;
8426   }
8427   }
8428   return 0;
8429 }
8430
8431 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8432   if (Instruction *Result = commonIntCastTransforms(CI))
8433     return Result;
8434   
8435   Value *Src = CI.getOperand(0);
8436   const Type *Ty = CI.getType();
8437   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8438   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8439
8440   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8441   if (DestBitWidth == 1) {
8442     Constant *One = ConstantInt::get(Src->getType(), 1);
8443     Src = Builder->CreateAnd(Src, One, "tmp");
8444     Value *Zero = Constant::getNullValue(Src->getType());
8445     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8446   }
8447
8448   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8449   ConstantInt *ShAmtV = 0;
8450   Value *ShiftOp = 0;
8451   if (Src->hasOneUse() &&
8452       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8453     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8454     
8455     // Get a mask for the bits shifting in.
8456     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8457     if (MaskedValueIsZero(ShiftOp, Mask)) {
8458       if (ShAmt >= DestBitWidth)        // All zeros.
8459         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8460       
8461       // Okay, we can shrink this.  Truncate the input, then return a new
8462       // shift.
8463       Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
8464       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8465       return BinaryOperator::CreateLShr(V1, V2);
8466     }
8467   }
8468   
8469   return 0;
8470 }
8471
8472 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8473 /// in order to eliminate the icmp.
8474 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8475                                              bool DoXform) {
8476   // If we are just checking for a icmp eq of a single bit and zext'ing it
8477   // to an integer, then shift the bit to the appropriate place and then
8478   // cast to integer to avoid the comparison.
8479   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8480     const APInt &Op1CV = Op1C->getValue();
8481       
8482     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8483     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8484     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8485         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8486       if (!DoXform) return ICI;
8487
8488       Value *In = ICI->getOperand(0);
8489       Value *Sh = ConstantInt::get(In->getType(),
8490                                    In->getType()->getScalarSizeInBits()-1);
8491       In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
8492       if (In->getType() != CI.getType())
8493         In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
8494
8495       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8496         Constant *One = ConstantInt::get(In->getType(), 1);
8497         In = Builder->CreateXor(In, One, In->getName()+".not");
8498       }
8499
8500       return ReplaceInstUsesWith(CI, In);
8501     }
8502       
8503       
8504       
8505     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8506     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8507     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8508     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8509     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8510     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8511     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8512     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8513     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8514         // This only works for EQ and NE
8515         ICI->isEquality()) {
8516       // If Op1C some other power of two, convert:
8517       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8518       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8519       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8520       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8521         
8522       APInt KnownZeroMask(~KnownZero);
8523       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8524         if (!DoXform) return ICI;
8525
8526         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8527         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8528           // (X&4) == 2 --> false
8529           // (X&4) != 2 --> true
8530           Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8531           Res = ConstantExpr::getZExt(Res, CI.getType());
8532           return ReplaceInstUsesWith(CI, Res);
8533         }
8534           
8535         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8536         Value *In = ICI->getOperand(0);
8537         if (ShiftAmt) {
8538           // Perform a logical shr by shiftamt.
8539           // Insert the shift to put the result in the low bit.
8540           In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8541                                    In->getName()+".lobit");
8542         }
8543           
8544         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8545           Constant *One = ConstantInt::get(In->getType(), 1);
8546           In = Builder->CreateXor(In, One, "tmp");
8547         }
8548           
8549         if (CI.getType() == In->getType())
8550           return ReplaceInstUsesWith(CI, In);
8551         else
8552           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8553       }
8554     }
8555   }
8556
8557   return 0;
8558 }
8559
8560 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8561   // If one of the common conversion will work ..
8562   if (Instruction *Result = commonIntCastTransforms(CI))
8563     return Result;
8564
8565   Value *Src = CI.getOperand(0);
8566
8567   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8568   // types and if the sizes are just right we can convert this into a logical
8569   // 'and' which will be much cheaper than the pair of casts.
8570   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8571     // Get the sizes of the types involved.  We know that the intermediate type
8572     // will be smaller than A or C, but don't know the relation between A and C.
8573     Value *A = CSrc->getOperand(0);
8574     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8575     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8576     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8577     // If we're actually extending zero bits, then if
8578     // SrcSize <  DstSize: zext(a & mask)
8579     // SrcSize == DstSize: a & mask
8580     // SrcSize  > DstSize: trunc(a) & mask
8581     if (SrcSize < DstSize) {
8582       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8583       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8584       Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
8585       return new ZExtInst(And, CI.getType());
8586     }
8587     
8588     if (SrcSize == DstSize) {
8589       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8590       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8591                                                            AndValue));
8592     }
8593     if (SrcSize > DstSize) {
8594       Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
8595       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8596       return BinaryOperator::CreateAnd(Trunc, 
8597                                        ConstantInt::get(Trunc->getType(),
8598                                                                AndValue));
8599     }
8600   }
8601
8602   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8603     return transformZExtICmp(ICI, CI);
8604
8605   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8606   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8607     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8608     // of the (zext icmp) will be transformed.
8609     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8610     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8611     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8612         (transformZExtICmp(LHS, CI, false) ||
8613          transformZExtICmp(RHS, CI, false))) {
8614       Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8615       Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
8616       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8617     }
8618   }
8619
8620   // zext(trunc(t) & C) -> (t & zext(C)).
8621   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8622     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8623       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8624         Value *TI0 = TI->getOperand(0);
8625         if (TI0->getType() == CI.getType())
8626           return
8627             BinaryOperator::CreateAnd(TI0,
8628                                 ConstantExpr::getZExt(C, CI.getType()));
8629       }
8630
8631   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8632   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8633     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8634       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8635         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8636             And->getOperand(1) == C)
8637           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8638             Value *TI0 = TI->getOperand(0);
8639             if (TI0->getType() == CI.getType()) {
8640               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8641               Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
8642               return BinaryOperator::CreateXor(NewAnd, ZC);
8643             }
8644           }
8645
8646   return 0;
8647 }
8648
8649 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8650   if (Instruction *I = commonIntCastTransforms(CI))
8651     return I;
8652   
8653   Value *Src = CI.getOperand(0);
8654   
8655   // Canonicalize sign-extend from i1 to a select.
8656   if (Src->getType() == Type::getInt1Ty(*Context))
8657     return SelectInst::Create(Src,
8658                               Constant::getAllOnesValue(CI.getType()),
8659                               Constant::getNullValue(CI.getType()));
8660
8661   // See if the value being truncated is already sign extended.  If so, just
8662   // eliminate the trunc/sext pair.
8663   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8664     Value *Op = cast<User>(Src)->getOperand(0);
8665     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8666     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8667     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8668     unsigned NumSignBits = ComputeNumSignBits(Op);
8669
8670     if (OpBits == DestBits) {
8671       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8672       // bits, it is already ready.
8673       if (NumSignBits > DestBits-MidBits)
8674         return ReplaceInstUsesWith(CI, Op);
8675     } else if (OpBits < DestBits) {
8676       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8677       // bits, just sext from i32.
8678       if (NumSignBits > OpBits-MidBits)
8679         return new SExtInst(Op, CI.getType(), "tmp");
8680     } else {
8681       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8682       // bits, just truncate to i32.
8683       if (NumSignBits > OpBits-MidBits)
8684         return new TruncInst(Op, CI.getType(), "tmp");
8685     }
8686   }
8687
8688   // If the input is a shl/ashr pair of a same constant, then this is a sign
8689   // extension from a smaller value.  If we could trust arbitrary bitwidth
8690   // integers, we could turn this into a truncate to the smaller bit and then
8691   // use a sext for the whole extension.  Since we don't, look deeper and check
8692   // for a truncate.  If the source and dest are the same type, eliminate the
8693   // trunc and extend and just do shifts.  For example, turn:
8694   //   %a = trunc i32 %i to i8
8695   //   %b = shl i8 %a, 6
8696   //   %c = ashr i8 %b, 6
8697   //   %d = sext i8 %c to i32
8698   // into:
8699   //   %a = shl i32 %i, 30
8700   //   %d = ashr i32 %a, 30
8701   Value *A = 0;
8702   ConstantInt *BA = 0, *CA = 0;
8703   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8704                         m_ConstantInt(CA))) &&
8705       BA == CA && isa<TruncInst>(A)) {
8706     Value *I = cast<TruncInst>(A)->getOperand(0);
8707     if (I->getType() == CI.getType()) {
8708       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8709       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8710       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8711       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8712       I = Builder->CreateShl(I, ShAmtV, CI.getName());
8713       return BinaryOperator::CreateAShr(I, ShAmtV);
8714     }
8715   }
8716   
8717   return 0;
8718 }
8719
8720 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8721 /// in the specified FP type without changing its value.
8722 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8723                               LLVMContext *Context) {
8724   bool losesInfo;
8725   APFloat F = CFP->getValueAPF();
8726   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8727   if (!losesInfo)
8728     return ConstantFP::get(*Context, F);
8729   return 0;
8730 }
8731
8732 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8733 /// through it until we get the source value.
8734 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8735   if (Instruction *I = dyn_cast<Instruction>(V))
8736     if (I->getOpcode() == Instruction::FPExt)
8737       return LookThroughFPExtensions(I->getOperand(0), Context);
8738   
8739   // If this value is a constant, return the constant in the smallest FP type
8740   // that can accurately represent it.  This allows us to turn
8741   // (float)((double)X+2.0) into x+2.0f.
8742   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8743     if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
8744       return V;  // No constant folding of this.
8745     // See if the value can be truncated to float and then reextended.
8746     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8747       return V;
8748     if (CFP->getType() == Type::getDoubleTy(*Context))
8749       return V;  // Won't shrink.
8750     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8751       return V;
8752     // Don't try to shrink to various long double types.
8753   }
8754   
8755   return V;
8756 }
8757
8758 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8759   if (Instruction *I = commonCastTransforms(CI))
8760     return I;
8761   
8762   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8763   // smaller than the destination type, we can eliminate the truncate by doing
8764   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8765   // many builtins (sqrt, etc).
8766   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8767   if (OpI && OpI->hasOneUse()) {
8768     switch (OpI->getOpcode()) {
8769     default: break;
8770     case Instruction::FAdd:
8771     case Instruction::FSub:
8772     case Instruction::FMul:
8773     case Instruction::FDiv:
8774     case Instruction::FRem:
8775       const Type *SrcTy = OpI->getType();
8776       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8777       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8778       if (LHSTrunc->getType() != SrcTy && 
8779           RHSTrunc->getType() != SrcTy) {
8780         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8781         // If the source types were both smaller than the destination type of
8782         // the cast, do this xform.
8783         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8784             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8785           LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8786           RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
8787           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8788         }
8789       }
8790       break;  
8791     }
8792   }
8793   return 0;
8794 }
8795
8796 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8797   return commonCastTransforms(CI);
8798 }
8799
8800 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8801   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8802   if (OpI == 0)
8803     return commonCastTransforms(FI);
8804
8805   // fptoui(uitofp(X)) --> X
8806   // fptoui(sitofp(X)) --> X
8807   // This is safe if the intermediate type has enough bits in its mantissa to
8808   // accurately represent all values of X.  For example, do not do this with
8809   // i64->float->i64.  This is also safe for sitofp case, because any negative
8810   // 'X' value would cause an undefined result for the fptoui. 
8811   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8812       OpI->getOperand(0)->getType() == FI.getType() &&
8813       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8814                     OpI->getType()->getFPMantissaWidth())
8815     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8816
8817   return commonCastTransforms(FI);
8818 }
8819
8820 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8821   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8822   if (OpI == 0)
8823     return commonCastTransforms(FI);
8824   
8825   // fptosi(sitofp(X)) --> X
8826   // fptosi(uitofp(X)) --> X
8827   // This is safe if the intermediate type has enough bits in its mantissa to
8828   // accurately represent all values of X.  For example, do not do this with
8829   // i64->float->i64.  This is also safe for sitofp case, because any negative
8830   // 'X' value would cause an undefined result for the fptoui. 
8831   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8832       OpI->getOperand(0)->getType() == FI.getType() &&
8833       (int)FI.getType()->getScalarSizeInBits() <=
8834                     OpI->getType()->getFPMantissaWidth())
8835     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8836   
8837   return commonCastTransforms(FI);
8838 }
8839
8840 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8841   return commonCastTransforms(CI);
8842 }
8843
8844 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8845   return commonCastTransforms(CI);
8846 }
8847
8848 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8849   // If the destination integer type is smaller than the intptr_t type for
8850   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8851   // trunc to be exposed to other transforms.  Don't do this for extending
8852   // ptrtoint's, because we don't know if the target sign or zero extends its
8853   // pointers.
8854   if (TD &&
8855       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8856     Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8857                                        TD->getIntPtrType(CI.getContext()),
8858                                        "tmp");
8859     return new TruncInst(P, CI.getType());
8860   }
8861   
8862   return commonPointerCastTransforms(CI);
8863 }
8864
8865 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8866   // If the source integer type is larger than the intptr_t type for
8867   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8868   // allows the trunc to be exposed to other transforms.  Don't do this for
8869   // extending inttoptr's, because we don't know if the target sign or zero
8870   // extends to pointers.
8871   if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
8872       TD->getPointerSizeInBits()) {
8873     Value *P = Builder->CreateTrunc(CI.getOperand(0),
8874                                     TD->getIntPtrType(CI.getContext()), "tmp");
8875     return new IntToPtrInst(P, CI.getType());
8876   }
8877   
8878   if (Instruction *I = commonCastTransforms(CI))
8879     return I;
8880
8881   return 0;
8882 }
8883
8884 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8885   // If the operands are integer typed then apply the integer transforms,
8886   // otherwise just apply the common ones.
8887   Value *Src = CI.getOperand(0);
8888   const Type *SrcTy = Src->getType();
8889   const Type *DestTy = CI.getType();
8890
8891   if (isa<PointerType>(SrcTy)) {
8892     if (Instruction *I = commonPointerCastTransforms(CI))
8893       return I;
8894   } else {
8895     if (Instruction *Result = commonCastTransforms(CI))
8896       return Result;
8897   }
8898
8899
8900   // Get rid of casts from one type to the same type. These are useless and can
8901   // be replaced by the operand.
8902   if (DestTy == Src->getType())
8903     return ReplaceInstUsesWith(CI, Src);
8904
8905   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8906     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8907     const Type *DstElTy = DstPTy->getElementType();
8908     const Type *SrcElTy = SrcPTy->getElementType();
8909     
8910     // If the address spaces don't match, don't eliminate the bitcast, which is
8911     // required for changing types.
8912     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8913       return 0;
8914     
8915     // If we are casting a alloca to a pointer to a type of the same
8916     // size, rewrite the allocation instruction to allocate the "right" type.
8917     // There is no need to modify malloc calls because it is their bitcast that
8918     // needs to be cleaned up.
8919     if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
8920       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8921         return V;
8922     
8923     // If the source and destination are pointers, and this cast is equivalent
8924     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8925     // This can enhance SROA and other transforms that want type-safe pointers.
8926     Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
8927     unsigned NumZeros = 0;
8928     while (SrcElTy != DstElTy && 
8929            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8930            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8931       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8932       ++NumZeros;
8933     }
8934
8935     // If we found a path from the src to dest, create the getelementptr now.
8936     if (SrcElTy == DstElTy) {
8937       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8938       return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8939                                                ((Instruction*) NULL));
8940     }
8941   }
8942
8943   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8944     if (DestVTy->getNumElements() == 1) {
8945       if (!isa<VectorType>(SrcTy)) {
8946         Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
8947         return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
8948                             Constant::getNullValue(Type::getInt32Ty(*Context)));
8949       }
8950       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8951     }
8952   }
8953
8954   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8955     if (SrcVTy->getNumElements() == 1) {
8956       if (!isa<VectorType>(DestTy)) {
8957         Value *Elem = 
8958           Builder->CreateExtractElement(Src,
8959                             Constant::getNullValue(Type::getInt32Ty(*Context)));
8960         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8961       }
8962     }
8963   }
8964
8965   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8966     if (SVI->hasOneUse()) {
8967       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8968       // a bitconvert to a vector with the same # elts.
8969       if (isa<VectorType>(DestTy) && 
8970           cast<VectorType>(DestTy)->getNumElements() ==
8971                 SVI->getType()->getNumElements() &&
8972           SVI->getType()->getNumElements() ==
8973             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8974         CastInst *Tmp;
8975         // If either of the operands is a cast from CI.getType(), then
8976         // evaluating the shuffle in the casted destination's type will allow
8977         // us to eliminate at least one cast.
8978         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8979              Tmp->getOperand(0)->getType() == DestTy) ||
8980             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8981              Tmp->getOperand(0)->getType() == DestTy)) {
8982           Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8983           Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
8984           // Return a new shuffle vector.  Use the same element ID's, as we
8985           // know the vector types match #elts.
8986           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8987         }
8988       }
8989     }
8990   }
8991   return 0;
8992 }
8993
8994 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8995 ///   %C = or %A, %B
8996 ///   %D = select %cond, %C, %A
8997 /// into:
8998 ///   %C = select %cond, %B, 0
8999 ///   %D = or %A, %C
9000 ///
9001 /// Assuming that the specified instruction is an operand to the select, return
9002 /// a bitmask indicating which operands of this instruction are foldable if they
9003 /// equal the other incoming value of the select.
9004 ///
9005 static unsigned GetSelectFoldableOperands(Instruction *I) {
9006   switch (I->getOpcode()) {
9007   case Instruction::Add:
9008   case Instruction::Mul:
9009   case Instruction::And:
9010   case Instruction::Or:
9011   case Instruction::Xor:
9012     return 3;              // Can fold through either operand.
9013   case Instruction::Sub:   // Can only fold on the amount subtracted.
9014   case Instruction::Shl:   // Can only fold on the shift amount.
9015   case Instruction::LShr:
9016   case Instruction::AShr:
9017     return 1;
9018   default:
9019     return 0;              // Cannot fold
9020   }
9021 }
9022
9023 /// GetSelectFoldableConstant - For the same transformation as the previous
9024 /// function, return the identity constant that goes into the select.
9025 static Constant *GetSelectFoldableConstant(Instruction *I,
9026                                            LLVMContext *Context) {
9027   switch (I->getOpcode()) {
9028   default: llvm_unreachable("This cannot happen!");
9029   case Instruction::Add:
9030   case Instruction::Sub:
9031   case Instruction::Or:
9032   case Instruction::Xor:
9033   case Instruction::Shl:
9034   case Instruction::LShr:
9035   case Instruction::AShr:
9036     return Constant::getNullValue(I->getType());
9037   case Instruction::And:
9038     return Constant::getAllOnesValue(I->getType());
9039   case Instruction::Mul:
9040     return ConstantInt::get(I->getType(), 1);
9041   }
9042 }
9043
9044 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9045 /// have the same opcode and only one use each.  Try to simplify this.
9046 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9047                                           Instruction *FI) {
9048   if (TI->getNumOperands() == 1) {
9049     // If this is a non-volatile load or a cast from the same type,
9050     // merge.
9051     if (TI->isCast()) {
9052       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9053         return 0;
9054     } else {
9055       return 0;  // unknown unary op.
9056     }
9057
9058     // Fold this by inserting a select from the input values.
9059     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9060                                           FI->getOperand(0), SI.getName()+".v");
9061     InsertNewInstBefore(NewSI, SI);
9062     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9063                             TI->getType());
9064   }
9065
9066   // Only handle binary operators here.
9067   if (!isa<BinaryOperator>(TI))
9068     return 0;
9069
9070   // Figure out if the operations have any operands in common.
9071   Value *MatchOp, *OtherOpT, *OtherOpF;
9072   bool MatchIsOpZero;
9073   if (TI->getOperand(0) == FI->getOperand(0)) {
9074     MatchOp  = TI->getOperand(0);
9075     OtherOpT = TI->getOperand(1);
9076     OtherOpF = FI->getOperand(1);
9077     MatchIsOpZero = true;
9078   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9079     MatchOp  = TI->getOperand(1);
9080     OtherOpT = TI->getOperand(0);
9081     OtherOpF = FI->getOperand(0);
9082     MatchIsOpZero = false;
9083   } else if (!TI->isCommutative()) {
9084     return 0;
9085   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9086     MatchOp  = TI->getOperand(0);
9087     OtherOpT = TI->getOperand(1);
9088     OtherOpF = FI->getOperand(0);
9089     MatchIsOpZero = true;
9090   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9091     MatchOp  = TI->getOperand(1);
9092     OtherOpT = TI->getOperand(0);
9093     OtherOpF = FI->getOperand(1);
9094     MatchIsOpZero = true;
9095   } else {
9096     return 0;
9097   }
9098
9099   // If we reach here, they do have operations in common.
9100   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9101                                          OtherOpF, SI.getName()+".v");
9102   InsertNewInstBefore(NewSI, SI);
9103
9104   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9105     if (MatchIsOpZero)
9106       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9107     else
9108       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9109   }
9110   llvm_unreachable("Shouldn't get here");
9111   return 0;
9112 }
9113
9114 static bool isSelect01(Constant *C1, Constant *C2) {
9115   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9116   if (!C1I)
9117     return false;
9118   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9119   if (!C2I)
9120     return false;
9121   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9122 }
9123
9124 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9125 /// facilitate further optimization.
9126 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9127                                             Value *FalseVal) {
9128   // See the comment above GetSelectFoldableOperands for a description of the
9129   // transformation we are doing here.
9130   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9131     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9132         !isa<Constant>(FalseVal)) {
9133       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9134         unsigned OpToFold = 0;
9135         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9136           OpToFold = 1;
9137         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9138           OpToFold = 2;
9139         }
9140
9141         if (OpToFold) {
9142           Constant *C = GetSelectFoldableConstant(TVI, Context);
9143           Value *OOp = TVI->getOperand(2-OpToFold);
9144           // Avoid creating select between 2 constants unless it's selecting
9145           // between 0 and 1.
9146           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9147             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9148             InsertNewInstBefore(NewSel, SI);
9149             NewSel->takeName(TVI);
9150             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9151               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9152             llvm_unreachable("Unknown instruction!!");
9153           }
9154         }
9155       }
9156     }
9157   }
9158
9159   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9160     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9161         !isa<Constant>(TrueVal)) {
9162       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9163         unsigned OpToFold = 0;
9164         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9165           OpToFold = 1;
9166         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9167           OpToFold = 2;
9168         }
9169
9170         if (OpToFold) {
9171           Constant *C = GetSelectFoldableConstant(FVI, Context);
9172           Value *OOp = FVI->getOperand(2-OpToFold);
9173           // Avoid creating select between 2 constants unless it's selecting
9174           // between 0 and 1.
9175           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9176             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9177             InsertNewInstBefore(NewSel, SI);
9178             NewSel->takeName(FVI);
9179             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9180               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9181             llvm_unreachable("Unknown instruction!!");
9182           }
9183         }
9184       }
9185     }
9186   }
9187
9188   return 0;
9189 }
9190
9191 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9192 /// ICmpInst as its first operand.
9193 ///
9194 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9195                                                    ICmpInst *ICI) {
9196   bool Changed = false;
9197   ICmpInst::Predicate Pred = ICI->getPredicate();
9198   Value *CmpLHS = ICI->getOperand(0);
9199   Value *CmpRHS = ICI->getOperand(1);
9200   Value *TrueVal = SI.getTrueValue();
9201   Value *FalseVal = SI.getFalseValue();
9202
9203   // Check cases where the comparison is with a constant that
9204   // can be adjusted to fit the min/max idiom. We may edit ICI in
9205   // place here, so make sure the select is the only user.
9206   if (ICI->hasOneUse())
9207     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9208       switch (Pred) {
9209       default: break;
9210       case ICmpInst::ICMP_ULT:
9211       case ICmpInst::ICMP_SLT: {
9212         // X < MIN ? T : F  -->  F
9213         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9214           return ReplaceInstUsesWith(SI, FalseVal);
9215         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9216         Constant *AdjustedRHS = SubOne(CI);
9217         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9218             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9219           Pred = ICmpInst::getSwappedPredicate(Pred);
9220           CmpRHS = AdjustedRHS;
9221           std::swap(FalseVal, TrueVal);
9222           ICI->setPredicate(Pred);
9223           ICI->setOperand(1, CmpRHS);
9224           SI.setOperand(1, TrueVal);
9225           SI.setOperand(2, FalseVal);
9226           Changed = true;
9227         }
9228         break;
9229       }
9230       case ICmpInst::ICMP_UGT:
9231       case ICmpInst::ICMP_SGT: {
9232         // X > MAX ? T : F  -->  F
9233         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9234           return ReplaceInstUsesWith(SI, FalseVal);
9235         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9236         Constant *AdjustedRHS = AddOne(CI);
9237         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9238             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9239           Pred = ICmpInst::getSwappedPredicate(Pred);
9240           CmpRHS = AdjustedRHS;
9241           std::swap(FalseVal, TrueVal);
9242           ICI->setPredicate(Pred);
9243           ICI->setOperand(1, CmpRHS);
9244           SI.setOperand(1, TrueVal);
9245           SI.setOperand(2, FalseVal);
9246           Changed = true;
9247         }
9248         break;
9249       }
9250       }
9251
9252       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9253       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9254       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9255       if (match(TrueVal, m_ConstantInt<-1>()) &&
9256           match(FalseVal, m_ConstantInt<0>()))
9257         Pred = ICI->getPredicate();
9258       else if (match(TrueVal, m_ConstantInt<0>()) &&
9259                match(FalseVal, m_ConstantInt<-1>()))
9260         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9261       
9262       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9263         // If we are just checking for a icmp eq of a single bit and zext'ing it
9264         // to an integer, then shift the bit to the appropriate place and then
9265         // cast to integer to avoid the comparison.
9266         const APInt &Op1CV = CI->getValue();
9267     
9268         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9269         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9270         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9271             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9272           Value *In = ICI->getOperand(0);
9273           Value *Sh = ConstantInt::get(In->getType(),
9274                                        In->getType()->getScalarSizeInBits()-1);
9275           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9276                                                         In->getName()+".lobit"),
9277                                    *ICI);
9278           if (In->getType() != SI.getType())
9279             In = CastInst::CreateIntegerCast(In, SI.getType(),
9280                                              true/*SExt*/, "tmp", ICI);
9281     
9282           if (Pred == ICmpInst::ICMP_SGT)
9283             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9284                                        In->getName()+".not"), *ICI);
9285     
9286           return ReplaceInstUsesWith(SI, In);
9287         }
9288       }
9289     }
9290
9291   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9292     // Transform (X == Y) ? X : Y  -> Y
9293     if (Pred == ICmpInst::ICMP_EQ)
9294       return ReplaceInstUsesWith(SI, FalseVal);
9295     // Transform (X != Y) ? X : Y  -> X
9296     if (Pred == ICmpInst::ICMP_NE)
9297       return ReplaceInstUsesWith(SI, TrueVal);
9298     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9299
9300   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9301     // Transform (X == Y) ? Y : X  -> X
9302     if (Pred == ICmpInst::ICMP_EQ)
9303       return ReplaceInstUsesWith(SI, FalseVal);
9304     // Transform (X != Y) ? Y : X  -> Y
9305     if (Pred == ICmpInst::ICMP_NE)
9306       return ReplaceInstUsesWith(SI, TrueVal);
9307     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9308   }
9309
9310   /// NOTE: if we wanted to, this is where to detect integer ABS
9311
9312   return Changed ? &SI : 0;
9313 }
9314
9315
9316 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9317 /// PHI node (but the two may be in different blocks).  See if the true/false
9318 /// values (V) are live in all of the predecessor blocks of the PHI.  For
9319 /// example, cases like this cannot be mapped:
9320 ///
9321 ///   X = phi [ C1, BB1], [C2, BB2]
9322 ///   Y = add
9323 ///   Z = select X, Y, 0
9324 ///
9325 /// because Y is not live in BB1/BB2.
9326 ///
9327 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9328                                                    const SelectInst &SI) {
9329   // If the value is a non-instruction value like a constant or argument, it
9330   // can always be mapped.
9331   const Instruction *I = dyn_cast<Instruction>(V);
9332   if (I == 0) return true;
9333   
9334   // If V is a PHI node defined in the same block as the condition PHI, we can
9335   // map the arguments.
9336   const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9337   
9338   if (const PHINode *VP = dyn_cast<PHINode>(I))
9339     if (VP->getParent() == CondPHI->getParent())
9340       return true;
9341   
9342   // Otherwise, if the PHI and select are defined in the same block and if V is
9343   // defined in a different block, then we can transform it.
9344   if (SI.getParent() == CondPHI->getParent() &&
9345       I->getParent() != CondPHI->getParent())
9346     return true;
9347   
9348   // Otherwise we have a 'hard' case and we can't tell without doing more
9349   // detailed dominator based analysis, punt.
9350   return false;
9351 }
9352
9353 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9354   Value *CondVal = SI.getCondition();
9355   Value *TrueVal = SI.getTrueValue();
9356   Value *FalseVal = SI.getFalseValue();
9357
9358   // select true, X, Y  -> X
9359   // select false, X, Y -> Y
9360   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9361     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9362
9363   // select C, X, X -> X
9364   if (TrueVal == FalseVal)
9365     return ReplaceInstUsesWith(SI, TrueVal);
9366
9367   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9368     return ReplaceInstUsesWith(SI, FalseVal);
9369   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9370     return ReplaceInstUsesWith(SI, TrueVal);
9371   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9372     if (isa<Constant>(TrueVal))
9373       return ReplaceInstUsesWith(SI, TrueVal);
9374     else
9375       return ReplaceInstUsesWith(SI, FalseVal);
9376   }
9377
9378   if (SI.getType() == Type::getInt1Ty(*Context)) {
9379     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9380       if (C->getZExtValue()) {
9381         // Change: A = select B, true, C --> A = or B, C
9382         return BinaryOperator::CreateOr(CondVal, FalseVal);
9383       } else {
9384         // Change: A = select B, false, C --> A = and !B, C
9385         Value *NotCond =
9386           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9387                                              "not."+CondVal->getName()), SI);
9388         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9389       }
9390     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9391       if (C->getZExtValue() == false) {
9392         // Change: A = select B, C, false --> A = and B, C
9393         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9394       } else {
9395         // Change: A = select B, C, true --> A = or !B, C
9396         Value *NotCond =
9397           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9398                                              "not."+CondVal->getName()), SI);
9399         return BinaryOperator::CreateOr(NotCond, TrueVal);
9400       }
9401     }
9402     
9403     // select a, b, a  -> a&b
9404     // select a, a, b  -> a|b
9405     if (CondVal == TrueVal)
9406       return BinaryOperator::CreateOr(CondVal, FalseVal);
9407     else if (CondVal == FalseVal)
9408       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9409   }
9410
9411   // Selecting between two integer constants?
9412   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9413     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9414       // select C, 1, 0 -> zext C to int
9415       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9416         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9417       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9418         // select C, 0, 1 -> zext !C to int
9419         Value *NotCond =
9420           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9421                                                "not."+CondVal->getName()), SI);
9422         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9423       }
9424
9425       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9426         // If one of the constants is zero (we know they can't both be) and we
9427         // have an icmp instruction with zero, and we have an 'and' with the
9428         // non-constant value, eliminate this whole mess.  This corresponds to
9429         // cases like this: ((X & 27) ? 27 : 0)
9430         if (TrueValC->isZero() || FalseValC->isZero())
9431           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9432               cast<Constant>(IC->getOperand(1))->isNullValue())
9433             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9434               if (ICA->getOpcode() == Instruction::And &&
9435                   isa<ConstantInt>(ICA->getOperand(1)) &&
9436                   (ICA->getOperand(1) == TrueValC ||
9437                    ICA->getOperand(1) == FalseValC) &&
9438                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9439                 // Okay, now we know that everything is set up, we just don't
9440                 // know whether we have a icmp_ne or icmp_eq and whether the 
9441                 // true or false val is the zero.
9442                 bool ShouldNotVal = !TrueValC->isZero();
9443                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9444                 Value *V = ICA;
9445                 if (ShouldNotVal)
9446                   V = InsertNewInstBefore(BinaryOperator::Create(
9447                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9448                 return ReplaceInstUsesWith(SI, V);
9449               }
9450       }
9451     }
9452
9453   // See if we are selecting two values based on a comparison of the two values.
9454   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9455     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9456       // Transform (X == Y) ? X : Y  -> Y
9457       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9458         // This is not safe in general for floating point:  
9459         // consider X== -0, Y== +0.
9460         // It becomes safe if either operand is a nonzero constant.
9461         ConstantFP *CFPt, *CFPf;
9462         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9463               !CFPt->getValueAPF().isZero()) ||
9464             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9465              !CFPf->getValueAPF().isZero()))
9466         return ReplaceInstUsesWith(SI, FalseVal);
9467       }
9468       // Transform (X != Y) ? X : Y  -> X
9469       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9470         return ReplaceInstUsesWith(SI, TrueVal);
9471       // NOTE: if we wanted to, this is where to detect MIN/MAX
9472
9473     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9474       // Transform (X == Y) ? Y : X  -> X
9475       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9476         // This is not safe in general for floating point:  
9477         // consider X== -0, Y== +0.
9478         // It becomes safe if either operand is a nonzero constant.
9479         ConstantFP *CFPt, *CFPf;
9480         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9481               !CFPt->getValueAPF().isZero()) ||
9482             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9483              !CFPf->getValueAPF().isZero()))
9484           return ReplaceInstUsesWith(SI, FalseVal);
9485       }
9486       // Transform (X != Y) ? Y : X  -> Y
9487       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9488         return ReplaceInstUsesWith(SI, TrueVal);
9489       // NOTE: if we wanted to, this is where to detect MIN/MAX
9490     }
9491     // NOTE: if we wanted to, this is where to detect ABS
9492   }
9493
9494   // See if we are selecting two values based on a comparison of the two values.
9495   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9496     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9497       return Result;
9498
9499   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9500     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9501       if (TI->hasOneUse() && FI->hasOneUse()) {
9502         Instruction *AddOp = 0, *SubOp = 0;
9503
9504         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9505         if (TI->getOpcode() == FI->getOpcode())
9506           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9507             return IV;
9508
9509         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9510         // even legal for FP.
9511         if ((TI->getOpcode() == Instruction::Sub &&
9512              FI->getOpcode() == Instruction::Add) ||
9513             (TI->getOpcode() == Instruction::FSub &&
9514              FI->getOpcode() == Instruction::FAdd)) {
9515           AddOp = FI; SubOp = TI;
9516         } else if ((FI->getOpcode() == Instruction::Sub &&
9517                     TI->getOpcode() == Instruction::Add) ||
9518                    (FI->getOpcode() == Instruction::FSub &&
9519                     TI->getOpcode() == Instruction::FAdd)) {
9520           AddOp = TI; SubOp = FI;
9521         }
9522
9523         if (AddOp) {
9524           Value *OtherAddOp = 0;
9525           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9526             OtherAddOp = AddOp->getOperand(1);
9527           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9528             OtherAddOp = AddOp->getOperand(0);
9529           }
9530
9531           if (OtherAddOp) {
9532             // So at this point we know we have (Y -> OtherAddOp):
9533             //        select C, (add X, Y), (sub X, Z)
9534             Value *NegVal;  // Compute -Z
9535             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9536               NegVal = ConstantExpr::getNeg(C);
9537             } else {
9538               NegVal = InsertNewInstBefore(
9539                     BinaryOperator::CreateNeg(SubOp->getOperand(1),
9540                                               "tmp"), SI);
9541             }
9542
9543             Value *NewTrueOp = OtherAddOp;
9544             Value *NewFalseOp = NegVal;
9545             if (AddOp != TI)
9546               std::swap(NewTrueOp, NewFalseOp);
9547             Instruction *NewSel =
9548               SelectInst::Create(CondVal, NewTrueOp,
9549                                  NewFalseOp, SI.getName() + ".p");
9550
9551             NewSel = InsertNewInstBefore(NewSel, SI);
9552             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9553           }
9554         }
9555       }
9556
9557   // See if we can fold the select into one of our operands.
9558   if (SI.getType()->isInteger()) {
9559     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9560     if (FoldI)
9561       return FoldI;
9562   }
9563
9564   // See if we can fold the select into a phi node if the condition is a select.
9565   if (isa<PHINode>(SI.getCondition())) 
9566     // The true/false values have to be live in the PHI predecessor's blocks.
9567     if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
9568         CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
9569       if (Instruction *NV = FoldOpIntoPhi(SI))
9570         return NV;
9571
9572   if (BinaryOperator::isNot(CondVal)) {
9573     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9574     SI.setOperand(1, FalseVal);
9575     SI.setOperand(2, TrueVal);
9576     return &SI;
9577   }
9578
9579   return 0;
9580 }
9581
9582 /// EnforceKnownAlignment - If the specified pointer points to an object that
9583 /// we control, modify the object's alignment to PrefAlign. This isn't
9584 /// often possible though. If alignment is important, a more reliable approach
9585 /// is to simply align all global variables and allocation instructions to
9586 /// their preferred alignment from the beginning.
9587 ///
9588 static unsigned EnforceKnownAlignment(Value *V,
9589                                       unsigned Align, unsigned PrefAlign) {
9590
9591   User *U = dyn_cast<User>(V);
9592   if (!U) return Align;
9593
9594   switch (Operator::getOpcode(U)) {
9595   default: break;
9596   case Instruction::BitCast:
9597     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9598   case Instruction::GetElementPtr: {
9599     // If all indexes are zero, it is just the alignment of the base pointer.
9600     bool AllZeroOperands = true;
9601     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9602       if (!isa<Constant>(*i) ||
9603           !cast<Constant>(*i)->isNullValue()) {
9604         AllZeroOperands = false;
9605         break;
9606       }
9607
9608     if (AllZeroOperands) {
9609       // Treat this like a bitcast.
9610       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9611     }
9612     break;
9613   }
9614   }
9615
9616   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9617     // If there is a large requested alignment and we can, bump up the alignment
9618     // of the global.
9619     if (!GV->isDeclaration()) {
9620       if (GV->getAlignment() >= PrefAlign)
9621         Align = GV->getAlignment();
9622       else {
9623         GV->setAlignment(PrefAlign);
9624         Align = PrefAlign;
9625       }
9626     }
9627   } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9628     // If there is a requested alignment and if this is an alloca, round up.
9629     if (AI->getAlignment() >= PrefAlign)
9630       Align = AI->getAlignment();
9631     else {
9632       AI->setAlignment(PrefAlign);
9633       Align = PrefAlign;
9634     }
9635   }
9636
9637   return Align;
9638 }
9639
9640 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9641 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9642 /// and it is more than the alignment of the ultimate object, see if we can
9643 /// increase the alignment of the ultimate object, making this check succeed.
9644 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9645                                                   unsigned PrefAlign) {
9646   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9647                       sizeof(PrefAlign) * CHAR_BIT;
9648   APInt Mask = APInt::getAllOnesValue(BitWidth);
9649   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9650   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9651   unsigned TrailZ = KnownZero.countTrailingOnes();
9652   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9653
9654   if (PrefAlign > Align)
9655     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9656   
9657     // We don't need to make any adjustment.
9658   return Align;
9659 }
9660
9661 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9662   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9663   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9664   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9665   unsigned CopyAlign = MI->getAlignment();
9666
9667   if (CopyAlign < MinAlign) {
9668     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 
9669                                              MinAlign, false));
9670     return MI;
9671   }
9672   
9673   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9674   // load/store.
9675   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9676   if (MemOpLength == 0) return 0;
9677   
9678   // Source and destination pointer types are always "i8*" for intrinsic.  See
9679   // if the size is something we can handle with a single primitive load/store.
9680   // A single load+store correctly handles overlapping memory in the memmove
9681   // case.
9682   unsigned Size = MemOpLength->getZExtValue();
9683   if (Size == 0) return MI;  // Delete this mem transfer.
9684   
9685   if (Size > 8 || (Size&(Size-1)))
9686     return 0;  // If not 1/2/4/8 bytes, exit.
9687   
9688   // Use an integer load+store unless we can find something better.
9689   Type *NewPtrTy =
9690                 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
9691   
9692   // Memcpy forces the use of i8* for the source and destination.  That means
9693   // that if you're using memcpy to move one double around, you'll get a cast
9694   // from double* to i8*.  We'd much rather use a double load+store rather than
9695   // an i64 load+store, here because this improves the odds that the source or
9696   // dest address will be promotable.  See if we can find a better type than the
9697   // integer datatype.
9698   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9699     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9700     if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9701       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9702       // down through these levels if so.
9703       while (!SrcETy->isSingleValueType()) {
9704         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9705           if (STy->getNumElements() == 1)
9706             SrcETy = STy->getElementType(0);
9707           else
9708             break;
9709         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9710           if (ATy->getNumElements() == 1)
9711             SrcETy = ATy->getElementType();
9712           else
9713             break;
9714         } else
9715           break;
9716       }
9717       
9718       if (SrcETy->isSingleValueType())
9719         NewPtrTy = PointerType::getUnqual(SrcETy);
9720     }
9721   }
9722   
9723   
9724   // If the memcpy/memmove provides better alignment info than we can
9725   // infer, use it.
9726   SrcAlign = std::max(SrcAlign, CopyAlign);
9727   DstAlign = std::max(DstAlign, CopyAlign);
9728   
9729   Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9730   Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
9731   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9732   InsertNewInstBefore(L, *MI);
9733   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9734
9735   // Set the size of the copy to 0, it will be deleted on the next iteration.
9736   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9737   return MI;
9738 }
9739
9740 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9741   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9742   if (MI->getAlignment() < Alignment) {
9743     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9744                                              Alignment, false));
9745     return MI;
9746   }
9747   
9748   // Extract the length and alignment and fill if they are constant.
9749   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9750   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9751   if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
9752     return 0;
9753   uint64_t Len = LenC->getZExtValue();
9754   Alignment = MI->getAlignment();
9755   
9756   // If the length is zero, this is a no-op
9757   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9758   
9759   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9760   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9761     const Type *ITy = IntegerType::get(*Context, Len*8);  // n=1 -> i8.
9762     
9763     Value *Dest = MI->getDest();
9764     Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
9765
9766     // Alignment 0 is identity for alignment 1 for memset, but not store.
9767     if (Alignment == 0) Alignment = 1;
9768     
9769     // Extract the fill value and store.
9770     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9771     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9772                                       Dest, false, Alignment), *MI);
9773     
9774     // Set the size of the copy to 0, it will be deleted on the next iteration.
9775     MI->setLength(Constant::getNullValue(LenC->getType()));
9776     return MI;
9777   }
9778
9779   return 0;
9780 }
9781
9782
9783 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9784 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9785 /// the heavy lifting.
9786 ///
9787 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9788   if (isFreeCall(&CI))
9789     return visitFree(CI);
9790
9791   // If the caller function is nounwind, mark the call as nounwind, even if the
9792   // callee isn't.
9793   if (CI.getParent()->getParent()->doesNotThrow() &&
9794       !CI.doesNotThrow()) {
9795     CI.setDoesNotThrow();
9796     return &CI;
9797   }
9798   
9799   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9800   if (!II) return visitCallSite(&CI);
9801   
9802   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9803   // visitCallSite.
9804   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9805     bool Changed = false;
9806
9807     // memmove/cpy/set of zero bytes is a noop.
9808     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9809       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9810
9811       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9812         if (CI->getZExtValue() == 1) {
9813           // Replace the instruction with just byte operations.  We would
9814           // transform other cases to loads/stores, but we don't know if
9815           // alignment is sufficient.
9816         }
9817     }
9818
9819     // If we have a memmove and the source operation is a constant global,
9820     // then the source and dest pointers can't alias, so we can change this
9821     // into a call to memcpy.
9822     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9823       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9824         if (GVSrc->isConstant()) {
9825           Module *M = CI.getParent()->getParent()->getParent();
9826           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9827           const Type *Tys[1];
9828           Tys[0] = CI.getOperand(3)->getType();
9829           CI.setOperand(0, 
9830                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9831           Changed = true;
9832         }
9833
9834       // memmove(x,x,size) -> noop.
9835       if (MMI->getSource() == MMI->getDest())
9836         return EraseInstFromFunction(CI);
9837     }
9838
9839     // If we can determine a pointer alignment that is bigger than currently
9840     // set, update the alignment.
9841     if (isa<MemTransferInst>(MI)) {
9842       if (Instruction *I = SimplifyMemTransfer(MI))
9843         return I;
9844     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9845       if (Instruction *I = SimplifyMemSet(MSI))
9846         return I;
9847     }
9848           
9849     if (Changed) return II;
9850   }
9851   
9852   switch (II->getIntrinsicID()) {
9853   default: break;
9854   case Intrinsic::bswap:
9855     // bswap(bswap(x)) -> x
9856     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9857       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9858         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9859     break;
9860   case Intrinsic::ppc_altivec_lvx:
9861   case Intrinsic::ppc_altivec_lvxl:
9862   case Intrinsic::x86_sse_loadu_ps:
9863   case Intrinsic::x86_sse2_loadu_pd:
9864   case Intrinsic::x86_sse2_loadu_dq:
9865     // Turn PPC lvx     -> load if the pointer is known aligned.
9866     // Turn X86 loadups -> load if the pointer is known aligned.
9867     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9868       Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9869                                          PointerType::getUnqual(II->getType()));
9870       return new LoadInst(Ptr);
9871     }
9872     break;
9873   case Intrinsic::ppc_altivec_stvx:
9874   case Intrinsic::ppc_altivec_stvxl:
9875     // Turn stvx -> store if the pointer is known aligned.
9876     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9877       const Type *OpPtrTy = 
9878         PointerType::getUnqual(II->getOperand(1)->getType());
9879       Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
9880       return new StoreInst(II->getOperand(1), Ptr);
9881     }
9882     break;
9883   case Intrinsic::x86_sse_storeu_ps:
9884   case Intrinsic::x86_sse2_storeu_pd:
9885   case Intrinsic::x86_sse2_storeu_dq:
9886     // Turn X86 storeu -> store if the pointer is known aligned.
9887     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9888       const Type *OpPtrTy = 
9889         PointerType::getUnqual(II->getOperand(2)->getType());
9890       Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
9891       return new StoreInst(II->getOperand(2), Ptr);
9892     }
9893     break;
9894     
9895   case Intrinsic::x86_sse_cvttss2si: {
9896     // These intrinsics only demands the 0th element of its input vector.  If
9897     // we can simplify the input based on that, do so now.
9898     unsigned VWidth =
9899       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9900     APInt DemandedElts(VWidth, 1);
9901     APInt UndefElts(VWidth, 0);
9902     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9903                                               UndefElts)) {
9904       II->setOperand(1, V);
9905       return II;
9906     }
9907     break;
9908   }
9909     
9910   case Intrinsic::ppc_altivec_vperm:
9911     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9912     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9913       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9914       
9915       // Check that all of the elements are integer constants or undefs.
9916       bool AllEltsOk = true;
9917       for (unsigned i = 0; i != 16; ++i) {
9918         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9919             !isa<UndefValue>(Mask->getOperand(i))) {
9920           AllEltsOk = false;
9921           break;
9922         }
9923       }
9924       
9925       if (AllEltsOk) {
9926         // Cast the input vectors to byte vectors.
9927         Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9928         Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
9929         Value *Result = UndefValue::get(Op0->getType());
9930         
9931         // Only extract each element once.
9932         Value *ExtractedElts[32];
9933         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9934         
9935         for (unsigned i = 0; i != 16; ++i) {
9936           if (isa<UndefValue>(Mask->getOperand(i)))
9937             continue;
9938           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9939           Idx &= 31;  // Match the hardware behavior.
9940           
9941           if (ExtractedElts[Idx] == 0) {
9942             ExtractedElts[Idx] = 
9943               Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1, 
9944                   ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9945                                             "tmp");
9946           }
9947         
9948           // Insert this value into the result vector.
9949           Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9950                          ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9951                                                 "tmp");
9952         }
9953         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9954       }
9955     }
9956     break;
9957
9958   case Intrinsic::stackrestore: {
9959     // If the save is right next to the restore, remove the restore.  This can
9960     // happen when variable allocas are DCE'd.
9961     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9962       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9963         BasicBlock::iterator BI = SS;
9964         if (&*++BI == II)
9965           return EraseInstFromFunction(CI);
9966       }
9967     }
9968     
9969     // Scan down this block to see if there is another stack restore in the
9970     // same block without an intervening call/alloca.
9971     BasicBlock::iterator BI = II;
9972     TerminatorInst *TI = II->getParent()->getTerminator();
9973     bool CannotRemove = false;
9974     for (++BI; &*BI != TI; ++BI) {
9975       if (isa<AllocaInst>(BI) || isMalloc(BI)) {
9976         CannotRemove = true;
9977         break;
9978       }
9979       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9980         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9981           // If there is a stackrestore below this one, remove this one.
9982           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9983             return EraseInstFromFunction(CI);
9984           // Otherwise, ignore the intrinsic.
9985         } else {
9986           // If we found a non-intrinsic call, we can't remove the stack
9987           // restore.
9988           CannotRemove = true;
9989           break;
9990         }
9991       }
9992     }
9993     
9994     // If the stack restore is in a return/unwind block and if there are no
9995     // allocas or calls between the restore and the return, nuke the restore.
9996     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9997       return EraseInstFromFunction(CI);
9998     break;
9999   }
10000   }
10001
10002   return visitCallSite(II);
10003 }
10004
10005 // InvokeInst simplification
10006 //
10007 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10008   return visitCallSite(&II);
10009 }
10010
10011 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
10012 /// passed through the varargs area, we can eliminate the use of the cast.
10013 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10014                                          const CastInst * const CI,
10015                                          const TargetData * const TD,
10016                                          const int ix) {
10017   if (!CI->isLosslessCast())
10018     return false;
10019
10020   // The size of ByVal arguments is derived from the type, so we
10021   // can't change to a type with a different size.  If the size were
10022   // passed explicitly we could avoid this check.
10023   if (!CS.paramHasAttr(ix, Attribute::ByVal))
10024     return true;
10025
10026   const Type* SrcTy = 
10027             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10028   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10029   if (!SrcTy->isSized() || !DstTy->isSized())
10030     return false;
10031   if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10032     return false;
10033   return true;
10034 }
10035
10036 // visitCallSite - Improvements for call and invoke instructions.
10037 //
10038 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10039   bool Changed = false;
10040
10041   // If the callee is a constexpr cast of a function, attempt to move the cast
10042   // to the arguments of the call/invoke.
10043   if (transformConstExprCastCall(CS)) return 0;
10044
10045   Value *Callee = CS.getCalledValue();
10046
10047   if (Function *CalleeF = dyn_cast<Function>(Callee))
10048     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10049       Instruction *OldCall = CS.getInstruction();
10050       // If the call and callee calling conventions don't match, this call must
10051       // be unreachable, as the call is undefined.
10052       new StoreInst(ConstantInt::getTrue(*Context),
10053                 UndefValue::get(Type::getInt1PtrTy(*Context)), 
10054                                   OldCall);
10055       // If OldCall dues not return void then replaceAllUsesWith undef.
10056       // This allows ValueHandlers and custom metadata to adjust itself.
10057       if (!OldCall->getType()->isVoidTy())
10058         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
10059       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10060         return EraseInstFromFunction(*OldCall);
10061       return 0;
10062     }
10063
10064   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10065     // This instruction is not reachable, just remove it.  We insert a store to
10066     // undef so that we know that this code is not reachable, despite the fact
10067     // that we can't modify the CFG here.
10068     new StoreInst(ConstantInt::getTrue(*Context),
10069                UndefValue::get(Type::getInt1PtrTy(*Context)),
10070                   CS.getInstruction());
10071
10072     // If CS dues not return void then replaceAllUsesWith undef.
10073     // This allows ValueHandlers and custom metadata to adjust itself.
10074     if (!CS.getInstruction()->getType()->isVoidTy())
10075       CS.getInstruction()->
10076         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
10077
10078     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10079       // Don't break the CFG, insert a dummy cond branch.
10080       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10081                          ConstantInt::getTrue(*Context), II);
10082     }
10083     return EraseInstFromFunction(*CS.getInstruction());
10084   }
10085
10086   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10087     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10088       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10089         return transformCallThroughTrampoline(CS);
10090
10091   const PointerType *PTy = cast<PointerType>(Callee->getType());
10092   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10093   if (FTy->isVarArg()) {
10094     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10095     // See if we can optimize any arguments passed through the varargs area of
10096     // the call.
10097     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10098            E = CS.arg_end(); I != E; ++I, ++ix) {
10099       CastInst *CI = dyn_cast<CastInst>(*I);
10100       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10101         *I = CI->getOperand(0);
10102         Changed = true;
10103       }
10104     }
10105   }
10106
10107   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10108     // Inline asm calls cannot throw - mark them 'nounwind'.
10109     CS.setDoesNotThrow();
10110     Changed = true;
10111   }
10112
10113   return Changed ? CS.getInstruction() : 0;
10114 }
10115
10116 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10117 // attempt to move the cast to the arguments of the call/invoke.
10118 //
10119 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10120   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10121   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10122   if (CE->getOpcode() != Instruction::BitCast || 
10123       !isa<Function>(CE->getOperand(0)))
10124     return false;
10125   Function *Callee = cast<Function>(CE->getOperand(0));
10126   Instruction *Caller = CS.getInstruction();
10127   const AttrListPtr &CallerPAL = CS.getAttributes();
10128
10129   // Okay, this is a cast from a function to a different type.  Unless doing so
10130   // would cause a type conversion of one of our arguments, change this call to
10131   // be a direct call with arguments casted to the appropriate types.
10132   //
10133   const FunctionType *FT = Callee->getFunctionType();
10134   const Type *OldRetTy = Caller->getType();
10135   const Type *NewRetTy = FT->getReturnType();
10136
10137   if (isa<StructType>(NewRetTy))
10138     return false; // TODO: Handle multiple return values.
10139
10140   // Check to see if we are changing the return type...
10141   if (OldRetTy != NewRetTy) {
10142     if (Callee->isDeclaration() &&
10143         // Conversion is ok if changing from one pointer type to another or from
10144         // a pointer to an integer of the same size.
10145         !((isa<PointerType>(OldRetTy) || !TD ||
10146            OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
10147           (isa<PointerType>(NewRetTy) || !TD ||
10148            NewRetTy == TD->getIntPtrType(Caller->getContext()))))
10149       return false;   // Cannot transform this return value.
10150
10151     if (!Caller->use_empty() &&
10152         // void -> non-void is handled specially
10153         !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
10154       return false;   // Cannot transform this return value.
10155
10156     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10157       Attributes RAttrs = CallerPAL.getRetAttributes();
10158       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10159         return false;   // Attribute not compatible with transformed value.
10160     }
10161
10162     // If the callsite is an invoke instruction, and the return value is used by
10163     // a PHI node in a successor, we cannot change the return type of the call
10164     // because there is no place to put the cast instruction (without breaking
10165     // the critical edge).  Bail out in this case.
10166     if (!Caller->use_empty())
10167       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10168         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10169              UI != E; ++UI)
10170           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10171             if (PN->getParent() == II->getNormalDest() ||
10172                 PN->getParent() == II->getUnwindDest())
10173               return false;
10174   }
10175
10176   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10177   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10178
10179   CallSite::arg_iterator AI = CS.arg_begin();
10180   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10181     const Type *ParamTy = FT->getParamType(i);
10182     const Type *ActTy = (*AI)->getType();
10183
10184     if (!CastInst::isCastable(ActTy, ParamTy))
10185       return false;   // Cannot transform this parameter value.
10186
10187     if (CallerPAL.getParamAttributes(i + 1) 
10188         & Attribute::typeIncompatible(ParamTy))
10189       return false;   // Attribute not compatible with transformed value.
10190
10191     // Converting from one pointer type to another or between a pointer and an
10192     // integer of the same size is safe even if we do not have a body.
10193     bool isConvertible = ActTy == ParamTy ||
10194       (TD && ((isa<PointerType>(ParamTy) ||
10195       ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10196               (isa<PointerType>(ActTy) ||
10197               ActTy == TD->getIntPtrType(Caller->getContext()))));
10198     if (Callee->isDeclaration() && !isConvertible) return false;
10199   }
10200
10201   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10202       Callee->isDeclaration())
10203     return false;   // Do not delete arguments unless we have a function body.
10204
10205   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10206       !CallerPAL.isEmpty())
10207     // In this case we have more arguments than the new function type, but we
10208     // won't be dropping them.  Check that these extra arguments have attributes
10209     // that are compatible with being a vararg call argument.
10210     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10211       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10212         break;
10213       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10214       if (PAttrs & Attribute::VarArgsIncompatible)
10215         return false;
10216     }
10217
10218   // Okay, we decided that this is a safe thing to do: go ahead and start
10219   // inserting cast instructions as necessary...
10220   std::vector<Value*> Args;
10221   Args.reserve(NumActualArgs);
10222   SmallVector<AttributeWithIndex, 8> attrVec;
10223   attrVec.reserve(NumCommonArgs);
10224
10225   // Get any return attributes.
10226   Attributes RAttrs = CallerPAL.getRetAttributes();
10227
10228   // If the return value is not being used, the type may not be compatible
10229   // with the existing attributes.  Wipe out any problematic attributes.
10230   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10231
10232   // Add the new return attributes.
10233   if (RAttrs)
10234     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10235
10236   AI = CS.arg_begin();
10237   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10238     const Type *ParamTy = FT->getParamType(i);
10239     if ((*AI)->getType() == ParamTy) {
10240       Args.push_back(*AI);
10241     } else {
10242       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10243           false, ParamTy, false);
10244       Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
10245     }
10246
10247     // Add any parameter attributes.
10248     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10249       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10250   }
10251
10252   // If the function takes more arguments than the call was taking, add them
10253   // now.
10254   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10255     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10256
10257   // If we are removing arguments to the function, emit an obnoxious warning.
10258   if (FT->getNumParams() < NumActualArgs) {
10259     if (!FT->isVarArg()) {
10260       errs() << "WARNING: While resolving call to function '"
10261              << Callee->getName() << "' arguments were dropped!\n";
10262     } else {
10263       // Add all of the arguments in their promoted form to the arg list.
10264       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10265         const Type *PTy = getPromotedType((*AI)->getType());
10266         if (PTy != (*AI)->getType()) {
10267           // Must promote to pass through va_arg area!
10268           Instruction::CastOps opcode =
10269             CastInst::getCastOpcode(*AI, false, PTy, false);
10270           Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
10271         } else {
10272           Args.push_back(*AI);
10273         }
10274
10275         // Add any parameter attributes.
10276         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10277           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10278       }
10279     }
10280   }
10281
10282   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10283     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10284
10285   if (NewRetTy->isVoidTy())
10286     Caller->setName("");   // Void type should not have a name.
10287
10288   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10289                                                      attrVec.end());
10290
10291   Instruction *NC;
10292   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10293     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10294                             Args.begin(), Args.end(),
10295                             Caller->getName(), Caller);
10296     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10297     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10298   } else {
10299     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10300                           Caller->getName(), Caller);
10301     CallInst *CI = cast<CallInst>(Caller);
10302     if (CI->isTailCall())
10303       cast<CallInst>(NC)->setTailCall();
10304     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10305     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10306   }
10307
10308   // Insert a cast of the return type as necessary.
10309   Value *NV = NC;
10310   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10311     if (!NV->getType()->isVoidTy()) {
10312       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10313                                                             OldRetTy, false);
10314       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10315
10316       // If this is an invoke instruction, we should insert it after the first
10317       // non-phi, instruction in the normal successor block.
10318       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10319         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10320         InsertNewInstBefore(NC, *I);
10321       } else {
10322         // Otherwise, it's a call, just insert cast right after the call instr
10323         InsertNewInstBefore(NC, *Caller);
10324       }
10325       Worklist.AddUsersToWorkList(*Caller);
10326     } else {
10327       NV = UndefValue::get(Caller->getType());
10328     }
10329   }
10330
10331
10332   if (!Caller->use_empty())
10333     Caller->replaceAllUsesWith(NV);
10334   
10335   EraseInstFromFunction(*Caller);
10336   return true;
10337 }
10338
10339 // transformCallThroughTrampoline - Turn a call to a function created by the
10340 // init_trampoline intrinsic into a direct call to the underlying function.
10341 //
10342 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10343   Value *Callee = CS.getCalledValue();
10344   const PointerType *PTy = cast<PointerType>(Callee->getType());
10345   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10346   const AttrListPtr &Attrs = CS.getAttributes();
10347
10348   // If the call already has the 'nest' attribute somewhere then give up -
10349   // otherwise 'nest' would occur twice after splicing in the chain.
10350   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10351     return 0;
10352
10353   IntrinsicInst *Tramp =
10354     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10355
10356   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10357   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10358   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10359
10360   const AttrListPtr &NestAttrs = NestF->getAttributes();
10361   if (!NestAttrs.isEmpty()) {
10362     unsigned NestIdx = 1;
10363     const Type *NestTy = 0;
10364     Attributes NestAttr = Attribute::None;
10365
10366     // Look for a parameter marked with the 'nest' attribute.
10367     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10368          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10369       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10370         // Record the parameter type and any other attributes.
10371         NestTy = *I;
10372         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10373         break;
10374       }
10375
10376     if (NestTy) {
10377       Instruction *Caller = CS.getInstruction();
10378       std::vector<Value*> NewArgs;
10379       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10380
10381       SmallVector<AttributeWithIndex, 8> NewAttrs;
10382       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10383
10384       // Insert the nest argument into the call argument list, which may
10385       // mean appending it.  Likewise for attributes.
10386
10387       // Add any result attributes.
10388       if (Attributes Attr = Attrs.getRetAttributes())
10389         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10390
10391       {
10392         unsigned Idx = 1;
10393         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10394         do {
10395           if (Idx == NestIdx) {
10396             // Add the chain argument and attributes.
10397             Value *NestVal = Tramp->getOperand(3);
10398             if (NestVal->getType() != NestTy)
10399               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10400             NewArgs.push_back(NestVal);
10401             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10402           }
10403
10404           if (I == E)
10405             break;
10406
10407           // Add the original argument and attributes.
10408           NewArgs.push_back(*I);
10409           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10410             NewAttrs.push_back
10411               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10412
10413           ++Idx, ++I;
10414         } while (1);
10415       }
10416
10417       // Add any function attributes.
10418       if (Attributes Attr = Attrs.getFnAttributes())
10419         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10420
10421       // The trampoline may have been bitcast to a bogus type (FTy).
10422       // Handle this by synthesizing a new function type, equal to FTy
10423       // with the chain parameter inserted.
10424
10425       std::vector<const Type*> NewTypes;
10426       NewTypes.reserve(FTy->getNumParams()+1);
10427
10428       // Insert the chain's type into the list of parameter types, which may
10429       // mean appending it.
10430       {
10431         unsigned Idx = 1;
10432         FunctionType::param_iterator I = FTy->param_begin(),
10433           E = FTy->param_end();
10434
10435         do {
10436           if (Idx == NestIdx)
10437             // Add the chain's type.
10438             NewTypes.push_back(NestTy);
10439
10440           if (I == E)
10441             break;
10442
10443           // Add the original type.
10444           NewTypes.push_back(*I);
10445
10446           ++Idx, ++I;
10447         } while (1);
10448       }
10449
10450       // Replace the trampoline call with a direct call.  Let the generic
10451       // code sort out any function type mismatches.
10452       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 
10453                                                 FTy->isVarArg());
10454       Constant *NewCallee =
10455         NestF->getType() == PointerType::getUnqual(NewFTy) ?
10456         NestF : ConstantExpr::getBitCast(NestF, 
10457                                          PointerType::getUnqual(NewFTy));
10458       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10459                                                    NewAttrs.end());
10460
10461       Instruction *NewCaller;
10462       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10463         NewCaller = InvokeInst::Create(NewCallee,
10464                                        II->getNormalDest(), II->getUnwindDest(),
10465                                        NewArgs.begin(), NewArgs.end(),
10466                                        Caller->getName(), Caller);
10467         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10468         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10469       } else {
10470         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10471                                      Caller->getName(), Caller);
10472         if (cast<CallInst>(Caller)->isTailCall())
10473           cast<CallInst>(NewCaller)->setTailCall();
10474         cast<CallInst>(NewCaller)->
10475           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10476         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10477       }
10478       if (!Caller->getType()->isVoidTy())
10479         Caller->replaceAllUsesWith(NewCaller);
10480       Caller->eraseFromParent();
10481       Worklist.Remove(Caller);
10482       return 0;
10483     }
10484   }
10485
10486   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10487   // parameter, there is no need to adjust the argument list.  Let the generic
10488   // code sort out any function type mismatches.
10489   Constant *NewCallee =
10490     NestF->getType() == PTy ? NestF : 
10491                               ConstantExpr::getBitCast(NestF, PTy);
10492   CS.setCalledFunction(NewCallee);
10493   return CS.getInstruction();
10494 }
10495
10496 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10497 /// and if a/b/c and the add's all have a single use, turn this into a phi
10498 /// and a single binop.
10499 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10500   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10501   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10502   unsigned Opc = FirstInst->getOpcode();
10503   Value *LHSVal = FirstInst->getOperand(0);
10504   Value *RHSVal = FirstInst->getOperand(1);
10505     
10506   const Type *LHSType = LHSVal->getType();
10507   const Type *RHSType = RHSVal->getType();
10508   
10509   // Scan to see if all operands are the same opcode, and all have one use.
10510   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10511     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10512     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10513         // Verify type of the LHS matches so we don't fold cmp's of different
10514         // types or GEP's with different index types.
10515         I->getOperand(0)->getType() != LHSType ||
10516         I->getOperand(1)->getType() != RHSType)
10517       return 0;
10518
10519     // If they are CmpInst instructions, check their predicates
10520     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10521       if (cast<CmpInst>(I)->getPredicate() !=
10522           cast<CmpInst>(FirstInst)->getPredicate())
10523         return 0;
10524     
10525     // Keep track of which operand needs a phi node.
10526     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10527     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10528   }
10529
10530   // If both LHS and RHS would need a PHI, don't do this transformation,
10531   // because it would increase the number of PHIs entering the block,
10532   // which leads to higher register pressure. This is especially
10533   // bad when the PHIs are in the header of a loop.
10534   if (!LHSVal && !RHSVal)
10535     return 0;
10536   
10537   // Otherwise, this is safe to transform!
10538   
10539   Value *InLHS = FirstInst->getOperand(0);
10540   Value *InRHS = FirstInst->getOperand(1);
10541   PHINode *NewLHS = 0, *NewRHS = 0;
10542   if (LHSVal == 0) {
10543     NewLHS = PHINode::Create(LHSType,
10544                              FirstInst->getOperand(0)->getName() + ".pn");
10545     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10546     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10547     InsertNewInstBefore(NewLHS, PN);
10548     LHSVal = NewLHS;
10549   }
10550   
10551   if (RHSVal == 0) {
10552     NewRHS = PHINode::Create(RHSType,
10553                              FirstInst->getOperand(1)->getName() + ".pn");
10554     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10555     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10556     InsertNewInstBefore(NewRHS, PN);
10557     RHSVal = NewRHS;
10558   }
10559   
10560   // Add all operands to the new PHIs.
10561   if (NewLHS || NewRHS) {
10562     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10563       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10564       if (NewLHS) {
10565         Value *NewInLHS = InInst->getOperand(0);
10566         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10567       }
10568       if (NewRHS) {
10569         Value *NewInRHS = InInst->getOperand(1);
10570         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10571       }
10572     }
10573   }
10574     
10575   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10576     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10577   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10578   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10579                          LHSVal, RHSVal);
10580 }
10581
10582 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10583   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10584   
10585   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10586                                         FirstInst->op_end());
10587   // This is true if all GEP bases are allocas and if all indices into them are
10588   // constants.
10589   bool AllBasePointersAreAllocas = true;
10590
10591   // We don't want to replace this phi if the replacement would require
10592   // more than one phi, which leads to higher register pressure. This is
10593   // especially bad when the PHIs are in the header of a loop.
10594   bool NeededPhi = false;
10595   
10596   // Scan to see if all operands are the same opcode, and all have one use.
10597   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10598     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10599     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10600       GEP->getNumOperands() != FirstInst->getNumOperands())
10601       return 0;
10602
10603     // Keep track of whether or not all GEPs are of alloca pointers.
10604     if (AllBasePointersAreAllocas &&
10605         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10606          !GEP->hasAllConstantIndices()))
10607       AllBasePointersAreAllocas = false;
10608     
10609     // Compare the operand lists.
10610     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10611       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10612         continue;
10613       
10614       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10615       // if one of the PHIs has a constant for the index.  The index may be
10616       // substantially cheaper to compute for the constants, so making it a
10617       // variable index could pessimize the path.  This also handles the case
10618       // for struct indices, which must always be constant.
10619       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10620           isa<ConstantInt>(GEP->getOperand(op)))
10621         return 0;
10622       
10623       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10624         return 0;
10625
10626       // If we already needed a PHI for an earlier operand, and another operand
10627       // also requires a PHI, we'd be introducing more PHIs than we're
10628       // eliminating, which increases register pressure on entry to the PHI's
10629       // block.
10630       if (NeededPhi)
10631         return 0;
10632
10633       FixedOperands[op] = 0;  // Needs a PHI.
10634       NeededPhi = true;
10635     }
10636   }
10637   
10638   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10639   // bother doing this transformation.  At best, this will just save a bit of
10640   // offset calculation, but all the predecessors will have to materialize the
10641   // stack address into a register anyway.  We'd actually rather *clone* the
10642   // load up into the predecessors so that we have a load of a gep of an alloca,
10643   // which can usually all be folded into the load.
10644   if (AllBasePointersAreAllocas)
10645     return 0;
10646   
10647   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10648   // that is variable.
10649   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10650   
10651   bool HasAnyPHIs = false;
10652   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10653     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10654     Value *FirstOp = FirstInst->getOperand(i);
10655     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10656                                      FirstOp->getName()+".pn");
10657     InsertNewInstBefore(NewPN, PN);
10658     
10659     NewPN->reserveOperandSpace(e);
10660     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10661     OperandPhis[i] = NewPN;
10662     FixedOperands[i] = NewPN;
10663     HasAnyPHIs = true;
10664   }
10665
10666   
10667   // Add all operands to the new PHIs.
10668   if (HasAnyPHIs) {
10669     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10670       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10671       BasicBlock *InBB = PN.getIncomingBlock(i);
10672       
10673       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10674         if (PHINode *OpPhi = OperandPhis[op])
10675           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10676     }
10677   }
10678   
10679   Value *Base = FixedOperands[0];
10680   return cast<GEPOperator>(FirstInst)->isInBounds() ?
10681     GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10682                                       FixedOperands.end()) :
10683     GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10684                               FixedOperands.end());
10685 }
10686
10687
10688 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10689 /// sink the load out of the block that defines it.  This means that it must be
10690 /// obvious the value of the load is not changed from the point of the load to
10691 /// the end of the block it is in.
10692 ///
10693 /// Finally, it is safe, but not profitable, to sink a load targetting a
10694 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10695 /// to a register.
10696 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10697   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10698   
10699   for (++BBI; BBI != E; ++BBI)
10700     if (BBI->mayWriteToMemory())
10701       return false;
10702   
10703   // Check for non-address taken alloca.  If not address-taken already, it isn't
10704   // profitable to do this xform.
10705   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10706     bool isAddressTaken = false;
10707     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10708          UI != E; ++UI) {
10709       if (isa<LoadInst>(UI)) continue;
10710       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10711         // If storing TO the alloca, then the address isn't taken.
10712         if (SI->getOperand(1) == AI) continue;
10713       }
10714       isAddressTaken = true;
10715       break;
10716     }
10717     
10718     if (!isAddressTaken && AI->isStaticAlloca())
10719       return false;
10720   }
10721   
10722   // If this load is a load from a GEP with a constant offset from an alloca,
10723   // then we don't want to sink it.  In its present form, it will be
10724   // load [constant stack offset].  Sinking it will cause us to have to
10725   // materialize the stack addresses in each predecessor in a register only to
10726   // do a shared load from register in the successor.
10727   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10728     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10729       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10730         return false;
10731   
10732   return true;
10733 }
10734
10735 Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
10736   LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
10737   
10738   // When processing loads, we need to propagate two bits of information to the
10739   // sunk load: whether it is volatile, and what its alignment is.  We currently
10740   // don't sink loads when some have their alignment specified and some don't.
10741   // visitLoadInst will propagate an alignment onto the load when TD is around,
10742   // and if TD isn't around, we can't handle the mixed case.
10743   bool isVolatile = FirstLI->isVolatile();
10744   unsigned LoadAlignment = FirstLI->getAlignment();
10745   
10746   // We can't sink the load if the loaded value could be modified between the
10747   // load and the PHI.
10748   if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
10749       !isSafeAndProfitableToSinkLoad(FirstLI))
10750     return 0;
10751   
10752   // If the PHI is of volatile loads and the load block has multiple
10753   // successors, sinking it would remove a load of the volatile value from
10754   // the path through the other successor.
10755   if (isVolatile && 
10756       FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
10757     return 0;
10758   
10759   // Check to see if all arguments are the same operation.
10760   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10761     LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
10762     if (!LI || !LI->hasOneUse())
10763       return 0;
10764     
10765     // We can't sink the load if the loaded value could be modified between 
10766     // the load and the PHI.
10767     if (LI->isVolatile() != isVolatile ||
10768         LI->getParent() != PN.getIncomingBlock(i) ||
10769         !isSafeAndProfitableToSinkLoad(LI))
10770       return 0;
10771       
10772     // If some of the loads have an alignment specified but not all of them,
10773     // we can't do the transformation.
10774     if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
10775       return 0;
10776     
10777     LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
10778     
10779     // If the PHI is of volatile loads and the load block has multiple
10780     // successors, sinking it would remove a load of the volatile value from
10781     // the path through the other successor.
10782     if (isVolatile &&
10783         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10784       return 0;
10785   }
10786   
10787   // Okay, they are all the same operation.  Create a new PHI node of the
10788   // correct type, and PHI together all of the LHS's of the instructions.
10789   PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
10790                                    PN.getName()+".in");
10791   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10792   
10793   Value *InVal = FirstLI->getOperand(0);
10794   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10795   
10796   // Add all operands to the new PHI.
10797   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10798     Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
10799     if (NewInVal != InVal)
10800       InVal = 0;
10801     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10802   }
10803   
10804   Value *PhiVal;
10805   if (InVal) {
10806     // The new PHI unions all of the same values together.  This is really
10807     // common, so we handle it intelligently here for compile-time speed.
10808     PhiVal = InVal;
10809     delete NewPN;
10810   } else {
10811     InsertNewInstBefore(NewPN, PN);
10812     PhiVal = NewPN;
10813   }
10814   
10815   // If this was a volatile load that we are merging, make sure to loop through
10816   // and mark all the input loads as non-volatile.  If we don't do this, we will
10817   // insert a new volatile load and the old ones will not be deletable.
10818   if (isVolatile)
10819     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10820       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10821   
10822   return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
10823 }
10824
10825
10826 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10827 // operator and they all are only used by the PHI, PHI together their
10828 // inputs, and do the operation once, to the result of the PHI.
10829 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10830   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10831
10832   if (isa<GetElementPtrInst>(FirstInst))
10833     return FoldPHIArgGEPIntoPHI(PN);
10834   if (isa<LoadInst>(FirstInst))
10835     return FoldPHIArgLoadIntoPHI(PN);
10836   
10837   // Scan the instruction, looking for input operations that can be folded away.
10838   // If all input operands to the phi are the same instruction (e.g. a cast from
10839   // the same type or "+42") we can pull the operation through the PHI, reducing
10840   // code size and simplifying code.
10841   Constant *ConstantOp = 0;
10842   const Type *CastSrcTy = 0;
10843   
10844   if (isa<CastInst>(FirstInst)) {
10845     CastSrcTy = FirstInst->getOperand(0)->getType();
10846   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10847     // Can fold binop, compare or shift here if the RHS is a constant, 
10848     // otherwise call FoldPHIArgBinOpIntoPHI.
10849     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10850     if (ConstantOp == 0)
10851       return FoldPHIArgBinOpIntoPHI(PN);
10852   } else {
10853     return 0;  // Cannot fold this operation.
10854   }
10855
10856   // Check to see if all arguments are the same operation.
10857   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10858     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10859     if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10860       return 0;
10861     if (CastSrcTy) {
10862       if (I->getOperand(0)->getType() != CastSrcTy)
10863         return 0;  // Cast operation must match.
10864     } else if (I->getOperand(1) != ConstantOp) {
10865       return 0;
10866     }
10867   }
10868
10869   // Okay, they are all the same operation.  Create a new PHI node of the
10870   // correct type, and PHI together all of the LHS's of the instructions.
10871   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10872                                    PN.getName()+".in");
10873   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10874
10875   Value *InVal = FirstInst->getOperand(0);
10876   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10877
10878   // Add all operands to the new PHI.
10879   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10880     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10881     if (NewInVal != InVal)
10882       InVal = 0;
10883     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10884   }
10885
10886   Value *PhiVal;
10887   if (InVal) {
10888     // The new PHI unions all of the same values together.  This is really
10889     // common, so we handle it intelligently here for compile-time speed.
10890     PhiVal = InVal;
10891     delete NewPN;
10892   } else {
10893     InsertNewInstBefore(NewPN, PN);
10894     PhiVal = NewPN;
10895   }
10896
10897   // Insert and return the new operation.
10898   if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
10899     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10900   
10901   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10902     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10903   
10904   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10905   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10906                          PhiVal, ConstantOp);
10907 }
10908
10909 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10910 /// that is dead.
10911 static bool DeadPHICycle(PHINode *PN,
10912                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10913   if (PN->use_empty()) return true;
10914   if (!PN->hasOneUse()) return false;
10915
10916   // Remember this node, and if we find the cycle, return.
10917   if (!PotentiallyDeadPHIs.insert(PN))
10918     return true;
10919   
10920   // Don't scan crazily complex things.
10921   if (PotentiallyDeadPHIs.size() == 16)
10922     return false;
10923
10924   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10925     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10926
10927   return false;
10928 }
10929
10930 /// PHIsEqualValue - Return true if this phi node is always equal to
10931 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10932 ///   z = some value; x = phi (y, z); y = phi (x, z)
10933 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10934                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10935   // See if we already saw this PHI node.
10936   if (!ValueEqualPHIs.insert(PN))
10937     return true;
10938   
10939   // Don't scan crazily complex things.
10940   if (ValueEqualPHIs.size() == 16)
10941     return false;
10942  
10943   // Scan the operands to see if they are either phi nodes or are equal to
10944   // the value.
10945   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10946     Value *Op = PN->getIncomingValue(i);
10947     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10948       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10949         return false;
10950     } else if (Op != NonPhiInVal)
10951       return false;
10952   }
10953   
10954   return true;
10955 }
10956
10957
10958 // PHINode simplification
10959 //
10960 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10961   // If LCSSA is around, don't mess with Phi nodes
10962   if (MustPreserveLCSSA) return 0;
10963   
10964   if (Value *V = PN.hasConstantValue())
10965     return ReplaceInstUsesWith(PN, V);
10966
10967   // If all PHI operands are the same operation, pull them through the PHI,
10968   // reducing code size.
10969   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10970       isa<Instruction>(PN.getIncomingValue(1)) &&
10971       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10972       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10973       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10974       // than themselves more than once.
10975       PN.getIncomingValue(0)->hasOneUse())
10976     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10977       return Result;
10978
10979   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10980   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10981   // PHI)... break the cycle.
10982   if (PN.hasOneUse()) {
10983     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10984     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10985       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10986       PotentiallyDeadPHIs.insert(&PN);
10987       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10988         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10989     }
10990    
10991     // If this phi has a single use, and if that use just computes a value for
10992     // the next iteration of a loop, delete the phi.  This occurs with unused
10993     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10994     // common case here is good because the only other things that catch this
10995     // are induction variable analysis (sometimes) and ADCE, which is only run
10996     // late.
10997     if (PHIUser->hasOneUse() &&
10998         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10999         PHIUser->use_back() == &PN) {
11000       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
11001     }
11002   }
11003
11004   // We sometimes end up with phi cycles that non-obviously end up being the
11005   // same value, for example:
11006   //   z = some value; x = phi (y, z); y = phi (x, z)
11007   // where the phi nodes don't necessarily need to be in the same block.  Do a
11008   // quick check to see if the PHI node only contains a single non-phi value, if
11009   // so, scan to see if the phi cycle is actually equal to that value.
11010   {
11011     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
11012     // Scan for the first non-phi operand.
11013     while (InValNo != NumOperandVals && 
11014            isa<PHINode>(PN.getIncomingValue(InValNo)))
11015       ++InValNo;
11016
11017     if (InValNo != NumOperandVals) {
11018       Value *NonPhiInVal = PN.getOperand(InValNo);
11019       
11020       // Scan the rest of the operands to see if there are any conflicts, if so
11021       // there is no need to recursively scan other phis.
11022       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11023         Value *OpVal = PN.getIncomingValue(InValNo);
11024         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11025           break;
11026       }
11027       
11028       // If we scanned over all operands, then we have one unique value plus
11029       // phi values.  Scan PHI nodes to see if they all merge in each other or
11030       // the value.
11031       if (InValNo == NumOperandVals) {
11032         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11033         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11034           return ReplaceInstUsesWith(PN, NonPhiInVal);
11035       }
11036     }
11037   }
11038
11039   // If there are multiple PHIs, sort their operands so that they all list
11040   // the blocks in the same order. This will help identical PHIs be eliminated
11041   // by other passes. Other passes shouldn't depend on this for correctness
11042   // however.
11043   PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
11044   if (&PN != FirstPN)
11045     for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
11046       BasicBlock *BBA = PN.getIncomingBlock(i);
11047       BasicBlock *BBB = FirstPN->getIncomingBlock(i);
11048       if (BBA != BBB) {
11049         Value *VA = PN.getIncomingValue(i);
11050         unsigned j = PN.getBasicBlockIndex(BBB);
11051         Value *VB = PN.getIncomingValue(j);
11052         PN.setIncomingBlock(i, BBB);
11053         PN.setIncomingValue(i, VB);
11054         PN.setIncomingBlock(j, BBA);
11055         PN.setIncomingValue(j, VA);
11056         // NOTE: Instcombine normally would want us to "return &PN" if we
11057         // modified any of the operands of an instruction.  However, since we
11058         // aren't adding or removing uses (just rearranging them) we don't do
11059         // this in this case.
11060       }
11061     }
11062
11063   return 0;
11064 }
11065
11066 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
11067   Value *PtrOp = GEP.getOperand(0);
11068   // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
11069   if (GEP.getNumOperands() == 1)
11070     return ReplaceInstUsesWith(GEP, PtrOp);
11071
11072   if (isa<UndefValue>(GEP.getOperand(0)))
11073     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
11074
11075   bool HasZeroPointerIndex = false;
11076   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11077     HasZeroPointerIndex = C->isNullValue();
11078
11079   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11080     return ReplaceInstUsesWith(GEP, PtrOp);
11081
11082   // Eliminate unneeded casts for indices.
11083   if (TD) {
11084     bool MadeChange = false;
11085     unsigned PtrSize = TD->getPointerSizeInBits();
11086     
11087     gep_type_iterator GTI = gep_type_begin(GEP);
11088     for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11089          I != E; ++I, ++GTI) {
11090       if (!isa<SequentialType>(*GTI)) continue;
11091       
11092       // If we are using a wider index than needed for this platform, shrink it
11093       // to what we need.  If narrower, sign-extend it to what we need.  This
11094       // explicit cast can make subsequent optimizations more obvious.
11095       unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
11096       if (OpBits == PtrSize)
11097         continue;
11098       
11099       *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
11100       MadeChange = true;
11101     }
11102     if (MadeChange) return &GEP;
11103   }
11104
11105   // Combine Indices - If the source pointer to this getelementptr instruction
11106   // is a getelementptr instruction, combine the indices of the two
11107   // getelementptr instructions into a single instruction.
11108   //
11109   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
11110     // Note that if our source is a gep chain itself that we wait for that
11111     // chain to be resolved before we perform this transformation.  This
11112     // avoids us creating a TON of code in some cases.
11113     //
11114     if (GetElementPtrInst *SrcGEP =
11115           dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11116       if (SrcGEP->getNumOperands() == 2)
11117         return 0;   // Wait until our source is folded to completion.
11118
11119     SmallVector<Value*, 8> Indices;
11120
11121     // Find out whether the last index in the source GEP is a sequential idx.
11122     bool EndsWithSequential = false;
11123     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11124          I != E; ++I)
11125       EndsWithSequential = !isa<StructType>(*I);
11126
11127     // Can we combine the two pointer arithmetics offsets?
11128     if (EndsWithSequential) {
11129       // Replace: gep (gep %P, long B), long A, ...
11130       // With:    T = long A+B; gep %P, T, ...
11131       //
11132       Value *Sum;
11133       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11134       Value *GO1 = GEP.getOperand(1);
11135       if (SO1 == Constant::getNullValue(SO1->getType())) {
11136         Sum = GO1;
11137       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
11138         Sum = SO1;
11139       } else {
11140         // If they aren't the same type, then the input hasn't been processed
11141         // by the loop above yet (which canonicalizes sequential index types to
11142         // intptr_t).  Just avoid transforming this until the input has been
11143         // normalized.
11144         if (SO1->getType() != GO1->getType())
11145           return 0;
11146         Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11147       }
11148
11149       // Update the GEP in place if possible.
11150       if (Src->getNumOperands() == 2) {
11151         GEP.setOperand(0, Src->getOperand(0));
11152         GEP.setOperand(1, Sum);
11153         return &GEP;
11154       }
11155       Indices.append(Src->op_begin()+1, Src->op_end()-1);
11156       Indices.push_back(Sum);
11157       Indices.append(GEP.op_begin()+2, GEP.op_end());
11158     } else if (isa<Constant>(*GEP.idx_begin()) &&
11159                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11160                Src->getNumOperands() != 1) {
11161       // Otherwise we can do the fold if the first index of the GEP is a zero
11162       Indices.append(Src->op_begin()+1, Src->op_end());
11163       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
11164     }
11165
11166     if (!Indices.empty())
11167       return (cast<GEPOperator>(&GEP)->isInBounds() &&
11168               Src->isInBounds()) ?
11169         GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11170                                           Indices.end(), GEP.getName()) :
11171         GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
11172                                   Indices.end(), GEP.getName());
11173   }
11174   
11175   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11176   if (Value *X = getBitCastOperand(PtrOp)) {
11177     assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
11178
11179     // If the input bitcast is actually "bitcast(bitcast(x))", then we don't 
11180     // want to change the gep until the bitcasts are eliminated.
11181     if (getBitCastOperand(X)) {
11182       Worklist.AddValue(PtrOp);
11183       return 0;
11184     }
11185     
11186     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11187     // into     : GEP [10 x i8]* X, i32 0, ...
11188     //
11189     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11190     //           into     : GEP i8* X, ...
11191     // 
11192     // This occurs when the program declares an array extern like "int X[];"
11193     if (HasZeroPointerIndex) {
11194       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11195       const PointerType *XTy = cast<PointerType>(X->getType());
11196       if (const ArrayType *CATy =
11197           dyn_cast<ArrayType>(CPTy->getElementType())) {
11198         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11199         if (CATy->getElementType() == XTy->getElementType()) {
11200           // -> GEP i8* X, ...
11201           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11202           return cast<GEPOperator>(&GEP)->isInBounds() ?
11203             GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11204                                               GEP.getName()) :
11205             GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11206                                       GEP.getName());
11207         }
11208         
11209         if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
11210           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11211           if (CATy->getElementType() == XATy->getElementType()) {
11212             // -> GEP [10 x i8]* X, i32 0, ...
11213             // At this point, we know that the cast source type is a pointer
11214             // to an array of the same type as the destination pointer
11215             // array.  Because the array type is never stepped over (there
11216             // is a leading zero) we can fold the cast into this GEP.
11217             GEP.setOperand(0, X);
11218             return &GEP;
11219           }
11220         }
11221       }
11222     } else if (GEP.getNumOperands() == 2) {
11223       // Transform things like:
11224       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11225       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11226       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11227       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11228       if (TD && isa<ArrayType>(SrcElTy) &&
11229           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11230           TD->getTypeAllocSize(ResElTy)) {
11231         Value *Idx[2];
11232         Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11233         Idx[1] = GEP.getOperand(1);
11234         Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11235           Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11236           Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11237         // V and GEP are both pointer types --> BitCast
11238         return new BitCastInst(NewGEP, GEP.getType());
11239       }
11240       
11241       // Transform things like:
11242       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11243       //   (where tmp = 8*tmp2) into:
11244       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11245       
11246       if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
11247         uint64_t ArrayEltSize =
11248             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11249         
11250         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11251         // allow either a mul, shift, or constant here.
11252         Value *NewIdx = 0;
11253         ConstantInt *Scale = 0;
11254         if (ArrayEltSize == 1) {
11255           NewIdx = GEP.getOperand(1);
11256           Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11257         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11258           NewIdx = ConstantInt::get(CI->getType(), 1);
11259           Scale = CI;
11260         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11261           if (Inst->getOpcode() == Instruction::Shl &&
11262               isa<ConstantInt>(Inst->getOperand(1))) {
11263             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11264             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11265             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11266                                      1ULL << ShAmtVal);
11267             NewIdx = Inst->getOperand(0);
11268           } else if (Inst->getOpcode() == Instruction::Mul &&
11269                      isa<ConstantInt>(Inst->getOperand(1))) {
11270             Scale = cast<ConstantInt>(Inst->getOperand(1));
11271             NewIdx = Inst->getOperand(0);
11272           }
11273         }
11274         
11275         // If the index will be to exactly the right offset with the scale taken
11276         // out, perform the transformation. Note, we don't know whether Scale is
11277         // signed or not. We'll use unsigned version of division/modulo
11278         // operation after making sure Scale doesn't have the sign bit set.
11279         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11280             Scale->getZExtValue() % ArrayEltSize == 0) {
11281           Scale = ConstantInt::get(Scale->getType(),
11282                                    Scale->getZExtValue() / ArrayEltSize);
11283           if (Scale->getZExtValue() != 1) {
11284             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11285                                                        false /*ZExt*/);
11286             NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
11287           }
11288
11289           // Insert the new GEP instruction.
11290           Value *Idx[2];
11291           Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11292           Idx[1] = NewIdx;
11293           Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11294             Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11295             Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11296           // The NewGEP must be pointer typed, so must the old one -> BitCast
11297           return new BitCastInst(NewGEP, GEP.getType());
11298         }
11299       }
11300     }
11301   }
11302   
11303   /// See if we can simplify:
11304   ///   X = bitcast A* to B*
11305   ///   Y = gep X, <...constant indices...>
11306   /// into a gep of the original struct.  This is important for SROA and alias
11307   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11308   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11309     if (TD &&
11310         !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11311       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11312       // a constant back from EmitGEPOffset.
11313       ConstantInt *OffsetV =
11314                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11315       int64_t Offset = OffsetV->getSExtValue();
11316       
11317       // If this GEP instruction doesn't move the pointer, just replace the GEP
11318       // with a bitcast of the real input to the dest type.
11319       if (Offset == 0) {
11320         // If the bitcast is of an allocation, and the allocation will be
11321         // converted to match the type of the cast, don't touch this.
11322         if (isa<AllocaInst>(BCI->getOperand(0)) ||
11323             isMalloc(BCI->getOperand(0))) {
11324           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11325           if (Instruction *I = visitBitCast(*BCI)) {
11326             if (I != BCI) {
11327               I->takeName(BCI);
11328               BCI->getParent()->getInstList().insert(BCI, I);
11329               ReplaceInstUsesWith(*BCI, I);
11330             }
11331             return &GEP;
11332           }
11333         }
11334         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11335       }
11336       
11337       // Otherwise, if the offset is non-zero, we need to find out if there is a
11338       // field at Offset in 'A's type.  If so, we can pull the cast through the
11339       // GEP.
11340       SmallVector<Value*, 8> NewIndices;
11341       const Type *InTy =
11342         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11343       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11344         Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11345           Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11346                                      NewIndices.end()) :
11347           Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11348                              NewIndices.end());
11349         
11350         if (NGEP->getType() == GEP.getType())
11351           return ReplaceInstUsesWith(GEP, NGEP);
11352         NGEP->takeName(&GEP);
11353         return new BitCastInst(NGEP, GEP.getType());
11354       }
11355     }
11356   }    
11357     
11358   return 0;
11359 }
11360
11361 Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
11362   // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
11363   if (AI.isArrayAllocation()) {  // Check C != 1
11364     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11365       const Type *NewTy = 
11366         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11367       assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11368       AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
11369       New->setAlignment(AI.getAlignment());
11370
11371       // Scan to the end of the allocation instructions, to skip over a block of
11372       // allocas if possible...also skip interleaved debug info
11373       //
11374       BasicBlock::iterator It = New;
11375       while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11376
11377       // Now that I is pointing to the first non-allocation-inst in the block,
11378       // insert our getelementptr instruction...
11379       //
11380       Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
11381       Value *Idx[2];
11382       Idx[0] = NullIdx;
11383       Idx[1] = NullIdx;
11384       Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11385                                                    New->getName()+".sub", It);
11386
11387       // Now make everything use the getelementptr instead of the original
11388       // allocation.
11389       return ReplaceInstUsesWith(AI, V);
11390     } else if (isa<UndefValue>(AI.getArraySize())) {
11391       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11392     }
11393   }
11394
11395   if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11396     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11397     // Note that we only do this for alloca's, because malloc should allocate
11398     // and return a unique pointer, even for a zero byte allocation.
11399     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11400       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11401
11402     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11403     if (AI.getAlignment() == 0)
11404       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11405   }
11406
11407   return 0;
11408 }
11409
11410 Instruction *InstCombiner::visitFree(Instruction &FI) {
11411   Value *Op = FI.getOperand(1);
11412
11413   // free undef -> unreachable.
11414   if (isa<UndefValue>(Op)) {
11415     // Insert a new store to null because we cannot modify the CFG here.
11416     new StoreInst(ConstantInt::getTrue(*Context),
11417            UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
11418     return EraseInstFromFunction(FI);
11419   }
11420   
11421   // If we have 'free null' delete the instruction.  This can happen in stl code
11422   // when lots of inlining happens.
11423   if (isa<ConstantPointerNull>(Op))
11424     return EraseInstFromFunction(FI);
11425
11426   // If we have a malloc call whose only use is a free call, delete both.
11427   if (isMalloc(Op)) {
11428     if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11429       if (Op->hasOneUse() && CI->hasOneUse()) {
11430         EraseInstFromFunction(FI);
11431         EraseInstFromFunction(*CI);
11432         return EraseInstFromFunction(*cast<Instruction>(Op));
11433       }
11434     } else {
11435       // Op is a call to malloc
11436       if (Op->hasOneUse()) {
11437         EraseInstFromFunction(FI);
11438         return EraseInstFromFunction(*cast<Instruction>(Op));
11439       }
11440     }
11441   }
11442
11443   return 0;
11444 }
11445
11446 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11447 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11448                                         const TargetData *TD) {
11449   User *CI = cast<User>(LI.getOperand(0));
11450   Value *CastOp = CI->getOperand(0);
11451   LLVMContext *Context = IC.getContext();
11452
11453   const PointerType *DestTy = cast<PointerType>(CI->getType());
11454   const Type *DestPTy = DestTy->getElementType();
11455   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11456
11457     // If the address spaces don't match, don't eliminate the cast.
11458     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11459       return 0;
11460
11461     const Type *SrcPTy = SrcTy->getElementType();
11462
11463     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11464          isa<VectorType>(DestPTy)) {
11465       // If the source is an array, the code below will not succeed.  Check to
11466       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11467       // constants.
11468       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11469         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11470           if (ASrcTy->getNumElements() != 0) {
11471             Value *Idxs[2];
11472             Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11473             Idxs[1] = Idxs[0];
11474             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11475             SrcTy = cast<PointerType>(CastOp->getType());
11476             SrcPTy = SrcTy->getElementType();
11477           }
11478
11479       if (IC.getTargetData() &&
11480           (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11481             isa<VectorType>(SrcPTy)) &&
11482           // Do not allow turning this into a load of an integer, which is then
11483           // casted to a pointer, this pessimizes pointer analysis a lot.
11484           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11485           IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11486                IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11487
11488         // Okay, we are casting from one integer or pointer type to another of
11489         // the same size.  Instead of casting the pointer before the load, cast
11490         // the result of the loaded value.
11491         Value *NewLoad = 
11492           IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
11493         // Now cast the result of the load.
11494         return new BitCastInst(NewLoad, LI.getType());
11495       }
11496     }
11497   }
11498   return 0;
11499 }
11500
11501 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11502   Value *Op = LI.getOperand(0);
11503
11504   // Attempt to improve the alignment.
11505   if (TD) {
11506     unsigned KnownAlign =
11507       GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11508     if (KnownAlign >
11509         (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11510                                   LI.getAlignment()))
11511       LI.setAlignment(KnownAlign);
11512   }
11513
11514   // load (cast X) --> cast (load X) iff safe.
11515   if (isa<CastInst>(Op))
11516     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11517       return Res;
11518
11519   // None of the following transforms are legal for volatile loads.
11520   if (LI.isVolatile()) return 0;
11521   
11522   // Do really simple store-to-load forwarding and load CSE, to catch cases
11523   // where there are several consequtive memory accesses to the same location,
11524   // separated by a few arithmetic operations.
11525   BasicBlock::iterator BBI = &LI;
11526   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11527     return ReplaceInstUsesWith(LI, AvailableVal);
11528
11529   // load(gep null, ...) -> unreachable
11530   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11531     const Value *GEPI0 = GEPI->getOperand(0);
11532     // TODO: Consider a target hook for valid address spaces for this xform.
11533     if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
11534       // Insert a new store to null instruction before the load to indicate
11535       // that this code is not reachable.  We do this instead of inserting
11536       // an unreachable instruction directly because we cannot modify the
11537       // CFG.
11538       new StoreInst(UndefValue::get(LI.getType()),
11539                     Constant::getNullValue(Op->getType()), &LI);
11540       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11541     }
11542   } 
11543
11544   // load null/undef -> unreachable
11545   // TODO: Consider a target hook for valid address spaces for this xform.
11546   if (isa<UndefValue>(Op) ||
11547       (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
11548     // Insert a new store to null instruction before the load to indicate that
11549     // this code is not reachable.  We do this instead of inserting an
11550     // unreachable instruction directly because we cannot modify the CFG.
11551     new StoreInst(UndefValue::get(LI.getType()),
11552                   Constant::getNullValue(Op->getType()), &LI);
11553     return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11554   }
11555
11556   // Instcombine load (constantexpr_cast global) -> cast (load global)
11557   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
11558     if (CE->isCast())
11559       if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11560         return Res;
11561   
11562   if (Op->hasOneUse()) {
11563     // Change select and PHI nodes to select values instead of addresses: this
11564     // helps alias analysis out a lot, allows many others simplifications, and
11565     // exposes redundancy in the code.
11566     //
11567     // Note that we cannot do the transformation unless we know that the
11568     // introduced loads cannot trap!  Something like this is valid as long as
11569     // the condition is always false: load (select bool %C, int* null, int* %G),
11570     // but it would not be valid if we transformed it to load from null
11571     // unconditionally.
11572     //
11573     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11574       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11575       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11576           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11577         Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11578                                         SI->getOperand(1)->getName()+".val");
11579         Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11580                                         SI->getOperand(2)->getName()+".val");
11581         return SelectInst::Create(SI->getCondition(), V1, V2);
11582       }
11583
11584       // load (select (cond, null, P)) -> load P
11585       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11586         if (C->isNullValue()) {
11587           LI.setOperand(0, SI->getOperand(2));
11588           return &LI;
11589         }
11590
11591       // load (select (cond, P, null)) -> load P
11592       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11593         if (C->isNullValue()) {
11594           LI.setOperand(0, SI->getOperand(1));
11595           return &LI;
11596         }
11597     }
11598   }
11599   return 0;
11600 }
11601
11602 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11603 /// when possible.  This makes it generally easy to do alias analysis and/or
11604 /// SROA/mem2reg of the memory object.
11605 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11606   User *CI = cast<User>(SI.getOperand(1));
11607   Value *CastOp = CI->getOperand(0);
11608
11609   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11610   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11611   if (SrcTy == 0) return 0;
11612   
11613   const Type *SrcPTy = SrcTy->getElementType();
11614
11615   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11616     return 0;
11617   
11618   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11619   /// to its first element.  This allows us to handle things like:
11620   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11621   /// on 32-bit hosts.
11622   SmallVector<Value*, 4> NewGEPIndices;
11623   
11624   // If the source is an array, the code below will not succeed.  Check to
11625   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11626   // constants.
11627   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11628     // Index through pointer.
11629     Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
11630     NewGEPIndices.push_back(Zero);
11631     
11632     while (1) {
11633       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11634         if (!STy->getNumElements()) /* Struct can be empty {} */
11635           break;
11636         NewGEPIndices.push_back(Zero);
11637         SrcPTy = STy->getElementType(0);
11638       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11639         NewGEPIndices.push_back(Zero);
11640         SrcPTy = ATy->getElementType();
11641       } else {
11642         break;
11643       }
11644     }
11645     
11646     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11647   }
11648
11649   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11650     return 0;
11651   
11652   // If the pointers point into different address spaces or if they point to
11653   // values with different sizes, we can't do the transformation.
11654   if (!IC.getTargetData() ||
11655       SrcTy->getAddressSpace() != 
11656         cast<PointerType>(CI->getType())->getAddressSpace() ||
11657       IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11658       IC.getTargetData()->getTypeSizeInBits(DestPTy))
11659     return 0;
11660
11661   // Okay, we are casting from one integer or pointer type to another of
11662   // the same size.  Instead of casting the pointer before 
11663   // the store, cast the value to be stored.
11664   Value *NewCast;
11665   Value *SIOp0 = SI.getOperand(0);
11666   Instruction::CastOps opcode = Instruction::BitCast;
11667   const Type* CastSrcTy = SIOp0->getType();
11668   const Type* CastDstTy = SrcPTy;
11669   if (isa<PointerType>(CastDstTy)) {
11670     if (CastSrcTy->isInteger())
11671       opcode = Instruction::IntToPtr;
11672   } else if (isa<IntegerType>(CastDstTy)) {
11673     if (isa<PointerType>(SIOp0->getType()))
11674       opcode = Instruction::PtrToInt;
11675   }
11676   
11677   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11678   // emit a GEP to index into its first field.
11679   if (!NewGEPIndices.empty())
11680     CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11681                                            NewGEPIndices.end());
11682   
11683   NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11684                                    SIOp0->getName()+".c");
11685   return new StoreInst(NewCast, CastOp);
11686 }
11687
11688 /// equivalentAddressValues - Test if A and B will obviously have the same
11689 /// value. This includes recognizing that %t0 and %t1 will have the same
11690 /// value in code like this:
11691 ///   %t0 = getelementptr \@a, 0, 3
11692 ///   store i32 0, i32* %t0
11693 ///   %t1 = getelementptr \@a, 0, 3
11694 ///   %t2 = load i32* %t1
11695 ///
11696 static bool equivalentAddressValues(Value *A, Value *B) {
11697   // Test if the values are trivially equivalent.
11698   if (A == B) return true;
11699   
11700   // Test if the values come form identical arithmetic instructions.
11701   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11702   // its only used to compare two uses within the same basic block, which
11703   // means that they'll always either have the same value or one of them
11704   // will have an undefined value.
11705   if (isa<BinaryOperator>(A) ||
11706       isa<CastInst>(A) ||
11707       isa<PHINode>(A) ||
11708       isa<GetElementPtrInst>(A))
11709     if (Instruction *BI = dyn_cast<Instruction>(B))
11710       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
11711         return true;
11712   
11713   // Otherwise they may not be equivalent.
11714   return false;
11715 }
11716
11717 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11718 // return the llvm.dbg.declare.
11719 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11720   if (!V->hasNUses(2))
11721     return 0;
11722   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11723        UI != E; ++UI) {
11724     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11725       return DI;
11726     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11727       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11728         return DI;
11729       }
11730   }
11731   return 0;
11732 }
11733
11734 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11735   Value *Val = SI.getOperand(0);
11736   Value *Ptr = SI.getOperand(1);
11737
11738   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11739     EraseInstFromFunction(SI);
11740     ++NumCombined;
11741     return 0;
11742   }
11743   
11744   // If the RHS is an alloca with a single use, zapify the store, making the
11745   // alloca dead.
11746   // If the RHS is an alloca with a two uses, the other one being a 
11747   // llvm.dbg.declare, zapify the store and the declare, making the
11748   // alloca dead.  We must do this to prevent declare's from affecting
11749   // codegen.
11750   if (!SI.isVolatile()) {
11751     if (Ptr->hasOneUse()) {
11752       if (isa<AllocaInst>(Ptr)) {
11753         EraseInstFromFunction(SI);
11754         ++NumCombined;
11755         return 0;
11756       }
11757       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11758         if (isa<AllocaInst>(GEP->getOperand(0))) {
11759           if (GEP->getOperand(0)->hasOneUse()) {
11760             EraseInstFromFunction(SI);
11761             ++NumCombined;
11762             return 0;
11763           }
11764           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11765             EraseInstFromFunction(*DI);
11766             EraseInstFromFunction(SI);
11767             ++NumCombined;
11768             return 0;
11769           }
11770         }
11771       }
11772     }
11773     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11774       EraseInstFromFunction(*DI);
11775       EraseInstFromFunction(SI);
11776       ++NumCombined;
11777       return 0;
11778     }
11779   }
11780
11781   // Attempt to improve the alignment.
11782   if (TD) {
11783     unsigned KnownAlign =
11784       GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11785     if (KnownAlign >
11786         (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11787                                   SI.getAlignment()))
11788       SI.setAlignment(KnownAlign);
11789   }
11790
11791   // Do really simple DSE, to catch cases where there are several consecutive
11792   // stores to the same location, separated by a few arithmetic operations. This
11793   // situation often occurs with bitfield accesses.
11794   BasicBlock::iterator BBI = &SI;
11795   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11796        --ScanInsts) {
11797     --BBI;
11798     // Don't count debug info directives, lest they affect codegen,
11799     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11800     // It is necessary for correctness to skip those that feed into a
11801     // llvm.dbg.declare, as these are not present when debugging is off.
11802     if (isa<DbgInfoIntrinsic>(BBI) ||
11803         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11804       ScanInsts++;
11805       continue;
11806     }    
11807     
11808     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11809       // Prev store isn't volatile, and stores to the same location?
11810       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11811                                                           SI.getOperand(1))) {
11812         ++NumDeadStore;
11813         ++BBI;
11814         EraseInstFromFunction(*PrevSI);
11815         continue;
11816       }
11817       break;
11818     }
11819     
11820     // If this is a load, we have to stop.  However, if the loaded value is from
11821     // the pointer we're loading and is producing the pointer we're storing,
11822     // then *this* store is dead (X = load P; store X -> P).
11823     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11824       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11825           !SI.isVolatile()) {
11826         EraseInstFromFunction(SI);
11827         ++NumCombined;
11828         return 0;
11829       }
11830       // Otherwise, this is a load from some other location.  Stores before it
11831       // may not be dead.
11832       break;
11833     }
11834     
11835     // Don't skip over loads or things that can modify memory.
11836     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11837       break;
11838   }
11839   
11840   
11841   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11842
11843   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11844   if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
11845     if (!isa<UndefValue>(Val)) {
11846       SI.setOperand(0, UndefValue::get(Val->getType()));
11847       if (Instruction *U = dyn_cast<Instruction>(Val))
11848         Worklist.Add(U);  // Dropped a use.
11849       ++NumCombined;
11850     }
11851     return 0;  // Do not modify these!
11852   }
11853
11854   // store undef, Ptr -> noop
11855   if (isa<UndefValue>(Val)) {
11856     EraseInstFromFunction(SI);
11857     ++NumCombined;
11858     return 0;
11859   }
11860
11861   // If the pointer destination is a cast, see if we can fold the cast into the
11862   // source instead.
11863   if (isa<CastInst>(Ptr))
11864     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11865       return Res;
11866   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11867     if (CE->isCast())
11868       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11869         return Res;
11870
11871   
11872   // If this store is the last instruction in the basic block (possibly
11873   // excepting debug info instructions and the pointer bitcasts that feed
11874   // into them), and if the block ends with an unconditional branch, try
11875   // to move it to the successor block.
11876   BBI = &SI; 
11877   do {
11878     ++BBI;
11879   } while (isa<DbgInfoIntrinsic>(BBI) ||
11880            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11881   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11882     if (BI->isUnconditional())
11883       if (SimplifyStoreAtEndOfBlock(SI))
11884         return 0;  // xform done!
11885   
11886   return 0;
11887 }
11888
11889 /// SimplifyStoreAtEndOfBlock - Turn things like:
11890 ///   if () { *P = v1; } else { *P = v2 }
11891 /// into a phi node with a store in the successor.
11892 ///
11893 /// Simplify things like:
11894 ///   *P = v1; if () { *P = v2; }
11895 /// into a phi node with a store in the successor.
11896 ///
11897 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11898   BasicBlock *StoreBB = SI.getParent();
11899   
11900   // Check to see if the successor block has exactly two incoming edges.  If
11901   // so, see if the other predecessor contains a store to the same location.
11902   // if so, insert a PHI node (if needed) and move the stores down.
11903   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11904   
11905   // Determine whether Dest has exactly two predecessors and, if so, compute
11906   // the other predecessor.
11907   pred_iterator PI = pred_begin(DestBB);
11908   BasicBlock *OtherBB = 0;
11909   if (*PI != StoreBB)
11910     OtherBB = *PI;
11911   ++PI;
11912   if (PI == pred_end(DestBB))
11913     return false;
11914   
11915   if (*PI != StoreBB) {
11916     if (OtherBB)
11917       return false;
11918     OtherBB = *PI;
11919   }
11920   if (++PI != pred_end(DestBB))
11921     return false;
11922
11923   // Bail out if all the relevant blocks aren't distinct (this can happen,
11924   // for example, if SI is in an infinite loop)
11925   if (StoreBB == DestBB || OtherBB == DestBB)
11926     return false;
11927
11928   // Verify that the other block ends in a branch and is not otherwise empty.
11929   BasicBlock::iterator BBI = OtherBB->getTerminator();
11930   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11931   if (!OtherBr || BBI == OtherBB->begin())
11932     return false;
11933   
11934   // If the other block ends in an unconditional branch, check for the 'if then
11935   // else' case.  there is an instruction before the branch.
11936   StoreInst *OtherStore = 0;
11937   if (OtherBr->isUnconditional()) {
11938     --BBI;
11939     // Skip over debugging info.
11940     while (isa<DbgInfoIntrinsic>(BBI) ||
11941            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11942       if (BBI==OtherBB->begin())
11943         return false;
11944       --BBI;
11945     }
11946     // If this isn't a store, isn't a store to the same location, or if the
11947     // alignments differ, bail out.
11948     OtherStore = dyn_cast<StoreInst>(BBI);
11949     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
11950         OtherStore->getAlignment() != SI.getAlignment())
11951       return false;
11952   } else {
11953     // Otherwise, the other block ended with a conditional branch. If one of the
11954     // destinations is StoreBB, then we have the if/then case.
11955     if (OtherBr->getSuccessor(0) != StoreBB && 
11956         OtherBr->getSuccessor(1) != StoreBB)
11957       return false;
11958     
11959     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11960     // if/then triangle.  See if there is a store to the same ptr as SI that
11961     // lives in OtherBB.
11962     for (;; --BBI) {
11963       // Check to see if we find the matching store.
11964       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11965         if (OtherStore->getOperand(1) != SI.getOperand(1) ||
11966             OtherStore->getAlignment() != SI.getAlignment())
11967           return false;
11968         break;
11969       }
11970       // If we find something that may be using or overwriting the stored
11971       // value, or if we run out of instructions, we can't do the xform.
11972       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11973           BBI == OtherBB->begin())
11974         return false;
11975     }
11976     
11977     // In order to eliminate the store in OtherBr, we have to
11978     // make sure nothing reads or overwrites the stored value in
11979     // StoreBB.
11980     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11981       // FIXME: This should really be AA driven.
11982       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11983         return false;
11984     }
11985   }
11986   
11987   // Insert a PHI node now if we need it.
11988   Value *MergedVal = OtherStore->getOperand(0);
11989   if (MergedVal != SI.getOperand(0)) {
11990     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11991     PN->reserveOperandSpace(2);
11992     PN->addIncoming(SI.getOperand(0), SI.getParent());
11993     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11994     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11995   }
11996   
11997   // Advance to a place where it is safe to insert the new store and
11998   // insert it.
11999   BBI = DestBB->getFirstNonPHI();
12000   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12001                                     OtherStore->isVolatile(),
12002                                     SI.getAlignment()), *BBI);
12003   
12004   // Nuke the old stores.
12005   EraseInstFromFunction(SI);
12006   EraseInstFromFunction(*OtherStore);
12007   ++NumCombined;
12008   return true;
12009 }
12010
12011
12012 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12013   // Change br (not X), label True, label False to: br X, label False, True
12014   Value *X = 0;
12015   BasicBlock *TrueDest;
12016   BasicBlock *FalseDest;
12017   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
12018       !isa<Constant>(X)) {
12019     // Swap Destinations and condition...
12020     BI.setCondition(X);
12021     BI.setSuccessor(0, FalseDest);
12022     BI.setSuccessor(1, TrueDest);
12023     return &BI;
12024   }
12025
12026   // Cannonicalize fcmp_one -> fcmp_oeq
12027   FCmpInst::Predicate FPred; Value *Y;
12028   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12029                              TrueDest, FalseDest)) &&
12030       BI.getCondition()->hasOneUse())
12031     if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12032         FPred == FCmpInst::FCMP_OGE) {
12033       FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12034       Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12035       
12036       // Swap Destinations and condition.
12037       BI.setSuccessor(0, FalseDest);
12038       BI.setSuccessor(1, TrueDest);
12039       Worklist.Add(Cond);
12040       return &BI;
12041     }
12042
12043   // Cannonicalize icmp_ne -> icmp_eq
12044   ICmpInst::Predicate IPred;
12045   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12046                       TrueDest, FalseDest)) &&
12047       BI.getCondition()->hasOneUse())
12048     if (IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12049         IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12050         IPred == ICmpInst::ICMP_SGE) {
12051       ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12052       Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12053       // Swap Destinations and condition.
12054       BI.setSuccessor(0, FalseDest);
12055       BI.setSuccessor(1, TrueDest);
12056       Worklist.Add(Cond);
12057       return &BI;
12058     }
12059
12060   return 0;
12061 }
12062
12063 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12064   Value *Cond = SI.getCondition();
12065   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12066     if (I->getOpcode() == Instruction::Add)
12067       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12068         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12069         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12070           SI.setOperand(i,
12071                    ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
12072                                                 AddRHS));
12073         SI.setOperand(0, I->getOperand(0));
12074         Worklist.Add(I);
12075         return &SI;
12076       }
12077   }
12078   return 0;
12079 }
12080
12081 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12082   Value *Agg = EV.getAggregateOperand();
12083
12084   if (!EV.hasIndices())
12085     return ReplaceInstUsesWith(EV, Agg);
12086
12087   if (Constant *C = dyn_cast<Constant>(Agg)) {
12088     if (isa<UndefValue>(C))
12089       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12090       
12091     if (isa<ConstantAggregateZero>(C))
12092       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12093
12094     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12095       // Extract the element indexed by the first index out of the constant
12096       Value *V = C->getOperand(*EV.idx_begin());
12097       if (EV.getNumIndices() > 1)
12098         // Extract the remaining indices out of the constant indexed by the
12099         // first index
12100         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12101       else
12102         return ReplaceInstUsesWith(EV, V);
12103     }
12104     return 0; // Can't handle other constants
12105   } 
12106   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12107     // We're extracting from an insertvalue instruction, compare the indices
12108     const unsigned *exti, *exte, *insi, *inse;
12109     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12110          exte = EV.idx_end(), inse = IV->idx_end();
12111          exti != exte && insi != inse;
12112          ++exti, ++insi) {
12113       if (*insi != *exti)
12114         // The insert and extract both reference distinctly different elements.
12115         // This means the extract is not influenced by the insert, and we can
12116         // replace the aggregate operand of the extract with the aggregate
12117         // operand of the insert. i.e., replace
12118         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12119         // %E = extractvalue { i32, { i32 } } %I, 0
12120         // with
12121         // %E = extractvalue { i32, { i32 } } %A, 0
12122         return ExtractValueInst::Create(IV->getAggregateOperand(),
12123                                         EV.idx_begin(), EV.idx_end());
12124     }
12125     if (exti == exte && insi == inse)
12126       // Both iterators are at the end: Index lists are identical. Replace
12127       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12128       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12129       // with "i32 42"
12130       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12131     if (exti == exte) {
12132       // The extract list is a prefix of the insert list. i.e. replace
12133       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12134       // %E = extractvalue { i32, { i32 } } %I, 1
12135       // with
12136       // %X = extractvalue { i32, { i32 } } %A, 1
12137       // %E = insertvalue { i32 } %X, i32 42, 0
12138       // by switching the order of the insert and extract (though the
12139       // insertvalue should be left in, since it may have other uses).
12140       Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12141                                                  EV.idx_begin(), EV.idx_end());
12142       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12143                                      insi, inse);
12144     }
12145     if (insi == inse)
12146       // The insert list is a prefix of the extract list
12147       // We can simply remove the common indices from the extract and make it
12148       // operate on the inserted value instead of the insertvalue result.
12149       // i.e., replace
12150       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12151       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12152       // with
12153       // %E extractvalue { i32 } { i32 42 }, 0
12154       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12155                                       exti, exte);
12156   }
12157   // Can't simplify extracts from other values. Note that nested extracts are
12158   // already simplified implicitely by the above (extract ( extract (insert) )
12159   // will be translated into extract ( insert ( extract ) ) first and then just
12160   // the value inserted, if appropriate).
12161   return 0;
12162 }
12163
12164 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12165 /// is to leave as a vector operation.
12166 static bool CheapToScalarize(Value *V, bool isConstant) {
12167   if (isa<ConstantAggregateZero>(V)) 
12168     return true;
12169   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12170     if (isConstant) return true;
12171     // If all elts are the same, we can extract.
12172     Constant *Op0 = C->getOperand(0);
12173     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12174       if (C->getOperand(i) != Op0)
12175         return false;
12176     return true;
12177   }
12178   Instruction *I = dyn_cast<Instruction>(V);
12179   if (!I) return false;
12180   
12181   // Insert element gets simplified to the inserted element or is deleted if
12182   // this is constant idx extract element and its a constant idx insertelt.
12183   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12184       isa<ConstantInt>(I->getOperand(2)))
12185     return true;
12186   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12187     return true;
12188   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12189     if (BO->hasOneUse() &&
12190         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12191          CheapToScalarize(BO->getOperand(1), isConstant)))
12192       return true;
12193   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12194     if (CI->hasOneUse() &&
12195         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12196          CheapToScalarize(CI->getOperand(1), isConstant)))
12197       return true;
12198   
12199   return false;
12200 }
12201
12202 /// Read and decode a shufflevector mask.
12203 ///
12204 /// It turns undef elements into values that are larger than the number of
12205 /// elements in the input.
12206 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12207   unsigned NElts = SVI->getType()->getNumElements();
12208   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12209     return std::vector<unsigned>(NElts, 0);
12210   if (isa<UndefValue>(SVI->getOperand(2)))
12211     return std::vector<unsigned>(NElts, 2*NElts);
12212
12213   std::vector<unsigned> Result;
12214   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12215   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12216     if (isa<UndefValue>(*i))
12217       Result.push_back(NElts*2);  // undef -> 8
12218     else
12219       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12220   return Result;
12221 }
12222
12223 /// FindScalarElement - Given a vector and an element number, see if the scalar
12224 /// value is already around as a register, for example if it were inserted then
12225 /// extracted from the vector.
12226 static Value *FindScalarElement(Value *V, unsigned EltNo,
12227                                 LLVMContext *Context) {
12228   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12229   const VectorType *PTy = cast<VectorType>(V->getType());
12230   unsigned Width = PTy->getNumElements();
12231   if (EltNo >= Width)  // Out of range access.
12232     return UndefValue::get(PTy->getElementType());
12233   
12234   if (isa<UndefValue>(V))
12235     return UndefValue::get(PTy->getElementType());
12236   else if (isa<ConstantAggregateZero>(V))
12237     return Constant::getNullValue(PTy->getElementType());
12238   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12239     return CP->getOperand(EltNo);
12240   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12241     // If this is an insert to a variable element, we don't know what it is.
12242     if (!isa<ConstantInt>(III->getOperand(2))) 
12243       return 0;
12244     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12245     
12246     // If this is an insert to the element we are looking for, return the
12247     // inserted value.
12248     if (EltNo == IIElt) 
12249       return III->getOperand(1);
12250     
12251     // Otherwise, the insertelement doesn't modify the value, recurse on its
12252     // vector input.
12253     return FindScalarElement(III->getOperand(0), EltNo, Context);
12254   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12255     unsigned LHSWidth =
12256       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12257     unsigned InEl = getShuffleMask(SVI)[EltNo];
12258     if (InEl < LHSWidth)
12259       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12260     else if (InEl < LHSWidth*2)
12261       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12262     else
12263       return UndefValue::get(PTy->getElementType());
12264   }
12265   
12266   // Otherwise, we don't know.
12267   return 0;
12268 }
12269
12270 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12271   // If vector val is undef, replace extract with scalar undef.
12272   if (isa<UndefValue>(EI.getOperand(0)))
12273     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12274
12275   // If vector val is constant 0, replace extract with scalar 0.
12276   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12277     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12278   
12279   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12280     // If vector val is constant with all elements the same, replace EI with
12281     // that element. When the elements are not identical, we cannot replace yet
12282     // (we do that below, but only when the index is constant).
12283     Constant *op0 = C->getOperand(0);
12284     for (unsigned i = 1; i != C->getNumOperands(); ++i)
12285       if (C->getOperand(i) != op0) {
12286         op0 = 0; 
12287         break;
12288       }
12289     if (op0)
12290       return ReplaceInstUsesWith(EI, op0);
12291   }
12292   
12293   // If extracting a specified index from the vector, see if we can recursively
12294   // find a previously computed scalar that was inserted into the vector.
12295   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12296     unsigned IndexVal = IdxC->getZExtValue();
12297     unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
12298       
12299     // If this is extracting an invalid index, turn this into undef, to avoid
12300     // crashing the code below.
12301     if (IndexVal >= VectorWidth)
12302       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12303     
12304     // This instruction only demands the single element from the input vector.
12305     // If the input vector has a single use, simplify it based on this use
12306     // property.
12307     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12308       APInt UndefElts(VectorWidth, 0);
12309       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12310       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12311                                                 DemandedMask, UndefElts)) {
12312         EI.setOperand(0, V);
12313         return &EI;
12314       }
12315     }
12316     
12317     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12318       return ReplaceInstUsesWith(EI, Elt);
12319     
12320     // If the this extractelement is directly using a bitcast from a vector of
12321     // the same number of elements, see if we can find the source element from
12322     // it.  In this case, we will end up needing to bitcast the scalars.
12323     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12324       if (const VectorType *VT = 
12325               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12326         if (VT->getNumElements() == VectorWidth)
12327           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12328                                              IndexVal, Context))
12329             return new BitCastInst(Elt, EI.getType());
12330     }
12331   }
12332   
12333   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12334     // Push extractelement into predecessor operation if legal and
12335     // profitable to do so
12336     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12337       if (I->hasOneUse() &&
12338           CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12339         Value *newEI0 =
12340           Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12341                                         EI.getName()+".lhs");
12342         Value *newEI1 =
12343           Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12344                                         EI.getName()+".rhs");
12345         return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12346       }
12347     } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12348       // Extracting the inserted element?
12349       if (IE->getOperand(2) == EI.getOperand(1))
12350         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12351       // If the inserted and extracted elements are constants, they must not
12352       // be the same value, extract from the pre-inserted value instead.
12353       if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
12354         Worklist.AddValue(EI.getOperand(0));
12355         EI.setOperand(0, IE->getOperand(0));
12356         return &EI;
12357       }
12358     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12359       // If this is extracting an element from a shufflevector, figure out where
12360       // it came from and extract from the appropriate input element instead.
12361       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12362         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12363         Value *Src;
12364         unsigned LHSWidth =
12365           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12366
12367         if (SrcIdx < LHSWidth)
12368           Src = SVI->getOperand(0);
12369         else if (SrcIdx < LHSWidth*2) {
12370           SrcIdx -= LHSWidth;
12371           Src = SVI->getOperand(1);
12372         } else {
12373           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12374         }
12375         return ExtractElementInst::Create(Src,
12376                          ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12377                                           false));
12378       }
12379     }
12380     // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12381   }
12382   return 0;
12383 }
12384
12385 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12386 /// elements from either LHS or RHS, return the shuffle mask and true. 
12387 /// Otherwise, return false.
12388 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12389                                          std::vector<Constant*> &Mask,
12390                                          LLVMContext *Context) {
12391   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12392          "Invalid CollectSingleShuffleElements");
12393   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12394
12395   if (isa<UndefValue>(V)) {
12396     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12397     return true;
12398   } else if (V == LHS) {
12399     for (unsigned i = 0; i != NumElts; ++i)
12400       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12401     return true;
12402   } else if (V == RHS) {
12403     for (unsigned i = 0; i != NumElts; ++i)
12404       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
12405     return true;
12406   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12407     // If this is an insert of an extract from some other vector, include it.
12408     Value *VecOp    = IEI->getOperand(0);
12409     Value *ScalarOp = IEI->getOperand(1);
12410     Value *IdxOp    = IEI->getOperand(2);
12411     
12412     if (!isa<ConstantInt>(IdxOp))
12413       return false;
12414     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12415     
12416     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12417       // Okay, we can handle this if the vector we are insertinting into is
12418       // transitively ok.
12419       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12420         // If so, update the mask to reflect the inserted undef.
12421         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
12422         return true;
12423       }      
12424     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12425       if (isa<ConstantInt>(EI->getOperand(1)) &&
12426           EI->getOperand(0)->getType() == V->getType()) {
12427         unsigned ExtractedIdx =
12428           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12429         
12430         // This must be extracting from either LHS or RHS.
12431         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12432           // Okay, we can handle this if the vector we are insertinting into is
12433           // transitively ok.
12434           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12435             // If so, update the mask to reflect the inserted value.
12436             if (EI->getOperand(0) == LHS) {
12437               Mask[InsertedIdx % NumElts] = 
12438                  ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12439             } else {
12440               assert(EI->getOperand(0) == RHS);
12441               Mask[InsertedIdx % NumElts] = 
12442                 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
12443               
12444             }
12445             return true;
12446           }
12447         }
12448       }
12449     }
12450   }
12451   // TODO: Handle shufflevector here!
12452   
12453   return false;
12454 }
12455
12456 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12457 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12458 /// that computes V and the LHS value of the shuffle.
12459 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12460                                      Value *&RHS, LLVMContext *Context) {
12461   assert(isa<VectorType>(V->getType()) && 
12462          (RHS == 0 || V->getType() == RHS->getType()) &&
12463          "Invalid shuffle!");
12464   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12465
12466   if (isa<UndefValue>(V)) {
12467     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12468     return V;
12469   } else if (isa<ConstantAggregateZero>(V)) {
12470     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
12471     return V;
12472   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12473     // If this is an insert of an extract from some other vector, include it.
12474     Value *VecOp    = IEI->getOperand(0);
12475     Value *ScalarOp = IEI->getOperand(1);
12476     Value *IdxOp    = IEI->getOperand(2);
12477     
12478     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12479       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12480           EI->getOperand(0)->getType() == V->getType()) {
12481         unsigned ExtractedIdx =
12482           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12483         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12484         
12485         // Either the extracted from or inserted into vector must be RHSVec,
12486         // otherwise we'd end up with a shuffle of three inputs.
12487         if (EI->getOperand(0) == RHS || RHS == 0) {
12488           RHS = EI->getOperand(0);
12489           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12490           Mask[InsertedIdx % NumElts] = 
12491             ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
12492           return V;
12493         }
12494         
12495         if (VecOp == RHS) {
12496           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12497                                             RHS, Context);
12498           // Everything but the extracted element is replaced with the RHS.
12499           for (unsigned i = 0; i != NumElts; ++i) {
12500             if (i != InsertedIdx)
12501               Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
12502           }
12503           return V;
12504         }
12505         
12506         // If this insertelement is a chain that comes from exactly these two
12507         // vectors, return the vector and the effective shuffle.
12508         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12509                                          Context))
12510           return EI->getOperand(0);
12511         
12512       }
12513     }
12514   }
12515   // TODO: Handle shufflevector here!
12516   
12517   // Otherwise, can't do anything fancy.  Return an identity vector.
12518   for (unsigned i = 0; i != NumElts; ++i)
12519     Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12520   return V;
12521 }
12522
12523 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12524   Value *VecOp    = IE.getOperand(0);
12525   Value *ScalarOp = IE.getOperand(1);
12526   Value *IdxOp    = IE.getOperand(2);
12527   
12528   // Inserting an undef or into an undefined place, remove this.
12529   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12530     ReplaceInstUsesWith(IE, VecOp);
12531   
12532   // If the inserted element was extracted from some other vector, and if the 
12533   // indexes are constant, try to turn this into a shufflevector operation.
12534   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12535     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12536         EI->getOperand(0)->getType() == IE.getType()) {
12537       unsigned NumVectorElts = IE.getType()->getNumElements();
12538       unsigned ExtractedIdx =
12539         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12540       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12541       
12542       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12543         return ReplaceInstUsesWith(IE, VecOp);
12544       
12545       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12546         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12547       
12548       // If we are extracting a value from a vector, then inserting it right
12549       // back into the same place, just use the input vector.
12550       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12551         return ReplaceInstUsesWith(IE, VecOp);      
12552       
12553       // If this insertelement isn't used by some other insertelement, turn it
12554       // (and any insertelements it points to), into one big shuffle.
12555       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12556         std::vector<Constant*> Mask;
12557         Value *RHS = 0;
12558         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12559         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12560         // We now have a shuffle of LHS, RHS, Mask.
12561         return new ShuffleVectorInst(LHS, RHS,
12562                                      ConstantVector::get(Mask));
12563       }
12564     }
12565   }
12566
12567   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12568   APInt UndefElts(VWidth, 0);
12569   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12570   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12571     return &IE;
12572
12573   return 0;
12574 }
12575
12576
12577 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12578   Value *LHS = SVI.getOperand(0);
12579   Value *RHS = SVI.getOperand(1);
12580   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12581
12582   bool MadeChange = false;
12583
12584   // Undefined shuffle mask -> undefined value.
12585   if (isa<UndefValue>(SVI.getOperand(2)))
12586     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12587
12588   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12589
12590   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12591     return 0;
12592
12593   APInt UndefElts(VWidth, 0);
12594   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12595   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12596     LHS = SVI.getOperand(0);
12597     RHS = SVI.getOperand(1);
12598     MadeChange = true;
12599   }
12600   
12601   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12602   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12603   if (LHS == RHS || isa<UndefValue>(LHS)) {
12604     if (isa<UndefValue>(LHS) && LHS == RHS) {
12605       // shuffle(undef,undef,mask) -> undef.
12606       return ReplaceInstUsesWith(SVI, LHS);
12607     }
12608     
12609     // Remap any references to RHS to use LHS.
12610     std::vector<Constant*> Elts;
12611     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12612       if (Mask[i] >= 2*e)
12613         Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12614       else {
12615         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12616             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12617           Mask[i] = 2*e;     // Turn into undef.
12618           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12619         } else {
12620           Mask[i] = Mask[i] % e;  // Force to LHS.
12621           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
12622         }
12623       }
12624     }
12625     SVI.setOperand(0, SVI.getOperand(1));
12626     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12627     SVI.setOperand(2, ConstantVector::get(Elts));
12628     LHS = SVI.getOperand(0);
12629     RHS = SVI.getOperand(1);
12630     MadeChange = true;
12631   }
12632   
12633   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12634   bool isLHSID = true, isRHSID = true;
12635     
12636   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12637     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12638     // Is this an identity shuffle of the LHS value?
12639     isLHSID &= (Mask[i] == i);
12640       
12641     // Is this an identity shuffle of the RHS value?
12642     isRHSID &= (Mask[i]-e == i);
12643   }
12644
12645   // Eliminate identity shuffles.
12646   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12647   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12648   
12649   // If the LHS is a shufflevector itself, see if we can combine it with this
12650   // one without producing an unusual shuffle.  Here we are really conservative:
12651   // we are absolutely afraid of producing a shuffle mask not in the input
12652   // program, because the code gen may not be smart enough to turn a merged
12653   // shuffle into two specific shuffles: it may produce worse code.  As such,
12654   // we only merge two shuffles if the result is one of the two input shuffle
12655   // masks.  In this case, merging the shuffles just removes one instruction,
12656   // which we know is safe.  This is good for things like turning:
12657   // (splat(splat)) -> splat.
12658   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12659     if (isa<UndefValue>(RHS)) {
12660       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12661
12662       std::vector<unsigned> NewMask;
12663       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12664         if (Mask[i] >= 2*e)
12665           NewMask.push_back(2*e);
12666         else
12667           NewMask.push_back(LHSMask[Mask[i]]);
12668       
12669       // If the result mask is equal to the src shuffle or this shuffle mask, do
12670       // the replacement.
12671       if (NewMask == LHSMask || NewMask == Mask) {
12672         unsigned LHSInNElts =
12673           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12674         std::vector<Constant*> Elts;
12675         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12676           if (NewMask[i] >= LHSInNElts*2) {
12677             Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12678           } else {
12679             Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
12680           }
12681         }
12682         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12683                                      LHSSVI->getOperand(1),
12684                                      ConstantVector::get(Elts));
12685       }
12686     }
12687   }
12688
12689   return MadeChange ? &SVI : 0;
12690 }
12691
12692
12693
12694
12695 /// TryToSinkInstruction - Try to move the specified instruction from its
12696 /// current block into the beginning of DestBlock, which can only happen if it's
12697 /// safe to move the instruction past all of the instructions between it and the
12698 /// end of its block.
12699 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12700   assert(I->hasOneUse() && "Invariants didn't hold!");
12701
12702   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12703   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12704     return false;
12705
12706   // Do not sink alloca instructions out of the entry block.
12707   if (isa<AllocaInst>(I) && I->getParent() ==
12708         &DestBlock->getParent()->getEntryBlock())
12709     return false;
12710
12711   // We can only sink load instructions if there is nothing between the load and
12712   // the end of block that could change the value.
12713   if (I->mayReadFromMemory()) {
12714     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12715          Scan != E; ++Scan)
12716       if (Scan->mayWriteToMemory())
12717         return false;
12718   }
12719
12720   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12721
12722   CopyPrecedingStopPoint(I, InsertPos);
12723   I->moveBefore(InsertPos);
12724   ++NumSunkInst;
12725   return true;
12726 }
12727
12728
12729 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12730 /// all reachable code to the worklist.
12731 ///
12732 /// This has a couple of tricks to make the code faster and more powerful.  In
12733 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12734 /// them to the worklist (this significantly speeds up instcombine on code where
12735 /// many instructions are dead or constant).  Additionally, if we find a branch
12736 /// whose condition is a known constant, we only visit the reachable successors.
12737 ///
12738 static bool AddReachableCodeToWorklist(BasicBlock *BB, 
12739                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12740                                        InstCombiner &IC,
12741                                        const TargetData *TD) {
12742   bool MadeIRChange = false;
12743   SmallVector<BasicBlock*, 256> Worklist;
12744   Worklist.push_back(BB);
12745   
12746   std::vector<Instruction*> InstrsForInstCombineWorklist;
12747   InstrsForInstCombineWorklist.reserve(128);
12748
12749   SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
12750   
12751   while (!Worklist.empty()) {
12752     BB = Worklist.back();
12753     Worklist.pop_back();
12754     
12755     // We have now visited this block!  If we've already been here, ignore it.
12756     if (!Visited.insert(BB)) continue;
12757
12758     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12759       Instruction *Inst = BBI++;
12760       
12761       // DCE instruction if trivially dead.
12762       if (isInstructionTriviallyDead(Inst)) {
12763         ++NumDeadInst;
12764         DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
12765         Inst->eraseFromParent();
12766         continue;
12767       }
12768       
12769       // ConstantProp instruction if trivially constant.
12770       if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
12771         if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12772           DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12773                        << *Inst << '\n');
12774           Inst->replaceAllUsesWith(C);
12775           ++NumConstProp;
12776           Inst->eraseFromParent();
12777           continue;
12778         }
12779       
12780       
12781       
12782       if (TD) {
12783         // See if we can constant fold its operands.
12784         for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
12785              i != e; ++i) {
12786           ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
12787           if (CE == 0) continue;
12788           
12789           // If we already folded this constant, don't try again.
12790           if (!FoldedConstants.insert(CE))
12791             continue;
12792           
12793           Constant *NewC =
12794             ConstantFoldConstantExpression(CE, BB->getContext(), TD);
12795           if (NewC && NewC != CE) {
12796             *i = NewC;
12797             MadeIRChange = true;
12798           }
12799         }
12800       }
12801       
12802
12803       InstrsForInstCombineWorklist.push_back(Inst);
12804     }
12805
12806     // Recursively visit successors.  If this is a branch or switch on a
12807     // constant, only visit the reachable successor.
12808     TerminatorInst *TI = BB->getTerminator();
12809     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12810       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12811         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12812         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12813         Worklist.push_back(ReachableBB);
12814         continue;
12815       }
12816     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12817       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12818         // See if this is an explicit destination.
12819         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12820           if (SI->getCaseValue(i) == Cond) {
12821             BasicBlock *ReachableBB = SI->getSuccessor(i);
12822             Worklist.push_back(ReachableBB);
12823             continue;
12824           }
12825         
12826         // Otherwise it is the default destination.
12827         Worklist.push_back(SI->getSuccessor(0));
12828         continue;
12829       }
12830     }
12831     
12832     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12833       Worklist.push_back(TI->getSuccessor(i));
12834   }
12835   
12836   // Once we've found all of the instructions to add to instcombine's worklist,
12837   // add them in reverse order.  This way instcombine will visit from the top
12838   // of the function down.  This jives well with the way that it adds all uses
12839   // of instructions to the worklist after doing a transformation, thus avoiding
12840   // some N^2 behavior in pathological cases.
12841   IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
12842                               InstrsForInstCombineWorklist.size());
12843   
12844   return MadeIRChange;
12845 }
12846
12847 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12848   MadeIRChange = false;
12849   
12850   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12851         << F.getNameStr() << "\n");
12852
12853   {
12854     // Do a depth-first traversal of the function, populate the worklist with
12855     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12856     // track of which blocks we visit.
12857     SmallPtrSet<BasicBlock*, 64> Visited;
12858     MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12859
12860     // Do a quick scan over the function.  If we find any blocks that are
12861     // unreachable, remove any instructions inside of them.  This prevents
12862     // the instcombine code from having to deal with some bad special cases.
12863     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12864       if (!Visited.count(BB)) {
12865         Instruction *Term = BB->getTerminator();
12866         while (Term != BB->begin()) {   // Remove instrs bottom-up
12867           BasicBlock::iterator I = Term; --I;
12868
12869           DEBUG(errs() << "IC: DCE: " << *I << '\n');
12870           // A debug intrinsic shouldn't force another iteration if we weren't
12871           // going to do one without it.
12872           if (!isa<DbgInfoIntrinsic>(I)) {
12873             ++NumDeadInst;
12874             MadeIRChange = true;
12875           }
12876
12877           // If I is not void type then replaceAllUsesWith undef.
12878           // This allows ValueHandlers and custom metadata to adjust itself.
12879           if (!I->getType()->isVoidTy())
12880             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12881           I->eraseFromParent();
12882         }
12883       }
12884   }
12885
12886   while (!Worklist.isEmpty()) {
12887     Instruction *I = Worklist.RemoveOne();
12888     if (I == 0) continue;  // skip null values.
12889
12890     // Check to see if we can DCE the instruction.
12891     if (isInstructionTriviallyDead(I)) {
12892       DEBUG(errs() << "IC: DCE: " << *I << '\n');
12893       EraseInstFromFunction(*I);
12894       ++NumDeadInst;
12895       MadeIRChange = true;
12896       continue;
12897     }
12898
12899     // Instruction isn't dead, see if we can constant propagate it.
12900     if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
12901       if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12902         DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
12903
12904         // Add operands to the worklist.
12905         ReplaceInstUsesWith(*I, C);
12906         ++NumConstProp;
12907         EraseInstFromFunction(*I);
12908         MadeIRChange = true;
12909         continue;
12910       }
12911
12912     // See if we can trivially sink this instruction to a successor basic block.
12913     if (I->hasOneUse()) {
12914       BasicBlock *BB = I->getParent();
12915       Instruction *UserInst = cast<Instruction>(I->use_back());
12916       BasicBlock *UserParent;
12917       
12918       // Get the block the use occurs in.
12919       if (PHINode *PN = dyn_cast<PHINode>(UserInst))
12920         UserParent = PN->getIncomingBlock(I->use_begin().getUse());
12921       else
12922         UserParent = UserInst->getParent();
12923       
12924       if (UserParent != BB) {
12925         bool UserIsSuccessor = false;
12926         // See if the user is one of our successors.
12927         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12928           if (*SI == UserParent) {
12929             UserIsSuccessor = true;
12930             break;
12931           }
12932
12933         // If the user is one of our immediate successors, and if that successor
12934         // only has us as a predecessors (we'd have to split the critical edge
12935         // otherwise), we can keep going.
12936         if (UserIsSuccessor && UserParent->getSinglePredecessor())
12937           // Okay, the CFG is simple enough, try to sink this instruction.
12938           MadeIRChange |= TryToSinkInstruction(I, UserParent);
12939       }
12940     }
12941
12942     // Now that we have an instruction, try combining it to simplify it.
12943     Builder->SetInsertPoint(I->getParent(), I);
12944     
12945 #ifndef NDEBUG
12946     std::string OrigI;
12947 #endif
12948     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
12949     DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
12950
12951     if (Instruction *Result = visit(*I)) {
12952       ++NumCombined;
12953       // Should we replace the old instruction with a new one?
12954       if (Result != I) {
12955         DEBUG(errs() << "IC: Old = " << *I << '\n'
12956                      << "    New = " << *Result << '\n');
12957
12958         // Everything uses the new instruction now.
12959         I->replaceAllUsesWith(Result);
12960
12961         // Push the new instruction and any users onto the worklist.
12962         Worklist.Add(Result);
12963         Worklist.AddUsersToWorkList(*Result);
12964
12965         // Move the name to the new instruction first.
12966         Result->takeName(I);
12967
12968         // Insert the new instruction into the basic block...
12969         BasicBlock *InstParent = I->getParent();
12970         BasicBlock::iterator InsertPos = I;
12971
12972         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12973           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12974             ++InsertPos;
12975
12976         InstParent->getInstList().insert(InsertPos, Result);
12977
12978         EraseInstFromFunction(*I);
12979       } else {
12980 #ifndef NDEBUG
12981         DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12982                      << "    New = " << *I << '\n');
12983 #endif
12984
12985         // If the instruction was modified, it's possible that it is now dead.
12986         // if so, remove it.
12987         if (isInstructionTriviallyDead(I)) {
12988           EraseInstFromFunction(*I);
12989         } else {
12990           Worklist.Add(I);
12991           Worklist.AddUsersToWorkList(*I);
12992         }
12993       }
12994       MadeIRChange = true;
12995     }
12996   }
12997
12998   Worklist.Zap();
12999   return MadeIRChange;
13000 }
13001
13002
13003 bool InstCombiner::runOnFunction(Function &F) {
13004   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13005   Context = &F.getContext();
13006   TD = getAnalysisIfAvailable<TargetData>();
13007
13008   
13009   /// Builder - This is an IRBuilder that automatically inserts new
13010   /// instructions into the worklist when they are created.
13011   IRBuilder<true, TargetFolder, InstCombineIRInserter> 
13012     TheBuilder(F.getContext(), TargetFolder(TD, F.getContext()),
13013                InstCombineIRInserter(Worklist));
13014   Builder = &TheBuilder;
13015   
13016   bool EverMadeChange = false;
13017
13018   // Iterate while there is work to do.
13019   unsigned Iteration = 0;
13020   while (DoOneIteration(F, Iteration++))
13021     EverMadeChange = true;
13022   
13023   Builder = 0;
13024   return EverMadeChange;
13025 }
13026
13027 FunctionPass *llvm::createInstructionCombiningPass() {
13028   return new InstCombiner();
13029 }