fix some cases where instcombine would change hte IR but not return true
[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/ValueTracking.h"
46 #include "llvm/Target/TargetData.h"
47 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
48 #include "llvm/Transforms/Utils/Local.h"
49 #include "llvm/Support/CallSite.h"
50 #include "llvm/Support/ConstantRange.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/GetElementPtrTypeIterator.h"
54 #include "llvm/Support/InstVisitor.h"
55 #include "llvm/Support/IRBuilder.h"
56 #include "llvm/Support/MathExtras.h"
57 #include "llvm/Support/PatternMatch.h"
58 #include "llvm/Support/Compiler.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include "llvm/ADT/DenseMap.h"
61 #include "llvm/ADT/SmallVector.h"
62 #include "llvm/ADT/SmallPtrSet.h"
63 #include "llvm/ADT/Statistic.h"
64 #include "llvm/ADT/STLExtras.h"
65 #include <algorithm>
66 #include <climits>
67 using namespace llvm;
68 using namespace llvm::PatternMatch;
69
70 STATISTIC(NumCombined , "Number of insts combined");
71 STATISTIC(NumConstProp, "Number of constant folds");
72 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
73 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
74 STATISTIC(NumSunkInst , "Number of instructions sunk");
75
76 namespace {
77   /// InstCombineWorklist - This is the worklist management logic for
78   /// InstCombine.
79   class InstCombineWorklist {
80     SmallVector<Instruction*, 256> Worklist;
81     DenseMap<Instruction*, unsigned> WorklistMap;
82     
83     void operator=(const InstCombineWorklist&RHS);   // DO NOT IMPLEMENT
84     InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
85   public:
86     InstCombineWorklist() {}
87     
88     bool isEmpty() const { return Worklist.empty(); }
89     
90     /// Add - Add the specified instruction to the worklist if it isn't already
91     /// in it.
92     void Add(Instruction *I) {
93       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
94         Worklist.push_back(I);
95     }
96     
97     void AddValue(Value *V) {
98       if (Instruction *I = dyn_cast<Instruction>(V))
99         Add(I);
100     }
101     
102     // Remove - remove I from the worklist if it exists.
103     void Remove(Instruction *I) {
104       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
105       if (It == WorklistMap.end()) return; // Not in worklist.
106       
107       // Don't bother moving everything down, just null out the slot.
108       Worklist[It->second] = 0;
109       
110       WorklistMap.erase(It);
111     }
112     
113     Instruction *RemoveOne() {
114       Instruction *I = Worklist.back();
115       Worklist.pop_back();
116       WorklistMap.erase(I);
117       return I;
118     }
119
120     /// AddUsersToWorkList - When an instruction is simplified, add all users of
121     /// the instruction to the work lists because they might get more simplified
122     /// now.
123     ///
124     void AddUsersToWorkList(Instruction &I) {
125       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
126            UI != UE; ++UI)
127         Add(cast<Instruction>(*UI));
128     }
129     
130     
131     /// Zap - check that the worklist is empty and nuke the backing store for
132     /// the map if it is large.
133     void Zap() {
134       assert(WorklistMap.empty() && "Worklist empty, but map not?");
135       
136       // Do an explicit clear, this shrinks the map if needed.
137       WorklistMap.clear();
138     }
139   };
140 } // end anonymous namespace.
141
142
143 namespace {
144   /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
145   /// just like the normal insertion helper, but also adds any new instructions
146   /// to the instcombine worklist.
147   class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
148     InstCombineWorklist &Worklist;
149   public:
150     InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
151     
152     void InsertHelper(Instruction *I, const Twine &Name,
153                       BasicBlock *BB, BasicBlock::iterator InsertPt) const {
154       IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
155       Worklist.Add(I);
156     }
157   };
158 } // end anonymous namespace
159
160
161 namespace {
162   class VISIBILITY_HIDDEN InstCombiner
163     : public FunctionPass,
164       public InstVisitor<InstCombiner, Instruction*> {
165     TargetData *TD;
166     bool MustPreserveLCSSA;
167     bool MadeIRChange;
168   public:
169     /// Worklist - All of the instructions that need to be simplified.
170     InstCombineWorklist Worklist;
171
172     /// Builder - This is an IRBuilder that automatically inserts new
173     /// instructions into the worklist when they are created.
174     typedef IRBuilder<true, ConstantFolder, InstCombineIRInserter> BuilderTy;
175     BuilderTy *Builder;
176         
177     static char ID; // Pass identification, replacement for typeid
178     InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
179
180     LLVMContext *Context;
181     LLVMContext *getContext() const { return Context; }
182
183   public:
184     virtual bool runOnFunction(Function &F);
185     
186     bool DoOneIteration(Function &F, unsigned ItNum);
187
188     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
189       AU.addPreservedID(LCSSAID);
190       AU.setPreservesCFG();
191     }
192
193     TargetData *getTargetData() const { return TD; }
194
195     // Visitation implementation - Implement instruction combining for different
196     // instruction types.  The semantics are as follows:
197     // Return Value:
198     //    null        - No change was made
199     //     I          - Change was made, I is still valid, I may be dead though
200     //   otherwise    - Change was made, replace I with returned instruction
201     //
202     Instruction *visitAdd(BinaryOperator &I);
203     Instruction *visitFAdd(BinaryOperator &I);
204     Instruction *visitSub(BinaryOperator &I);
205     Instruction *visitFSub(BinaryOperator &I);
206     Instruction *visitMul(BinaryOperator &I);
207     Instruction *visitFMul(BinaryOperator &I);
208     Instruction *visitURem(BinaryOperator &I);
209     Instruction *visitSRem(BinaryOperator &I);
210     Instruction *visitFRem(BinaryOperator &I);
211     bool SimplifyDivRemOfSelect(BinaryOperator &I);
212     Instruction *commonRemTransforms(BinaryOperator &I);
213     Instruction *commonIRemTransforms(BinaryOperator &I);
214     Instruction *commonDivTransforms(BinaryOperator &I);
215     Instruction *commonIDivTransforms(BinaryOperator &I);
216     Instruction *visitUDiv(BinaryOperator &I);
217     Instruction *visitSDiv(BinaryOperator &I);
218     Instruction *visitFDiv(BinaryOperator &I);
219     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
220     Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
221     Instruction *visitAnd(BinaryOperator &I);
222     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
223     Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
224     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
225                                      Value *A, Value *B, Value *C);
226     Instruction *visitOr (BinaryOperator &I);
227     Instruction *visitXor(BinaryOperator &I);
228     Instruction *visitShl(BinaryOperator &I);
229     Instruction *visitAShr(BinaryOperator &I);
230     Instruction *visitLShr(BinaryOperator &I);
231     Instruction *commonShiftTransforms(BinaryOperator &I);
232     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
233                                       Constant *RHSC);
234     Instruction *visitFCmpInst(FCmpInst &I);
235     Instruction *visitICmpInst(ICmpInst &I);
236     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
237     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
238                                                 Instruction *LHS,
239                                                 ConstantInt *RHS);
240     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
241                                 ConstantInt *DivRHS);
242
243     Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
244                              ICmpInst::Predicate Cond, Instruction &I);
245     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
246                                      BinaryOperator &I);
247     Instruction *commonCastTransforms(CastInst &CI);
248     Instruction *commonIntCastTransforms(CastInst &CI);
249     Instruction *commonPointerCastTransforms(CastInst &CI);
250     Instruction *visitTrunc(TruncInst &CI);
251     Instruction *visitZExt(ZExtInst &CI);
252     Instruction *visitSExt(SExtInst &CI);
253     Instruction *visitFPTrunc(FPTruncInst &CI);
254     Instruction *visitFPExt(CastInst &CI);
255     Instruction *visitFPToUI(FPToUIInst &FI);
256     Instruction *visitFPToSI(FPToSIInst &FI);
257     Instruction *visitUIToFP(CastInst &CI);
258     Instruction *visitSIToFP(CastInst &CI);
259     Instruction *visitPtrToInt(PtrToIntInst &CI);
260     Instruction *visitIntToPtr(IntToPtrInst &CI);
261     Instruction *visitBitCast(BitCastInst &CI);
262     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
263                                 Instruction *FI);
264     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
265     Instruction *visitSelectInst(SelectInst &SI);
266     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
267     Instruction *visitCallInst(CallInst &CI);
268     Instruction *visitInvokeInst(InvokeInst &II);
269     Instruction *visitPHINode(PHINode &PN);
270     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
271     Instruction *visitAllocationInst(AllocationInst &AI);
272     Instruction *visitFreeInst(FreeInst &FI);
273     Instruction *visitLoadInst(LoadInst &LI);
274     Instruction *visitStoreInst(StoreInst &SI);
275     Instruction *visitBranchInst(BranchInst &BI);
276     Instruction *visitSwitchInst(SwitchInst &SI);
277     Instruction *visitInsertElementInst(InsertElementInst &IE);
278     Instruction *visitExtractElementInst(ExtractElementInst &EI);
279     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
280     Instruction *visitExtractValueInst(ExtractValueInst &EV);
281
282     // visitInstruction - Specify what to return for unhandled instructions...
283     Instruction *visitInstruction(Instruction &I) { return 0; }
284
285   private:
286     Instruction *visitCallSite(CallSite CS);
287     bool transformConstExprCastCall(CallSite CS);
288     Instruction *transformCallThroughTrampoline(CallSite CS);
289     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
290                                    bool DoXform = true);
291     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
292     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
293
294
295   public:
296     // InsertNewInstBefore - insert an instruction New before instruction Old
297     // in the program.  Add the new instruction to the worklist.
298     //
299     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
300       assert(New && New->getParent() == 0 &&
301              "New instruction already inserted into a basic block!");
302       BasicBlock *BB = Old.getParent();
303       BB->getInstList().insert(&Old, New);  // Insert inst
304       Worklist.Add(New);
305       return New;
306     }
307         
308     // ReplaceInstUsesWith - This method is to be used when an instruction is
309     // found to be dead, replacable with another preexisting expression.  Here
310     // we add all uses of I to the worklist, replace all uses of I with the new
311     // value, then return I, so that the inst combiner will know that I was
312     // modified.
313     //
314     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
315       Worklist.AddUsersToWorkList(I);   // Add all modified instrs to worklist.
316       
317       // If we are replacing the instruction with itself, this must be in a
318       // segment of unreachable code, so just clobber the instruction.
319       if (&I == V) 
320         V = UndefValue::get(I.getType());
321         
322       I.replaceAllUsesWith(V);
323       return &I;
324     }
325
326     // EraseInstFromFunction - When dealing with an instruction that has side
327     // effects or produces a void value, we can't rely on DCE to delete the
328     // instruction.  Instead, visit methods should return the value returned by
329     // this function.
330     Instruction *EraseInstFromFunction(Instruction &I) {
331       DEBUG(errs() << "IC: erase " << I);
332
333       assert(I.use_empty() && "Cannot erase instruction that is used!");
334       // Make sure that we reprocess all operands now that we reduced their
335       // use counts.
336       if (I.getNumOperands() < 8) {
337         for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
338           if (Instruction *Op = dyn_cast<Instruction>(*i))
339             Worklist.Add(Op);
340       }
341       Worklist.Remove(&I);
342       I.eraseFromParent();
343       MadeIRChange = true;
344       return 0;  // Don't do anything with FI
345     }
346         
347     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
348                            APInt &KnownOne, unsigned Depth = 0) const {
349       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
350     }
351     
352     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
353                            unsigned Depth = 0) const {
354       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
355     }
356     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
357       return llvm::ComputeNumSignBits(Op, TD, Depth);
358     }
359
360   private:
361
362     /// SimplifyCommutative - This performs a few simplifications for 
363     /// commutative operators.
364     bool SimplifyCommutative(BinaryOperator &I);
365
366     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
367     /// most-complex to least-complex order.
368     bool SimplifyCompare(CmpInst &I);
369
370     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
371     /// based on the demanded bits.
372     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
373                                    APInt& KnownZero, APInt& KnownOne,
374                                    unsigned Depth);
375     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
376                               APInt& KnownZero, APInt& KnownOne,
377                               unsigned Depth=0);
378         
379     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
380     /// SimplifyDemandedBits knows about.  See if the instruction has any
381     /// properties that allow us to simplify its operands.
382     bool SimplifyDemandedInstructionBits(Instruction &Inst);
383         
384     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
385                                       APInt& UndefElts, unsigned Depth = 0);
386       
387     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
388     // PHI node as operand #0, see if we can fold the instruction into the PHI
389     // (which is only possible if all operands to the PHI are constants).
390     Instruction *FoldOpIntoPhi(Instruction &I);
391
392     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
393     // operator and they all are only used by the PHI, PHI together their
394     // inputs, and do the operation once, to the result of the PHI.
395     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
396     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
397     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
398
399     
400     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
401                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
402     
403     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
404                               bool isSub, Instruction &I);
405     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
406                                  bool isSigned, bool Inside, Instruction &IB);
407     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
408     Instruction *MatchBSwap(BinaryOperator &I);
409     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
410     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
411     Instruction *SimplifyMemSet(MemSetInst *MI);
412
413
414     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
415
416     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
417                                     unsigned CastOpc, int &NumCastsRemoved);
418     unsigned GetOrEnforceKnownAlignment(Value *V,
419                                         unsigned PrefAlign = 0);
420
421   };
422 } // end anonymous namespace
423
424 char InstCombiner::ID = 0;
425 static RegisterPass<InstCombiner>
426 X("instcombine", "Combine redundant instructions");
427
428 // getComplexity:  Assign a complexity or rank value to LLVM Values...
429 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
430 static unsigned getComplexity(Value *V) {
431   if (isa<Instruction>(V)) {
432     if (BinaryOperator::isNeg(V) ||
433         BinaryOperator::isFNeg(V) ||
434         BinaryOperator::isNot(V))
435       return 3;
436     return 4;
437   }
438   if (isa<Argument>(V)) return 3;
439   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
440 }
441
442 // isOnlyUse - Return true if this instruction will be deleted if we stop using
443 // it.
444 static bool isOnlyUse(Value *V) {
445   return V->hasOneUse() || isa<Constant>(V);
446 }
447
448 // getPromotedType - Return the specified type promoted as it would be to pass
449 // though a va_arg area...
450 static const Type *getPromotedType(const Type *Ty) {
451   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
452     if (ITy->getBitWidth() < 32)
453       return Type::getInt32Ty(Ty->getContext());
454   }
455   return Ty;
456 }
457
458 /// getBitCastOperand - If the specified operand is a CastInst, a constant
459 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
460 /// operand value, otherwise return null.
461 static Value *getBitCastOperand(Value *V) {
462   if (Operator *O = dyn_cast<Operator>(V)) {
463     if (O->getOpcode() == Instruction::BitCast)
464       return O->getOperand(0);
465     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
466       if (GEP->hasAllZeroIndices())
467         return GEP->getPointerOperand();
468   }
469   return 0;
470 }
471
472 /// This function is a wrapper around CastInst::isEliminableCastPair. It
473 /// simply extracts arguments and returns what that function returns.
474 static Instruction::CastOps 
475 isEliminableCastPair(
476   const CastInst *CI, ///< The first cast instruction
477   unsigned opcode,       ///< The opcode of the second cast instruction
478   const Type *DstTy,     ///< The target type for the second cast instruction
479   TargetData *TD         ///< The target data for pointer size
480 ) {
481
482   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
483   const Type *MidTy = CI->getType();                  // B from above
484
485   // Get the opcodes of the two Cast instructions
486   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
487   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
488
489   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
490                                                 DstTy,
491                                   TD ? TD->getIntPtrType(CI->getContext()) : 0);
492   
493   // We don't want to form an inttoptr or ptrtoint that converts to an integer
494   // type that differs from the pointer size.
495   if ((Res == Instruction::IntToPtr &&
496           (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
497       (Res == Instruction::PtrToInt &&
498           (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
499     Res = 0;
500   
501   return Instruction::CastOps(Res);
502 }
503
504 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
505 /// in any code being generated.  It does not require codegen if V is simple
506 /// enough or if the cast can be folded into other casts.
507 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
508                               const Type *Ty, TargetData *TD) {
509   if (V->getType() == Ty || isa<Constant>(V)) return false;
510   
511   // If this is another cast that can be eliminated, it isn't codegen either.
512   if (const CastInst *CI = dyn_cast<CastInst>(V))
513     if (isEliminableCastPair(CI, opcode, Ty, TD))
514       return false;
515   return true;
516 }
517
518 // SimplifyCommutative - This performs a few simplifications for commutative
519 // operators:
520 //
521 //  1. Order operands such that they are listed from right (least complex) to
522 //     left (most complex).  This puts constants before unary operators before
523 //     binary operators.
524 //
525 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
526 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
527 //
528 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
529   bool Changed = false;
530   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
531     Changed = !I.swapOperands();
532
533   if (!I.isAssociative()) return Changed;
534   Instruction::BinaryOps Opcode = I.getOpcode();
535   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
536     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
537       if (isa<Constant>(I.getOperand(1))) {
538         Constant *Folded = ConstantExpr::get(I.getOpcode(),
539                                              cast<Constant>(I.getOperand(1)),
540                                              cast<Constant>(Op->getOperand(1)));
541         I.setOperand(0, Op->getOperand(0));
542         I.setOperand(1, Folded);
543         return true;
544       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
545         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
546             isOnlyUse(Op) && isOnlyUse(Op1)) {
547           Constant *C1 = cast<Constant>(Op->getOperand(1));
548           Constant *C2 = cast<Constant>(Op1->getOperand(1));
549
550           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
551           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
552           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
553                                                     Op1->getOperand(0),
554                                                     Op1->getName(), &I);
555           Worklist.Add(New);
556           I.setOperand(0, New);
557           I.setOperand(1, Folded);
558           return true;
559         }
560     }
561   return Changed;
562 }
563
564 /// SimplifyCompare - For a CmpInst this function just orders the operands
565 /// so that theyare listed from right (least complex) to left (most complex).
566 /// This puts constants before unary operators before binary operators.
567 bool InstCombiner::SimplifyCompare(CmpInst &I) {
568   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
569     return false;
570   I.swapOperands();
571   // Compare instructions are not associative so there's nothing else we can do.
572   return true;
573 }
574
575 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
576 // if the LHS is a constant zero (which is the 'negate' form).
577 //
578 static inline Value *dyn_castNegVal(Value *V) {
579   if (BinaryOperator::isNeg(V))
580     return BinaryOperator::getNegArgument(V);
581
582   // Constants can be considered to be negated values if they can be folded.
583   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
584     return ConstantExpr::getNeg(C);
585
586   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
587     if (C->getType()->getElementType()->isInteger())
588       return ConstantExpr::getNeg(C);
589
590   return 0;
591 }
592
593 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
594 // instruction if the LHS is a constant negative zero (which is the 'negate'
595 // form).
596 //
597 static inline Value *dyn_castFNegVal(Value *V) {
598   if (BinaryOperator::isFNeg(V))
599     return BinaryOperator::getFNegArgument(V);
600
601   // Constants can be considered to be negated values if they can be folded.
602   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
603     return ConstantExpr::getFNeg(C);
604
605   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
606     if (C->getType()->getElementType()->isFloatingPoint())
607       return ConstantExpr::getFNeg(C);
608
609   return 0;
610 }
611
612 static inline Value *dyn_castNotVal(Value *V) {
613   if (BinaryOperator::isNot(V))
614     return BinaryOperator::getNotArgument(V);
615
616   // Constants can be considered to be not'ed values...
617   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
618     return ConstantInt::get(C->getType(), ~C->getValue());
619   return 0;
620 }
621
622 // dyn_castFoldableMul - If this value is a multiply that can be folded into
623 // other computations (because it has a constant operand), return the
624 // non-constant operand of the multiply, and set CST to point to the multiplier.
625 // Otherwise, return null.
626 //
627 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
628   if (V->hasOneUse() && V->getType()->isInteger())
629     if (Instruction *I = dyn_cast<Instruction>(V)) {
630       if (I->getOpcode() == Instruction::Mul)
631         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
632           return I->getOperand(0);
633       if (I->getOpcode() == Instruction::Shl)
634         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
635           // The multiplier is really 1 << CST.
636           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
637           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
638           CST = ConstantInt::get(V->getType()->getContext(),
639                                  APInt(BitWidth, 1).shl(CSTVal));
640           return I->getOperand(0);
641         }
642     }
643   return 0;
644 }
645
646 /// AddOne - Add one to a ConstantInt
647 static Constant *AddOne(Constant *C) {
648   return ConstantExpr::getAdd(C, 
649     ConstantInt::get(C->getType(), 1));
650 }
651 /// SubOne - Subtract one from a ConstantInt
652 static Constant *SubOne(ConstantInt *C) {
653   return ConstantExpr::getSub(C, 
654     ConstantInt::get(C->getType(), 1));
655 }
656 /// MultiplyOverflows - True if the multiply can not be expressed in an int
657 /// this size.
658 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
659   uint32_t W = C1->getBitWidth();
660   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
661   if (sign) {
662     LHSExt.sext(W * 2);
663     RHSExt.sext(W * 2);
664   } else {
665     LHSExt.zext(W * 2);
666     RHSExt.zext(W * 2);
667   }
668
669   APInt MulExt = LHSExt * RHSExt;
670
671   if (sign) {
672     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
673     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
674     return MulExt.slt(Min) || MulExt.sgt(Max);
675   } else 
676     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
677 }
678
679
680 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
681 /// specified instruction is a constant integer.  If so, check to see if there
682 /// are any bits set in the constant that are not demanded.  If so, shrink the
683 /// constant and return true.
684 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
685                                    APInt Demanded) {
686   assert(I && "No instruction?");
687   assert(OpNo < I->getNumOperands() && "Operand index too large");
688
689   // If the operand is not a constant integer, nothing to do.
690   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
691   if (!OpC) return false;
692
693   // If there are no bits set that aren't demanded, nothing to do.
694   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
695   if ((~Demanded & OpC->getValue()) == 0)
696     return false;
697
698   // This instruction is producing bits that are not demanded. Shrink the RHS.
699   Demanded &= OpC->getValue();
700   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
701   return true;
702 }
703
704 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
705 // set of known zero and one bits, compute the maximum and minimum values that
706 // could have the specified known zero and known one bits, returning them in
707 // min/max.
708 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
709                                                    const APInt& KnownOne,
710                                                    APInt& Min, APInt& Max) {
711   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
712          KnownZero.getBitWidth() == Min.getBitWidth() &&
713          KnownZero.getBitWidth() == Max.getBitWidth() &&
714          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
715   APInt UnknownBits = ~(KnownZero|KnownOne);
716
717   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
718   // bit if it is unknown.
719   Min = KnownOne;
720   Max = KnownOne|UnknownBits;
721   
722   if (UnknownBits.isNegative()) { // Sign bit is unknown
723     Min.set(Min.getBitWidth()-1);
724     Max.clear(Max.getBitWidth()-1);
725   }
726 }
727
728 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
729 // a set of known zero and one bits, compute the maximum and minimum values that
730 // could have the specified known zero and known one bits, returning them in
731 // min/max.
732 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
733                                                      const APInt &KnownOne,
734                                                      APInt &Min, APInt &Max) {
735   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
736          KnownZero.getBitWidth() == Min.getBitWidth() &&
737          KnownZero.getBitWidth() == Max.getBitWidth() &&
738          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
739   APInt UnknownBits = ~(KnownZero|KnownOne);
740   
741   // The minimum value is when the unknown bits are all zeros.
742   Min = KnownOne;
743   // The maximum value is when the unknown bits are all ones.
744   Max = KnownOne|UnknownBits;
745 }
746
747 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
748 /// SimplifyDemandedBits knows about.  See if the instruction has any
749 /// properties that allow us to simplify its operands.
750 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
751   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
752   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
753   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
754   
755   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
756                                      KnownZero, KnownOne, 0);
757   if (V == 0) return false;
758   if (V == &Inst) return true;
759   ReplaceInstUsesWith(Inst, V);
760   return true;
761 }
762
763 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
764 /// specified instruction operand if possible, updating it in place.  It returns
765 /// true if it made any change and false otherwise.
766 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
767                                         APInt &KnownZero, APInt &KnownOne,
768                                         unsigned Depth) {
769   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
770                                           KnownZero, KnownOne, Depth);
771   if (NewVal == 0) return false;
772   U.set(NewVal);
773   return true;
774 }
775
776
777 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
778 /// value based on the demanded bits.  When this function is called, it is known
779 /// that only the bits set in DemandedMask of the result of V are ever used
780 /// downstream. Consequently, depending on the mask and V, it may be possible
781 /// to replace V with a constant or one of its operands. In such cases, this
782 /// function does the replacement and returns true. In all other cases, it
783 /// returns false after analyzing the expression and setting KnownOne and known
784 /// to be one in the expression.  KnownZero contains all the bits that are known
785 /// to be zero in the expression. These are provided to potentially allow the
786 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
787 /// the expression. KnownOne and KnownZero always follow the invariant that 
788 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
789 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
790 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
791 /// and KnownOne must all be the same.
792 ///
793 /// This returns null if it did not change anything and it permits no
794 /// simplification.  This returns V itself if it did some simplification of V's
795 /// operands based on the information about what bits are demanded. This returns
796 /// some other non-null value if it found out that V is equal to another value
797 /// in the context where the specified bits are demanded, but not for all users.
798 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
799                                              APInt &KnownZero, APInt &KnownOne,
800                                              unsigned Depth) {
801   assert(V != 0 && "Null pointer of Value???");
802   assert(Depth <= 6 && "Limit Search Depth");
803   uint32_t BitWidth = DemandedMask.getBitWidth();
804   const Type *VTy = V->getType();
805   assert((TD || !isa<PointerType>(VTy)) &&
806          "SimplifyDemandedBits needs to know bit widths!");
807   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
808          (!VTy->isIntOrIntVector() ||
809           VTy->getScalarSizeInBits() == BitWidth) &&
810          KnownZero.getBitWidth() == BitWidth &&
811          KnownOne.getBitWidth() == BitWidth &&
812          "Value *V, DemandedMask, KnownZero and KnownOne "
813          "must have same BitWidth");
814   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
815     // We know all of the bits for a constant!
816     KnownOne = CI->getValue() & DemandedMask;
817     KnownZero = ~KnownOne & DemandedMask;
818     return 0;
819   }
820   if (isa<ConstantPointerNull>(V)) {
821     // We know all of the bits for a constant!
822     KnownOne.clear();
823     KnownZero = DemandedMask;
824     return 0;
825   }
826
827   KnownZero.clear();
828   KnownOne.clear();
829   if (DemandedMask == 0) {   // Not demanding any bits from V.
830     if (isa<UndefValue>(V))
831       return 0;
832     return UndefValue::get(VTy);
833   }
834   
835   if (Depth == 6)        // Limit search depth.
836     return 0;
837   
838   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
839   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
840
841   Instruction *I = dyn_cast<Instruction>(V);
842   if (!I) {
843     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
844     return 0;        // Only analyze instructions.
845   }
846
847   // If there are multiple uses of this value and we aren't at the root, then
848   // we can't do any simplifications of the operands, because DemandedMask
849   // only reflects the bits demanded by *one* of the users.
850   if (Depth != 0 && !I->hasOneUse()) {
851     // Despite the fact that we can't simplify this instruction in all User's
852     // context, we can at least compute the knownzero/knownone bits, and we can
853     // do simplifications that apply to *just* the one user if we know that
854     // this instruction has a simpler value in that context.
855     if (I->getOpcode() == Instruction::And) {
856       // If either the LHS or the RHS are Zero, the result is zero.
857       ComputeMaskedBits(I->getOperand(1), DemandedMask,
858                         RHSKnownZero, RHSKnownOne, Depth+1);
859       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
860                         LHSKnownZero, LHSKnownOne, Depth+1);
861       
862       // If all of the demanded bits are known 1 on one side, return the other.
863       // These bits cannot contribute to the result of the 'and' in this
864       // context.
865       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
866           (DemandedMask & ~LHSKnownZero))
867         return I->getOperand(0);
868       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
869           (DemandedMask & ~RHSKnownZero))
870         return I->getOperand(1);
871       
872       // If all of the demanded bits in the inputs are known zeros, return zero.
873       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
874         return Constant::getNullValue(VTy);
875       
876     } else if (I->getOpcode() == Instruction::Or) {
877       // We can simplify (X|Y) -> X or Y in the user's context if we know that
878       // only bits from X or Y are demanded.
879       
880       // If either the LHS or the RHS are One, the result is One.
881       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
882                         RHSKnownZero, RHSKnownOne, Depth+1);
883       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
884                         LHSKnownZero, LHSKnownOne, Depth+1);
885       
886       // If all of the demanded bits are known zero on one side, return the
887       // other.  These bits cannot contribute to the result of the 'or' in this
888       // context.
889       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
890           (DemandedMask & ~LHSKnownOne))
891         return I->getOperand(0);
892       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
893           (DemandedMask & ~RHSKnownOne))
894         return I->getOperand(1);
895       
896       // If all of the potentially set bits on one side are known to be set on
897       // the other side, just use the 'other' side.
898       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
899           (DemandedMask & (~RHSKnownZero)))
900         return I->getOperand(0);
901       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
902           (DemandedMask & (~LHSKnownZero)))
903         return I->getOperand(1);
904     }
905     
906     // Compute the KnownZero/KnownOne bits to simplify things downstream.
907     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
908     return 0;
909   }
910   
911   // If this is the root being simplified, allow it to have multiple uses,
912   // just set the DemandedMask to all bits so that we can try to simplify the
913   // operands.  This allows visitTruncInst (for example) to simplify the
914   // operand of a trunc without duplicating all the logic below.
915   if (Depth == 0 && !V->hasOneUse())
916     DemandedMask = APInt::getAllOnesValue(BitWidth);
917   
918   switch (I->getOpcode()) {
919   default:
920     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
921     break;
922   case Instruction::And:
923     // If either the LHS or the RHS are Zero, the result is zero.
924     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
925                              RHSKnownZero, RHSKnownOne, Depth+1) ||
926         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
927                              LHSKnownZero, LHSKnownOne, Depth+1))
928       return I;
929     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
930     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
931
932     // If all of the demanded bits are known 1 on one side, return the other.
933     // These bits cannot contribute to the result of the 'and'.
934     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
935         (DemandedMask & ~LHSKnownZero))
936       return I->getOperand(0);
937     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
938         (DemandedMask & ~RHSKnownZero))
939       return I->getOperand(1);
940     
941     // If all of the demanded bits in the inputs are known zeros, return zero.
942     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
943       return Constant::getNullValue(VTy);
944       
945     // If the RHS is a constant, see if we can simplify it.
946     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
947       return I;
948       
949     // Output known-1 bits are only known if set in both the LHS & RHS.
950     RHSKnownOne &= LHSKnownOne;
951     // Output known-0 are known to be clear if zero in either the LHS | RHS.
952     RHSKnownZero |= LHSKnownZero;
953     break;
954   case Instruction::Or:
955     // If either the LHS or the RHS are One, the result is One.
956     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
957                              RHSKnownZero, RHSKnownOne, Depth+1) ||
958         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
959                              LHSKnownZero, LHSKnownOne, Depth+1))
960       return I;
961     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
962     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
963     
964     // If all of the demanded bits are known zero on one side, return the other.
965     // These bits cannot contribute to the result of the 'or'.
966     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
967         (DemandedMask & ~LHSKnownOne))
968       return I->getOperand(0);
969     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
970         (DemandedMask & ~RHSKnownOne))
971       return I->getOperand(1);
972
973     // If all of the potentially set bits on one side are known to be set on
974     // the other side, just use the 'other' side.
975     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
976         (DemandedMask & (~RHSKnownZero)))
977       return I->getOperand(0);
978     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
979         (DemandedMask & (~LHSKnownZero)))
980       return I->getOperand(1);
981         
982     // If the RHS is a constant, see if we can simplify it.
983     if (ShrinkDemandedConstant(I, 1, DemandedMask))
984       return I;
985           
986     // Output known-0 bits are only known if clear in both the LHS & RHS.
987     RHSKnownZero &= LHSKnownZero;
988     // Output known-1 are known to be set if set in either the LHS | RHS.
989     RHSKnownOne |= LHSKnownOne;
990     break;
991   case Instruction::Xor: {
992     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
993                              RHSKnownZero, RHSKnownOne, Depth+1) ||
994         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
995                              LHSKnownZero, LHSKnownOne, Depth+1))
996       return I;
997     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
998     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
999     
1000     // If all of the demanded bits are known zero on one side, return the other.
1001     // These bits cannot contribute to the result of the 'xor'.
1002     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1003       return I->getOperand(0);
1004     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1005       return I->getOperand(1);
1006     
1007     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1008     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1009                          (RHSKnownOne & LHSKnownOne);
1010     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1011     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1012                         (RHSKnownOne & LHSKnownZero);
1013     
1014     // If all of the demanded bits are known to be zero on one side or the
1015     // other, turn this into an *inclusive* or.
1016     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1017     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1018       Instruction *Or = 
1019         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1020                                  I->getName());
1021       return InsertNewInstBefore(Or, *I);
1022     }
1023     
1024     // If all of the demanded bits on one side are known, and all of the set
1025     // bits on that side are also known to be set on the other side, turn this
1026     // into an AND, as we know the bits will be cleared.
1027     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1028     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1029       // all known
1030       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1031         Constant *AndC = Constant::getIntegerValue(VTy,
1032                                                    ~RHSKnownOne & DemandedMask);
1033         Instruction *And = 
1034           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1035         return InsertNewInstBefore(And, *I);
1036       }
1037     }
1038     
1039     // If the RHS is a constant, see if we can simplify it.
1040     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1041     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1042       return I;
1043     
1044     RHSKnownZero = KnownZeroOut;
1045     RHSKnownOne  = KnownOneOut;
1046     break;
1047   }
1048   case Instruction::Select:
1049     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1050                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1051         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1052                              LHSKnownZero, LHSKnownOne, Depth+1))
1053       return I;
1054     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1055     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1056     
1057     // If the operands are constants, see if we can simplify them.
1058     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1059         ShrinkDemandedConstant(I, 2, DemandedMask))
1060       return I;
1061     
1062     // Only known if known in both the LHS and RHS.
1063     RHSKnownOne &= LHSKnownOne;
1064     RHSKnownZero &= LHSKnownZero;
1065     break;
1066   case Instruction::Trunc: {
1067     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1068     DemandedMask.zext(truncBf);
1069     RHSKnownZero.zext(truncBf);
1070     RHSKnownOne.zext(truncBf);
1071     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1072                              RHSKnownZero, RHSKnownOne, Depth+1))
1073       return I;
1074     DemandedMask.trunc(BitWidth);
1075     RHSKnownZero.trunc(BitWidth);
1076     RHSKnownOne.trunc(BitWidth);
1077     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1078     break;
1079   }
1080   case Instruction::BitCast:
1081     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1082       return false;  // vector->int or fp->int?
1083
1084     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1085       if (const VectorType *SrcVTy =
1086             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1087         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1088           // Don't touch a bitcast between vectors of different element counts.
1089           return false;
1090       } else
1091         // Don't touch a scalar-to-vector bitcast.
1092         return false;
1093     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1094       // Don't touch a vector-to-scalar bitcast.
1095       return false;
1096
1097     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1098                              RHSKnownZero, RHSKnownOne, Depth+1))
1099       return I;
1100     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1101     break;
1102   case Instruction::ZExt: {
1103     // Compute the bits in the result that are not present in the input.
1104     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1105     
1106     DemandedMask.trunc(SrcBitWidth);
1107     RHSKnownZero.trunc(SrcBitWidth);
1108     RHSKnownOne.trunc(SrcBitWidth);
1109     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1110                              RHSKnownZero, RHSKnownOne, Depth+1))
1111       return I;
1112     DemandedMask.zext(BitWidth);
1113     RHSKnownZero.zext(BitWidth);
1114     RHSKnownOne.zext(BitWidth);
1115     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1116     // The top bits are known to be zero.
1117     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1118     break;
1119   }
1120   case Instruction::SExt: {
1121     // Compute the bits in the result that are not present in the input.
1122     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1123     
1124     APInt InputDemandedBits = DemandedMask & 
1125                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1126
1127     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1128     // If any of the sign extended bits are demanded, we know that the sign
1129     // bit is demanded.
1130     if ((NewBits & DemandedMask) != 0)
1131       InputDemandedBits.set(SrcBitWidth-1);
1132       
1133     InputDemandedBits.trunc(SrcBitWidth);
1134     RHSKnownZero.trunc(SrcBitWidth);
1135     RHSKnownOne.trunc(SrcBitWidth);
1136     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1137                              RHSKnownZero, RHSKnownOne, Depth+1))
1138       return I;
1139     InputDemandedBits.zext(BitWidth);
1140     RHSKnownZero.zext(BitWidth);
1141     RHSKnownOne.zext(BitWidth);
1142     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1143       
1144     // If the sign bit of the input is known set or clear, then we know the
1145     // top bits of the result.
1146
1147     // If the input sign bit is known zero, or if the NewBits are not demanded
1148     // convert this into a zero extension.
1149     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1150       // Convert to ZExt cast
1151       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1152       return InsertNewInstBefore(NewCast, *I);
1153     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1154       RHSKnownOne |= NewBits;
1155     }
1156     break;
1157   }
1158   case Instruction::Add: {
1159     // Figure out what the input bits are.  If the top bits of the and result
1160     // are not demanded, then the add doesn't demand them from its input
1161     // either.
1162     unsigned NLZ = DemandedMask.countLeadingZeros();
1163       
1164     // If there is a constant on the RHS, there are a variety of xformations
1165     // we can do.
1166     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1167       // If null, this should be simplified elsewhere.  Some of the xforms here
1168       // won't work if the RHS is zero.
1169       if (RHS->isZero())
1170         break;
1171       
1172       // If the top bit of the output is demanded, demand everything from the
1173       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1174       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1175
1176       // Find information about known zero/one bits in the input.
1177       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1178                                LHSKnownZero, LHSKnownOne, Depth+1))
1179         return I;
1180
1181       // If the RHS of the add has bits set that can't affect the input, reduce
1182       // the constant.
1183       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1184         return I;
1185       
1186       // Avoid excess work.
1187       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1188         break;
1189       
1190       // Turn it into OR if input bits are zero.
1191       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1192         Instruction *Or =
1193           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1194                                    I->getName());
1195         return InsertNewInstBefore(Or, *I);
1196       }
1197       
1198       // We can say something about the output known-zero and known-one bits,
1199       // depending on potential carries from the input constant and the
1200       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1201       // bits set and the RHS constant is 0x01001, then we know we have a known
1202       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1203       
1204       // To compute this, we first compute the potential carry bits.  These are
1205       // the bits which may be modified.  I'm not aware of a better way to do
1206       // this scan.
1207       const APInt &RHSVal = RHS->getValue();
1208       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1209       
1210       // Now that we know which bits have carries, compute the known-1/0 sets.
1211       
1212       // Bits are known one if they are known zero in one operand and one in the
1213       // other, and there is no input carry.
1214       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1215                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1216       
1217       // Bits are known zero if they are known zero in both operands and there
1218       // is no input carry.
1219       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1220     } else {
1221       // If the high-bits of this ADD are not demanded, then it does not demand
1222       // the high bits of its LHS or RHS.
1223       if (DemandedMask[BitWidth-1] == 0) {
1224         // Right fill the mask of bits for this ADD to demand the most
1225         // significant bit and all those below it.
1226         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1227         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1228                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1229             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1230                                  LHSKnownZero, LHSKnownOne, Depth+1))
1231           return I;
1232       }
1233     }
1234     break;
1235   }
1236   case Instruction::Sub:
1237     // If the high-bits of this SUB are not demanded, then it does not demand
1238     // the high bits of its LHS or RHS.
1239     if (DemandedMask[BitWidth-1] == 0) {
1240       // Right fill the mask of bits for this SUB to demand the most
1241       // significant bit and all those below it.
1242       uint32_t NLZ = DemandedMask.countLeadingZeros();
1243       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1244       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1245                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1246           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1247                                LHSKnownZero, LHSKnownOne, Depth+1))
1248         return I;
1249     }
1250     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1251     // the known zeros and ones.
1252     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1253     break;
1254   case Instruction::Shl:
1255     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1256       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1257       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1258       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1259                                RHSKnownZero, RHSKnownOne, Depth+1))
1260         return I;
1261       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1262       RHSKnownZero <<= ShiftAmt;
1263       RHSKnownOne  <<= ShiftAmt;
1264       // low bits known zero.
1265       if (ShiftAmt)
1266         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1267     }
1268     break;
1269   case Instruction::LShr:
1270     // For a logical shift right
1271     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1272       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1273       
1274       // Unsigned shift right.
1275       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1276       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1277                                RHSKnownZero, RHSKnownOne, Depth+1))
1278         return I;
1279       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1280       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1281       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1282       if (ShiftAmt) {
1283         // Compute the new bits that are at the top now.
1284         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1285         RHSKnownZero |= HighBits;  // high bits known zero.
1286       }
1287     }
1288     break;
1289   case Instruction::AShr:
1290     // If this is an arithmetic shift right and only the low-bit is set, we can
1291     // always convert this into a logical shr, even if the shift amount is
1292     // variable.  The low bit of the shift cannot be an input sign bit unless
1293     // the shift amount is >= the size of the datatype, which is undefined.
1294     if (DemandedMask == 1) {
1295       // Perform the logical shift right.
1296       Instruction *NewVal = BinaryOperator::CreateLShr(
1297                         I->getOperand(0), I->getOperand(1), I->getName());
1298       return InsertNewInstBefore(NewVal, *I);
1299     }    
1300
1301     // If the sign bit is the only bit demanded by this ashr, then there is no
1302     // need to do it, the shift doesn't change the high bit.
1303     if (DemandedMask.isSignBit())
1304       return I->getOperand(0);
1305     
1306     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1307       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1308       
1309       // Signed shift right.
1310       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1311       // If any of the "high bits" are demanded, we should set the sign bit as
1312       // demanded.
1313       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1314         DemandedMaskIn.set(BitWidth-1);
1315       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1316                                RHSKnownZero, RHSKnownOne, Depth+1))
1317         return I;
1318       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1319       // Compute the new bits that are at the top now.
1320       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1321       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1322       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1323         
1324       // Handle the sign bits.
1325       APInt SignBit(APInt::getSignBit(BitWidth));
1326       // Adjust to where it is now in the mask.
1327       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1328         
1329       // If the input sign bit is known to be zero, or if none of the top bits
1330       // are demanded, turn this into an unsigned shift right.
1331       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1332           (HighBits & ~DemandedMask) == HighBits) {
1333         // Perform the logical shift right.
1334         Instruction *NewVal = BinaryOperator::CreateLShr(
1335                           I->getOperand(0), SA, I->getName());
1336         return InsertNewInstBefore(NewVal, *I);
1337       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1338         RHSKnownOne |= HighBits;
1339       }
1340     }
1341     break;
1342   case Instruction::SRem:
1343     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1344       APInt RA = Rem->getValue().abs();
1345       if (RA.isPowerOf2()) {
1346         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1347           return I->getOperand(0);
1348
1349         APInt LowBits = RA - 1;
1350         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1351         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1352                                  LHSKnownZero, LHSKnownOne, Depth+1))
1353           return I;
1354
1355         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1356           LHSKnownZero |= ~LowBits;
1357
1358         KnownZero |= LHSKnownZero & DemandedMask;
1359
1360         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1361       }
1362     }
1363     break;
1364   case Instruction::URem: {
1365     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1366     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1367     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1368                              KnownZero2, KnownOne2, Depth+1) ||
1369         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1370                              KnownZero2, KnownOne2, Depth+1))
1371       return I;
1372
1373     unsigned Leaders = KnownZero2.countLeadingOnes();
1374     Leaders = std::max(Leaders,
1375                        KnownZero2.countLeadingOnes());
1376     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1377     break;
1378   }
1379   case Instruction::Call:
1380     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1381       switch (II->getIntrinsicID()) {
1382       default: break;
1383       case Intrinsic::bswap: {
1384         // If the only bits demanded come from one byte of the bswap result,
1385         // just shift the input byte into position to eliminate the bswap.
1386         unsigned NLZ = DemandedMask.countLeadingZeros();
1387         unsigned NTZ = DemandedMask.countTrailingZeros();
1388           
1389         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1390         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1391         // have 14 leading zeros, round to 8.
1392         NLZ &= ~7;
1393         NTZ &= ~7;
1394         // If we need exactly one byte, we can do this transformation.
1395         if (BitWidth-NLZ-NTZ == 8) {
1396           unsigned ResultBit = NTZ;
1397           unsigned InputBit = BitWidth-NTZ-8;
1398           
1399           // Replace this with either a left or right shift to get the byte into
1400           // the right place.
1401           Instruction *NewVal;
1402           if (InputBit > ResultBit)
1403             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1404                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1405           else
1406             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1407                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1408           NewVal->takeName(I);
1409           return InsertNewInstBefore(NewVal, *I);
1410         }
1411           
1412         // TODO: Could compute known zero/one bits based on the input.
1413         break;
1414       }
1415       }
1416     }
1417     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1418     break;
1419   }
1420   
1421   // If the client is only demanding bits that we know, return the known
1422   // constant.
1423   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1424     return Constant::getIntegerValue(VTy, RHSKnownOne);
1425   return false;
1426 }
1427
1428
1429 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1430 /// any number of elements. DemandedElts contains the set of elements that are
1431 /// actually used by the caller.  This method analyzes which elements of the
1432 /// operand are undef and returns that information in UndefElts.
1433 ///
1434 /// If the information about demanded elements can be used to simplify the
1435 /// operation, the operation is simplified, then the resultant value is
1436 /// returned.  This returns null if no change was made.
1437 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1438                                                 APInt& UndefElts,
1439                                                 unsigned Depth) {
1440   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1441   APInt EltMask(APInt::getAllOnesValue(VWidth));
1442   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1443
1444   if (isa<UndefValue>(V)) {
1445     // If the entire vector is undefined, just return this info.
1446     UndefElts = EltMask;
1447     return 0;
1448   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1449     UndefElts = EltMask;
1450     return UndefValue::get(V->getType());
1451   }
1452
1453   UndefElts = 0;
1454   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1455     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1456     Constant *Undef = UndefValue::get(EltTy);
1457
1458     std::vector<Constant*> Elts;
1459     for (unsigned i = 0; i != VWidth; ++i)
1460       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1461         Elts.push_back(Undef);
1462         UndefElts.set(i);
1463       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1464         Elts.push_back(Undef);
1465         UndefElts.set(i);
1466       } else {                               // Otherwise, defined.
1467         Elts.push_back(CP->getOperand(i));
1468       }
1469
1470     // If we changed the constant, return it.
1471     Constant *NewCP = ConstantVector::get(Elts);
1472     return NewCP != CP ? NewCP : 0;
1473   } else if (isa<ConstantAggregateZero>(V)) {
1474     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1475     // set to undef.
1476     
1477     // Check if this is identity. If so, return 0 since we are not simplifying
1478     // anything.
1479     if (DemandedElts == ((1ULL << VWidth) -1))
1480       return 0;
1481     
1482     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1483     Constant *Zero = Constant::getNullValue(EltTy);
1484     Constant *Undef = UndefValue::get(EltTy);
1485     std::vector<Constant*> Elts;
1486     for (unsigned i = 0; i != VWidth; ++i) {
1487       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1488       Elts.push_back(Elt);
1489     }
1490     UndefElts = DemandedElts ^ EltMask;
1491     return ConstantVector::get(Elts);
1492   }
1493   
1494   // Limit search depth.
1495   if (Depth == 10)
1496     return 0;
1497
1498   // If multiple users are using the root value, procede with
1499   // simplification conservatively assuming that all elements
1500   // are needed.
1501   if (!V->hasOneUse()) {
1502     // Quit if we find multiple users of a non-root value though.
1503     // They'll be handled when it's their turn to be visited by
1504     // the main instcombine process.
1505     if (Depth != 0)
1506       // TODO: Just compute the UndefElts information recursively.
1507       return 0;
1508
1509     // Conservatively assume that all elements are needed.
1510     DemandedElts = EltMask;
1511   }
1512   
1513   Instruction *I = dyn_cast<Instruction>(V);
1514   if (!I) return 0;        // Only analyze instructions.
1515   
1516   bool MadeChange = false;
1517   APInt UndefElts2(VWidth, 0);
1518   Value *TmpV;
1519   switch (I->getOpcode()) {
1520   default: break;
1521     
1522   case Instruction::InsertElement: {
1523     // If this is a variable index, we don't know which element it overwrites.
1524     // demand exactly the same input as we produce.
1525     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1526     if (Idx == 0) {
1527       // Note that we can't propagate undef elt info, because we don't know
1528       // which elt is getting updated.
1529       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1530                                         UndefElts2, Depth+1);
1531       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1532       break;
1533     }
1534     
1535     // If this is inserting an element that isn't demanded, remove this
1536     // insertelement.
1537     unsigned IdxNo = Idx->getZExtValue();
1538     if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1539       Worklist.Add(I);
1540       return I->getOperand(0);
1541     }
1542     
1543     // Otherwise, the element inserted overwrites whatever was there, so the
1544     // input demanded set is simpler than the output set.
1545     APInt DemandedElts2 = DemandedElts;
1546     DemandedElts2.clear(IdxNo);
1547     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1548                                       UndefElts, Depth+1);
1549     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1550
1551     // The inserted element is defined.
1552     UndefElts.clear(IdxNo);
1553     break;
1554   }
1555   case Instruction::ShuffleVector: {
1556     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1557     uint64_t LHSVWidth =
1558       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1559     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1560     for (unsigned i = 0; i < VWidth; i++) {
1561       if (DemandedElts[i]) {
1562         unsigned MaskVal = Shuffle->getMaskValue(i);
1563         if (MaskVal != -1u) {
1564           assert(MaskVal < LHSVWidth * 2 &&
1565                  "shufflevector mask index out of range!");
1566           if (MaskVal < LHSVWidth)
1567             LeftDemanded.set(MaskVal);
1568           else
1569             RightDemanded.set(MaskVal - LHSVWidth);
1570         }
1571       }
1572     }
1573
1574     APInt UndefElts4(LHSVWidth, 0);
1575     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1576                                       UndefElts4, Depth+1);
1577     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1578
1579     APInt UndefElts3(LHSVWidth, 0);
1580     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1581                                       UndefElts3, Depth+1);
1582     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1583
1584     bool NewUndefElts = false;
1585     for (unsigned i = 0; i < VWidth; i++) {
1586       unsigned MaskVal = Shuffle->getMaskValue(i);
1587       if (MaskVal == -1u) {
1588         UndefElts.set(i);
1589       } else if (MaskVal < LHSVWidth) {
1590         if (UndefElts4[MaskVal]) {
1591           NewUndefElts = true;
1592           UndefElts.set(i);
1593         }
1594       } else {
1595         if (UndefElts3[MaskVal - LHSVWidth]) {
1596           NewUndefElts = true;
1597           UndefElts.set(i);
1598         }
1599       }
1600     }
1601
1602     if (NewUndefElts) {
1603       // Add additional discovered undefs.
1604       std::vector<Constant*> Elts;
1605       for (unsigned i = 0; i < VWidth; ++i) {
1606         if (UndefElts[i])
1607           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
1608         else
1609           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
1610                                           Shuffle->getMaskValue(i)));
1611       }
1612       I->setOperand(2, ConstantVector::get(Elts));
1613       MadeChange = true;
1614     }
1615     break;
1616   }
1617   case Instruction::BitCast: {
1618     // Vector->vector casts only.
1619     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1620     if (!VTy) break;
1621     unsigned InVWidth = VTy->getNumElements();
1622     APInt InputDemandedElts(InVWidth, 0);
1623     unsigned Ratio;
1624
1625     if (VWidth == InVWidth) {
1626       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1627       // elements as are demanded of us.
1628       Ratio = 1;
1629       InputDemandedElts = DemandedElts;
1630     } else if (VWidth > InVWidth) {
1631       // Untested so far.
1632       break;
1633       
1634       // If there are more elements in the result than there are in the source,
1635       // then an input element is live if any of the corresponding output
1636       // elements are live.
1637       Ratio = VWidth/InVWidth;
1638       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1639         if (DemandedElts[OutIdx])
1640           InputDemandedElts.set(OutIdx/Ratio);
1641       }
1642     } else {
1643       // Untested so far.
1644       break;
1645       
1646       // If there are more elements in the source than there are in the result,
1647       // then an input element is live if the corresponding output element is
1648       // live.
1649       Ratio = InVWidth/VWidth;
1650       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1651         if (DemandedElts[InIdx/Ratio])
1652           InputDemandedElts.set(InIdx);
1653     }
1654     
1655     // div/rem demand all inputs, because they don't want divide by zero.
1656     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1657                                       UndefElts2, Depth+1);
1658     if (TmpV) {
1659       I->setOperand(0, TmpV);
1660       MadeChange = true;
1661     }
1662     
1663     UndefElts = UndefElts2;
1664     if (VWidth > InVWidth) {
1665       llvm_unreachable("Unimp");
1666       // If there are more elements in the result than there are in the source,
1667       // then an output element is undef if the corresponding input element is
1668       // undef.
1669       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1670         if (UndefElts2[OutIdx/Ratio])
1671           UndefElts.set(OutIdx);
1672     } else if (VWidth < InVWidth) {
1673       llvm_unreachable("Unimp");
1674       // If there are more elements in the source than there are in the result,
1675       // then a result element is undef if all of the corresponding input
1676       // elements are undef.
1677       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1678       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1679         if (!UndefElts2[InIdx])            // Not undef?
1680           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1681     }
1682     break;
1683   }
1684   case Instruction::And:
1685   case Instruction::Or:
1686   case Instruction::Xor:
1687   case Instruction::Add:
1688   case Instruction::Sub:
1689   case Instruction::Mul:
1690     // div/rem demand all inputs, because they don't want divide by zero.
1691     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1692                                       UndefElts, Depth+1);
1693     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1694     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1695                                       UndefElts2, Depth+1);
1696     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1697       
1698     // Output elements are undefined if both are undefined.  Consider things
1699     // like undef&0.  The result is known zero, not undef.
1700     UndefElts &= UndefElts2;
1701     break;
1702     
1703   case Instruction::Call: {
1704     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1705     if (!II) break;
1706     switch (II->getIntrinsicID()) {
1707     default: break;
1708       
1709     // Binary vector operations that work column-wise.  A dest element is a
1710     // function of the corresponding input elements from the two inputs.
1711     case Intrinsic::x86_sse_sub_ss:
1712     case Intrinsic::x86_sse_mul_ss:
1713     case Intrinsic::x86_sse_min_ss:
1714     case Intrinsic::x86_sse_max_ss:
1715     case Intrinsic::x86_sse2_sub_sd:
1716     case Intrinsic::x86_sse2_mul_sd:
1717     case Intrinsic::x86_sse2_min_sd:
1718     case Intrinsic::x86_sse2_max_sd:
1719       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1720                                         UndefElts, Depth+1);
1721       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1722       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1723                                         UndefElts2, Depth+1);
1724       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1725
1726       // If only the low elt is demanded and this is a scalarizable intrinsic,
1727       // scalarize it now.
1728       if (DemandedElts == 1) {
1729         switch (II->getIntrinsicID()) {
1730         default: break;
1731         case Intrinsic::x86_sse_sub_ss:
1732         case Intrinsic::x86_sse_mul_ss:
1733         case Intrinsic::x86_sse2_sub_sd:
1734         case Intrinsic::x86_sse2_mul_sd:
1735           // TODO: Lower MIN/MAX/ABS/etc
1736           Value *LHS = II->getOperand(1);
1737           Value *RHS = II->getOperand(2);
1738           // Extract the element as scalars.
1739           LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS, 
1740             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1741           RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1742             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1743           
1744           switch (II->getIntrinsicID()) {
1745           default: llvm_unreachable("Case stmts out of sync!");
1746           case Intrinsic::x86_sse_sub_ss:
1747           case Intrinsic::x86_sse2_sub_sd:
1748             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1749                                                         II->getName()), *II);
1750             break;
1751           case Intrinsic::x86_sse_mul_ss:
1752           case Intrinsic::x86_sse2_mul_sd:
1753             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1754                                                          II->getName()), *II);
1755             break;
1756           }
1757           
1758           Instruction *New =
1759             InsertElementInst::Create(
1760               UndefValue::get(II->getType()), TmpV,
1761               ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
1762           InsertNewInstBefore(New, *II);
1763           return New;
1764         }            
1765       }
1766         
1767       // Output elements are undefined if both are undefined.  Consider things
1768       // like undef&0.  The result is known zero, not undef.
1769       UndefElts &= UndefElts2;
1770       break;
1771     }
1772     break;
1773   }
1774   }
1775   return MadeChange ? I : 0;
1776 }
1777
1778
1779 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1780 /// function is designed to check a chain of associative operators for a
1781 /// potential to apply a certain optimization.  Since the optimization may be
1782 /// applicable if the expression was reassociated, this checks the chain, then
1783 /// reassociates the expression as necessary to expose the optimization
1784 /// opportunity.  This makes use of a special Functor, which must define
1785 /// 'shouldApply' and 'apply' methods.
1786 ///
1787 template<typename Functor>
1788 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1789   unsigned Opcode = Root.getOpcode();
1790   Value *LHS = Root.getOperand(0);
1791
1792   // Quick check, see if the immediate LHS matches...
1793   if (F.shouldApply(LHS))
1794     return F.apply(Root);
1795
1796   // Otherwise, if the LHS is not of the same opcode as the root, return.
1797   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1798   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1799     // Should we apply this transform to the RHS?
1800     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1801
1802     // If not to the RHS, check to see if we should apply to the LHS...
1803     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1804       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1805       ShouldApply = true;
1806     }
1807
1808     // If the functor wants to apply the optimization to the RHS of LHSI,
1809     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1810     if (ShouldApply) {
1811       // Now all of the instructions are in the current basic block, go ahead
1812       // and perform the reassociation.
1813       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1814
1815       // First move the selected RHS to the LHS of the root...
1816       Root.setOperand(0, LHSI->getOperand(1));
1817
1818       // Make what used to be the LHS of the root be the user of the root...
1819       Value *ExtraOperand = TmpLHSI->getOperand(1);
1820       if (&Root == TmpLHSI) {
1821         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1822         return 0;
1823       }
1824       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1825       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1826       BasicBlock::iterator ARI = &Root; ++ARI;
1827       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1828       ARI = Root;
1829
1830       // Now propagate the ExtraOperand down the chain of instructions until we
1831       // get to LHSI.
1832       while (TmpLHSI != LHSI) {
1833         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1834         // Move the instruction to immediately before the chain we are
1835         // constructing to avoid breaking dominance properties.
1836         NextLHSI->moveBefore(ARI);
1837         ARI = NextLHSI;
1838
1839         Value *NextOp = NextLHSI->getOperand(1);
1840         NextLHSI->setOperand(1, ExtraOperand);
1841         TmpLHSI = NextLHSI;
1842         ExtraOperand = NextOp;
1843       }
1844
1845       // Now that the instructions are reassociated, have the functor perform
1846       // the transformation...
1847       return F.apply(Root);
1848     }
1849
1850     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1851   }
1852   return 0;
1853 }
1854
1855 namespace {
1856
1857 // AddRHS - Implements: X + X --> X << 1
1858 struct AddRHS {
1859   Value *RHS;
1860   explicit AddRHS(Value *rhs) : RHS(rhs) {}
1861   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1862   Instruction *apply(BinaryOperator &Add) const {
1863     return BinaryOperator::CreateShl(Add.getOperand(0),
1864                                      ConstantInt::get(Add.getType(), 1));
1865   }
1866 };
1867
1868 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1869 //                 iff C1&C2 == 0
1870 struct AddMaskingAnd {
1871   Constant *C2;
1872   explicit AddMaskingAnd(Constant *c) : C2(c) {}
1873   bool shouldApply(Value *LHS) const {
1874     ConstantInt *C1;
1875     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1876            ConstantExpr::getAnd(C1, C2)->isNullValue();
1877   }
1878   Instruction *apply(BinaryOperator &Add) const {
1879     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1880   }
1881 };
1882
1883 }
1884
1885 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1886                                              InstCombiner *IC) {
1887   if (CastInst *CI = dyn_cast<CastInst>(&I))
1888     return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
1889
1890   // Figure out if the constant is the left or the right argument.
1891   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1892   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1893
1894   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1895     if (ConstIsRHS)
1896       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1897     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1898   }
1899
1900   Value *Op0 = SO, *Op1 = ConstOperand;
1901   if (!ConstIsRHS)
1902     std::swap(Op0, Op1);
1903   
1904   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1905     return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1906                                     SO->getName()+".op");
1907   if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1908     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1909                                    SO->getName()+".cmp");
1910   if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1911     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1912                                    SO->getName()+".cmp");
1913   llvm_unreachable("Unknown binary instruction type!");
1914 }
1915
1916 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1917 // constant as the other operand, try to fold the binary operator into the
1918 // select arguments.  This also works for Cast instructions, which obviously do
1919 // not have a second operand.
1920 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1921                                      InstCombiner *IC) {
1922   // Don't modify shared select instructions
1923   if (!SI->hasOneUse()) return 0;
1924   Value *TV = SI->getOperand(1);
1925   Value *FV = SI->getOperand(2);
1926
1927   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1928     // Bool selects with constant operands can be folded to logical ops.
1929     if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
1930
1931     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1932     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1933
1934     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1935                               SelectFalseVal);
1936   }
1937   return 0;
1938 }
1939
1940
1941 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1942 /// node as operand #0, see if we can fold the instruction into the PHI (which
1943 /// is only possible if all operands to the PHI are constants).
1944 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1945   PHINode *PN = cast<PHINode>(I.getOperand(0));
1946   unsigned NumPHIValues = PN->getNumIncomingValues();
1947   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1948
1949   // Check to see if all of the operands of the PHI are constants.  If there is
1950   // one non-constant value, remember the BB it is.  If there is more than one
1951   // or if *it* is a PHI, bail out.
1952   BasicBlock *NonConstBB = 0;
1953   for (unsigned i = 0; i != NumPHIValues; ++i)
1954     if (!isa<Constant>(PN->getIncomingValue(i))) {
1955       if (NonConstBB) return 0;  // More than one non-const value.
1956       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1957       NonConstBB = PN->getIncomingBlock(i);
1958       
1959       // If the incoming non-constant value is in I's block, we have an infinite
1960       // loop.
1961       if (NonConstBB == I.getParent())
1962         return 0;
1963     }
1964   
1965   // If there is exactly one non-constant value, we can insert a copy of the
1966   // operation in that block.  However, if this is a critical edge, we would be
1967   // inserting the computation one some other paths (e.g. inside a loop).  Only
1968   // do this if the pred block is unconditionally branching into the phi block.
1969   if (NonConstBB) {
1970     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1971     if (!BI || !BI->isUnconditional()) return 0;
1972   }
1973
1974   // Okay, we can do the transformation: create the new PHI node.
1975   PHINode *NewPN = PHINode::Create(I.getType(), "");
1976   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1977   InsertNewInstBefore(NewPN, *PN);
1978   NewPN->takeName(PN);
1979
1980   // Next, add all of the operands to the PHI.
1981   if (I.getNumOperands() == 2) {
1982     Constant *C = cast<Constant>(I.getOperand(1));
1983     for (unsigned i = 0; i != NumPHIValues; ++i) {
1984       Value *InV = 0;
1985       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1986         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1987           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1988         else
1989           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1990       } else {
1991         assert(PN->getIncomingBlock(i) == NonConstBB);
1992         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1993           InV = BinaryOperator::Create(BO->getOpcode(),
1994                                        PN->getIncomingValue(i), C, "phitmp",
1995                                        NonConstBB->getTerminator());
1996         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1997           InV = CmpInst::Create(CI->getOpcode(),
1998                                 CI->getPredicate(),
1999                                 PN->getIncomingValue(i), C, "phitmp",
2000                                 NonConstBB->getTerminator());
2001         else
2002           llvm_unreachable("Unknown binop!");
2003         
2004         Worklist.Add(cast<Instruction>(InV));
2005       }
2006       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2007     }
2008   } else { 
2009     CastInst *CI = cast<CastInst>(&I);
2010     const Type *RetTy = CI->getType();
2011     for (unsigned i = 0; i != NumPHIValues; ++i) {
2012       Value *InV;
2013       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2014         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2015       } else {
2016         assert(PN->getIncomingBlock(i) == NonConstBB);
2017         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2018                                I.getType(), "phitmp", 
2019                                NonConstBB->getTerminator());
2020         Worklist.Add(cast<Instruction>(InV));
2021       }
2022       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2023     }
2024   }
2025   return ReplaceInstUsesWith(I, NewPN);
2026 }
2027
2028
2029 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2030 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2031 /// This basically requires proving that the add in the original type would not
2032 /// overflow to change the sign bit or have a carry out.
2033 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2034   // There are different heuristics we can use for this.  Here are some simple
2035   // ones.
2036   
2037   // Add has the property that adding any two 2's complement numbers can only 
2038   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2039   // have at least two sign bits, we know that the addition of the two values will
2040   // sign extend fine.
2041   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2042     return true;
2043   
2044   
2045   // If one of the operands only has one non-zero bit, and if the other operand
2046   // has a known-zero bit in a more significant place than it (not including the
2047   // sign bit) the ripple may go up to and fill the zero, but won't change the
2048   // sign.  For example, (X & ~4) + 1.
2049   
2050   // TODO: Implement.
2051   
2052   return false;
2053 }
2054
2055
2056 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2057   bool Changed = SimplifyCommutative(I);
2058   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2059
2060   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2061     // X + undef -> undef
2062     if (isa<UndefValue>(RHS))
2063       return ReplaceInstUsesWith(I, RHS);
2064
2065     // X + 0 --> X
2066     if (RHSC->isNullValue())
2067       return ReplaceInstUsesWith(I, LHS);
2068
2069     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2070       // X + (signbit) --> X ^ signbit
2071       const APInt& Val = CI->getValue();
2072       uint32_t BitWidth = Val.getBitWidth();
2073       if (Val == APInt::getSignBit(BitWidth))
2074         return BinaryOperator::CreateXor(LHS, RHS);
2075       
2076       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2077       // (X & 254)+1 -> (X&254)|1
2078       if (SimplifyDemandedInstructionBits(I))
2079         return &I;
2080
2081       // zext(bool) + C -> bool ? C + 1 : C
2082       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2083         if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2084           return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2085     }
2086
2087     if (isa<PHINode>(LHS))
2088       if (Instruction *NV = FoldOpIntoPhi(I))
2089         return NV;
2090     
2091     ConstantInt *XorRHS = 0;
2092     Value *XorLHS = 0;
2093     if (isa<ConstantInt>(RHSC) &&
2094         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2095       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2096       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2097       
2098       uint32_t Size = TySizeBits / 2;
2099       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2100       APInt CFF80Val(-C0080Val);
2101       do {
2102         if (TySizeBits > Size) {
2103           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2104           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2105           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2106               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2107             // This is a sign extend if the top bits are known zero.
2108             if (!MaskedValueIsZero(XorLHS, 
2109                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2110               Size = 0;  // Not a sign ext, but can't be any others either.
2111             break;
2112           }
2113         }
2114         Size >>= 1;
2115         C0080Val = APIntOps::lshr(C0080Val, Size);
2116         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2117       } while (Size >= 1);
2118       
2119       // FIXME: This shouldn't be necessary. When the backends can handle types
2120       // with funny bit widths then this switch statement should be removed. It
2121       // is just here to get the size of the "middle" type back up to something
2122       // that the back ends can handle.
2123       const Type *MiddleType = 0;
2124       switch (Size) {
2125         default: break;
2126         case 32: MiddleType = Type::getInt32Ty(*Context); break;
2127         case 16: MiddleType = Type::getInt16Ty(*Context); break;
2128         case  8: MiddleType = Type::getInt8Ty(*Context); break;
2129       }
2130       if (MiddleType) {
2131         Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
2132         return new SExtInst(NewTrunc, I.getType(), I.getName());
2133       }
2134     }
2135   }
2136
2137   if (I.getType() == Type::getInt1Ty(*Context))
2138     return BinaryOperator::CreateXor(LHS, RHS);
2139
2140   // X + X --> X << 1
2141   if (I.getType()->isInteger()) {
2142     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2143       return Result;
2144
2145     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2146       if (RHSI->getOpcode() == Instruction::Sub)
2147         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2148           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2149     }
2150     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2151       if (LHSI->getOpcode() == Instruction::Sub)
2152         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2153           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2154     }
2155   }
2156
2157   // -A + B  -->  B - A
2158   // -A + -B  -->  -(A + B)
2159   if (Value *LHSV = dyn_castNegVal(LHS)) {
2160     if (LHS->getType()->isIntOrIntVector()) {
2161       if (Value *RHSV = dyn_castNegVal(RHS)) {
2162         Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
2163         return BinaryOperator::CreateNeg(NewAdd);
2164       }
2165     }
2166     
2167     return BinaryOperator::CreateSub(RHS, LHSV);
2168   }
2169
2170   // A + -B  -->  A - B
2171   if (!isa<Constant>(RHS))
2172     if (Value *V = dyn_castNegVal(RHS))
2173       return BinaryOperator::CreateSub(LHS, V);
2174
2175
2176   ConstantInt *C2;
2177   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2178     if (X == RHS)   // X*C + X --> X * (C+1)
2179       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2180
2181     // X*C1 + X*C2 --> X * (C1+C2)
2182     ConstantInt *C1;
2183     if (X == dyn_castFoldableMul(RHS, C1))
2184       return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2185   }
2186
2187   // X + X*C --> X * (C+1)
2188   if (dyn_castFoldableMul(RHS, C2) == LHS)
2189     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2190
2191   // X + ~X --> -1   since   ~X = -X-1
2192   if (dyn_castNotVal(LHS) == RHS ||
2193       dyn_castNotVal(RHS) == LHS)
2194     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2195   
2196
2197   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2198   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2199     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2200       return R;
2201   
2202   // A+B --> A|B iff A and B have no bits set in common.
2203   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2204     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2205     APInt LHSKnownOne(IT->getBitWidth(), 0);
2206     APInt LHSKnownZero(IT->getBitWidth(), 0);
2207     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2208     if (LHSKnownZero != 0) {
2209       APInt RHSKnownOne(IT->getBitWidth(), 0);
2210       APInt RHSKnownZero(IT->getBitWidth(), 0);
2211       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2212       
2213       // No bits in common -> bitwise or.
2214       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2215         return BinaryOperator::CreateOr(LHS, RHS);
2216     }
2217   }
2218
2219   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2220   if (I.getType()->isIntOrIntVector()) {
2221     Value *W, *X, *Y, *Z;
2222     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2223         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2224       if (W != Y) {
2225         if (W == Z) {
2226           std::swap(Y, Z);
2227         } else if (Y == X) {
2228           std::swap(W, X);
2229         } else if (X == Z) {
2230           std::swap(Y, Z);
2231           std::swap(W, X);
2232         }
2233       }
2234
2235       if (W == Y) {
2236         Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
2237         return BinaryOperator::CreateMul(W, NewAdd);
2238       }
2239     }
2240   }
2241
2242   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2243     Value *X = 0;
2244     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2245       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2246
2247     // (X & FF00) + xx00  -> (X+xx00) & FF00
2248     if (LHS->hasOneUse() &&
2249         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2250       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2251       if (Anded == CRHS) {
2252         // See if all bits from the first bit set in the Add RHS up are included
2253         // in the mask.  First, get the rightmost bit.
2254         const APInt& AddRHSV = CRHS->getValue();
2255
2256         // Form a mask of all bits from the lowest bit added through the top.
2257         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2258
2259         // See if the and mask includes all of these bits.
2260         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2261
2262         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2263           // Okay, the xform is safe.  Insert the new add pronto.
2264           Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
2265           return BinaryOperator::CreateAnd(NewAdd, C2);
2266         }
2267       }
2268     }
2269
2270     // Try to fold constant add into select arguments.
2271     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2272       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2273         return R;
2274   }
2275
2276   // add (select X 0 (sub n A)) A  -->  select X A n
2277   {
2278     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2279     Value *A = RHS;
2280     if (!SI) {
2281       SI = dyn_cast<SelectInst>(RHS);
2282       A = LHS;
2283     }
2284     if (SI && SI->hasOneUse()) {
2285       Value *TV = SI->getTrueValue();
2286       Value *FV = SI->getFalseValue();
2287       Value *N;
2288
2289       // Can we fold the add into the argument of the select?
2290       // We check both true and false select arguments for a matching subtract.
2291       if (match(FV, m_Zero()) &&
2292           match(TV, m_Sub(m_Value(N), m_Specific(A))))
2293         // Fold the add into the true select value.
2294         return SelectInst::Create(SI->getCondition(), N, A);
2295       if (match(TV, m_Zero()) &&
2296           match(FV, m_Sub(m_Value(N), m_Specific(A))))
2297         // Fold the add into the false select value.
2298         return SelectInst::Create(SI->getCondition(), A, N);
2299     }
2300   }
2301
2302   // Check for (add (sext x), y), see if we can merge this into an
2303   // integer add followed by a sext.
2304   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2305     // (add (sext x), cst) --> (sext (add x, cst'))
2306     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2307       Constant *CI = 
2308         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2309       if (LHSConv->hasOneUse() &&
2310           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2311           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2312         // Insert the new, smaller add.
2313         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0), 
2314                                            CI, "addconv");
2315         return new SExtInst(NewAdd, I.getType());
2316       }
2317     }
2318     
2319     // (add (sext x), (sext y)) --> (sext (add int x, y))
2320     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2321       // Only do this if x/y have the same type, if at last one of them has a
2322       // single use (so we don't increase the number of sexts), and if the
2323       // integer add will not overflow.
2324       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2325           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2326           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2327                                    RHSConv->getOperand(0))) {
2328         // Insert the new integer add.
2329         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0), 
2330                                            RHSConv->getOperand(0), "addconv");
2331         return new SExtInst(NewAdd, I.getType());
2332       }
2333     }
2334   }
2335
2336   return Changed ? &I : 0;
2337 }
2338
2339 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2340   bool Changed = SimplifyCommutative(I);
2341   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2342
2343   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2344     // X + 0 --> X
2345     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2346       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2347                               (I.getType())->getValueAPF()))
2348         return ReplaceInstUsesWith(I, LHS);
2349     }
2350
2351     if (isa<PHINode>(LHS))
2352       if (Instruction *NV = FoldOpIntoPhi(I))
2353         return NV;
2354   }
2355
2356   // -A + B  -->  B - A
2357   // -A + -B  -->  -(A + B)
2358   if (Value *LHSV = dyn_castFNegVal(LHS))
2359     return BinaryOperator::CreateFSub(RHS, LHSV);
2360
2361   // A + -B  -->  A - B
2362   if (!isa<Constant>(RHS))
2363     if (Value *V = dyn_castFNegVal(RHS))
2364       return BinaryOperator::CreateFSub(LHS, V);
2365
2366   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2367   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2368     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2369       return ReplaceInstUsesWith(I, LHS);
2370
2371   // Check for (add double (sitofp x), y), see if we can merge this into an
2372   // integer add followed by a promotion.
2373   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2374     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2375     // ... if the constant fits in the integer value.  This is useful for things
2376     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2377     // requires a constant pool load, and generally allows the add to be better
2378     // instcombined.
2379     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2380       Constant *CI = 
2381       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2382       if (LHSConv->hasOneUse() &&
2383           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2384           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2385         // Insert the new integer add.
2386         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2387                                            CI, "addconv");
2388         return new SIToFPInst(NewAdd, I.getType());
2389       }
2390     }
2391     
2392     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2393     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2394       // Only do this if x/y have the same type, if at last one of them has a
2395       // single use (so we don't increase the number of int->fp conversions),
2396       // and if the integer add will not overflow.
2397       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2398           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2399           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2400                                    RHSConv->getOperand(0))) {
2401         // Insert the new integer add.
2402         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0), 
2403                                            RHSConv->getOperand(0), "addconv");
2404         return new SIToFPInst(NewAdd, I.getType());
2405       }
2406     }
2407   }
2408   
2409   return Changed ? &I : 0;
2410 }
2411
2412 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2413   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2414
2415   if (Op0 == Op1)                        // sub X, X  -> 0
2416     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2417
2418   // If this is a 'B = x-(-A)', change to B = x+A...
2419   if (Value *V = dyn_castNegVal(Op1))
2420     return BinaryOperator::CreateAdd(Op0, V);
2421
2422   if (isa<UndefValue>(Op0))
2423     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2424   if (isa<UndefValue>(Op1))
2425     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2426
2427   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2428     // Replace (-1 - A) with (~A)...
2429     if (C->isAllOnesValue())
2430       return BinaryOperator::CreateNot(Op1);
2431
2432     // C - ~X == X + (1+C)
2433     Value *X = 0;
2434     if (match(Op1, m_Not(m_Value(X))))
2435       return BinaryOperator::CreateAdd(X, AddOne(C));
2436
2437     // -(X >>u 31) -> (X >>s 31)
2438     // -(X >>s 31) -> (X >>u 31)
2439     if (C->isZero()) {
2440       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2441         if (SI->getOpcode() == Instruction::LShr) {
2442           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2443             // Check to see if we are shifting out everything but the sign bit.
2444             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2445                 SI->getType()->getPrimitiveSizeInBits()-1) {
2446               // Ok, the transformation is safe.  Insert AShr.
2447               return BinaryOperator::Create(Instruction::AShr, 
2448                                           SI->getOperand(0), CU, SI->getName());
2449             }
2450           }
2451         }
2452         else if (SI->getOpcode() == Instruction::AShr) {
2453           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2454             // Check to see if we are shifting out everything but the sign bit.
2455             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2456                 SI->getType()->getPrimitiveSizeInBits()-1) {
2457               // Ok, the transformation is safe.  Insert LShr. 
2458               return BinaryOperator::CreateLShr(
2459                                           SI->getOperand(0), CU, SI->getName());
2460             }
2461           }
2462         }
2463       }
2464     }
2465
2466     // Try to fold constant sub into select arguments.
2467     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2468       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2469         return R;
2470
2471     // C - zext(bool) -> bool ? C - 1 : C
2472     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2473       if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2474         return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2475   }
2476
2477   if (I.getType() == Type::getInt1Ty(*Context))
2478     return BinaryOperator::CreateXor(Op0, Op1);
2479
2480   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2481     if (Op1I->getOpcode() == Instruction::Add) {
2482       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2483         return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2484                                          I.getName());
2485       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2486         return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2487                                          I.getName());
2488       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2489         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2490           // C1-(X+C2) --> (C1-C2)-X
2491           return BinaryOperator::CreateSub(
2492             ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2493       }
2494     }
2495
2496     if (Op1I->hasOneUse()) {
2497       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2498       // is not used by anyone else...
2499       //
2500       if (Op1I->getOpcode() == Instruction::Sub) {
2501         // Swap the two operands of the subexpr...
2502         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2503         Op1I->setOperand(0, IIOp1);
2504         Op1I->setOperand(1, IIOp0);
2505
2506         // Create the new top level add instruction...
2507         return BinaryOperator::CreateAdd(Op0, Op1);
2508       }
2509
2510       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2511       //
2512       if (Op1I->getOpcode() == Instruction::And &&
2513           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2514         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2515
2516         Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
2517         return BinaryOperator::CreateAnd(Op0, NewNot);
2518       }
2519
2520       // 0 - (X sdiv C)  -> (X sdiv -C)
2521       if (Op1I->getOpcode() == Instruction::SDiv)
2522         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2523           if (CSI->isZero())
2524             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2525               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2526                                           ConstantExpr::getNeg(DivRHS));
2527
2528       // X - X*C --> X * (1-C)
2529       ConstantInt *C2 = 0;
2530       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2531         Constant *CP1 = 
2532           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2533                                              C2);
2534         return BinaryOperator::CreateMul(Op0, CP1);
2535       }
2536     }
2537   }
2538
2539   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2540     if (Op0I->getOpcode() == Instruction::Add) {
2541       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2542         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2543       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2544         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2545     } else if (Op0I->getOpcode() == Instruction::Sub) {
2546       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2547         return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2548                                          I.getName());
2549     }
2550   }
2551
2552   ConstantInt *C1;
2553   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2554     if (X == Op1)  // X*C - X --> X * (C-1)
2555       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2556
2557     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2558     if (X == dyn_castFoldableMul(Op1, C2))
2559       return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2560   }
2561   return 0;
2562 }
2563
2564 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2565   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2566
2567   // If this is a 'B = x-(-A)', change to B = x+A...
2568   if (Value *V = dyn_castFNegVal(Op1))
2569     return BinaryOperator::CreateFAdd(Op0, V);
2570
2571   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2572     if (Op1I->getOpcode() == Instruction::FAdd) {
2573       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2574         return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
2575                                           I.getName());
2576       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2577         return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
2578                                           I.getName());
2579     }
2580   }
2581
2582   return 0;
2583 }
2584
2585 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2586 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2587 /// TrueIfSigned if the result of the comparison is true when the input value is
2588 /// signed.
2589 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2590                            bool &TrueIfSigned) {
2591   switch (pred) {
2592   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2593     TrueIfSigned = true;
2594     return RHS->isZero();
2595   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2596     TrueIfSigned = true;
2597     return RHS->isAllOnesValue();
2598   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2599     TrueIfSigned = false;
2600     return RHS->isAllOnesValue();
2601   case ICmpInst::ICMP_UGT:
2602     // True if LHS u> RHS and RHS == high-bit-mask - 1
2603     TrueIfSigned = true;
2604     return RHS->getValue() ==
2605       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2606   case ICmpInst::ICMP_UGE: 
2607     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2608     TrueIfSigned = true;
2609     return RHS->getValue().isSignBit();
2610   default:
2611     return false;
2612   }
2613 }
2614
2615 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2616   bool Changed = SimplifyCommutative(I);
2617   Value *Op0 = I.getOperand(0);
2618
2619   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2620     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2621
2622   // Simplify mul instructions with a constant RHS...
2623   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2624     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2625
2626       // ((X << C1)*C2) == (X * (C2 << C1))
2627       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2628         if (SI->getOpcode() == Instruction::Shl)
2629           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2630             return BinaryOperator::CreateMul(SI->getOperand(0),
2631                                         ConstantExpr::getShl(CI, ShOp));
2632
2633       if (CI->isZero())
2634         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2635       if (CI->equalsInt(1))                  // X * 1  == X
2636         return ReplaceInstUsesWith(I, Op0);
2637       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2638         return BinaryOperator::CreateNeg(Op0, I.getName());
2639
2640       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2641       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2642         return BinaryOperator::CreateShl(Op0,
2643                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2644       }
2645     } else if (isa<VectorType>(Op1->getType())) {
2646       if (Op1->isNullValue())
2647         return ReplaceInstUsesWith(I, Op1);
2648
2649       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2650         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2651           return BinaryOperator::CreateNeg(Op0, I.getName());
2652
2653         // As above, vector X*splat(1.0) -> X in all defined cases.
2654         if (Constant *Splat = Op1V->getSplatValue()) {
2655           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2656             if (CI->equalsInt(1))
2657               return ReplaceInstUsesWith(I, Op0);
2658         }
2659       }
2660     }
2661     
2662     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2663       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2664           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2665         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2666         Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1, "tmp");
2667         Value *C1C2 = Builder->CreateMul(Op1, Op0I->getOperand(1));
2668         return BinaryOperator::CreateAdd(Add, C1C2);
2669         
2670       }
2671
2672     // Try to fold constant mul into select arguments.
2673     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2674       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2675         return R;
2676
2677     if (isa<PHINode>(Op0))
2678       if (Instruction *NV = FoldOpIntoPhi(I))
2679         return NV;
2680   }
2681
2682   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2683     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2684       return BinaryOperator::CreateMul(Op0v, Op1v);
2685
2686   // (X / Y) *  Y = X - (X % Y)
2687   // (X / Y) * -Y = (X % Y) - X
2688   {
2689     Value *Op1 = I.getOperand(1);
2690     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2691     if (!BO ||
2692         (BO->getOpcode() != Instruction::UDiv && 
2693          BO->getOpcode() != Instruction::SDiv)) {
2694       Op1 = Op0;
2695       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2696     }
2697     Value *Neg = dyn_castNegVal(Op1);
2698     if (BO && BO->hasOneUse() &&
2699         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2700         (BO->getOpcode() == Instruction::UDiv ||
2701          BO->getOpcode() == Instruction::SDiv)) {
2702       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2703
2704       // If the division is exact, X % Y is zero.
2705       if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2706         if (SDiv->isExact()) {
2707           if (Op1BO == Op1)
2708             return ReplaceInstUsesWith(I, Op0BO);
2709           else
2710             return BinaryOperator::CreateNeg(Op0BO);
2711         }
2712
2713       Value *Rem;
2714       if (BO->getOpcode() == Instruction::UDiv)
2715         Rem = Builder->CreateURem(Op0BO, Op1BO);
2716       else
2717         Rem = Builder->CreateSRem(Op0BO, Op1BO);
2718       Rem->takeName(BO);
2719
2720       if (Op1BO == Op1)
2721         return BinaryOperator::CreateSub(Op0BO, Rem);
2722       return BinaryOperator::CreateSub(Rem, Op0BO);
2723     }
2724   }
2725
2726   if (I.getType() == Type::getInt1Ty(*Context))
2727     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2728
2729   // If one of the operands of the multiply is a cast from a boolean value, then
2730   // we know the bool is either zero or one, so this is a 'masking' multiply.
2731   // See if we can simplify things based on how the boolean was originally
2732   // formed.
2733   CastInst *BoolCast = 0;
2734   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2735     if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2736       BoolCast = CI;
2737   if (!BoolCast)
2738     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2739       if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2740         BoolCast = CI;
2741   if (BoolCast) {
2742     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2743       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2744       const Type *SCOpTy = SCIOp0->getType();
2745       bool TIS = false;
2746       
2747       // If the icmp is true iff the sign bit of X is set, then convert this
2748       // multiply into a shift/and combination.
2749       if (isa<ConstantInt>(SCIOp1) &&
2750           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2751           TIS) {
2752         // Shift the X value right to turn it into "all signbits".
2753         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2754                                           SCOpTy->getPrimitiveSizeInBits()-1);
2755         Value *V = Builder->CreateAShr(SCIOp0, Amt,
2756                                     BoolCast->getOperand(0)->getName()+".mask");
2757
2758         // If the multiply type is not the same as the source type, sign extend
2759         // or truncate to the multiply type.
2760         if (I.getType() != V->getType())
2761           V = Builder->CreateIntCast(V, I.getType(), true);
2762
2763         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2764         return BinaryOperator::CreateAnd(V, OtherOp);
2765       }
2766     }
2767   }
2768
2769   return Changed ? &I : 0;
2770 }
2771
2772 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2773   bool Changed = SimplifyCommutative(I);
2774   Value *Op0 = I.getOperand(0);
2775
2776   // Simplify mul instructions with a constant RHS...
2777   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2778     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2779       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2780       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2781       if (Op1F->isExactlyValue(1.0))
2782         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2783     } else if (isa<VectorType>(Op1->getType())) {
2784       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2785         // As above, vector X*splat(1.0) -> X in all defined cases.
2786         if (Constant *Splat = Op1V->getSplatValue()) {
2787           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2788             if (F->isExactlyValue(1.0))
2789               return ReplaceInstUsesWith(I, Op0);
2790         }
2791       }
2792     }
2793
2794     // Try to fold constant mul into select arguments.
2795     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2796       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2797         return R;
2798
2799     if (isa<PHINode>(Op0))
2800       if (Instruction *NV = FoldOpIntoPhi(I))
2801         return NV;
2802   }
2803
2804   if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
2805     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
2806       return BinaryOperator::CreateFMul(Op0v, Op1v);
2807
2808   return Changed ? &I : 0;
2809 }
2810
2811 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2812 /// instruction.
2813 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2814   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2815   
2816   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2817   int NonNullOperand = -1;
2818   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2819     if (ST->isNullValue())
2820       NonNullOperand = 2;
2821   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2822   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2823     if (ST->isNullValue())
2824       NonNullOperand = 1;
2825   
2826   if (NonNullOperand == -1)
2827     return false;
2828   
2829   Value *SelectCond = SI->getOperand(0);
2830   
2831   // Change the div/rem to use 'Y' instead of the select.
2832   I.setOperand(1, SI->getOperand(NonNullOperand));
2833   
2834   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2835   // problem.  However, the select, or the condition of the select may have
2836   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2837   // propagate the known value for the select into other uses of it, and
2838   // propagate a known value of the condition into its other users.
2839   
2840   // If the select and condition only have a single use, don't bother with this,
2841   // early exit.
2842   if (SI->use_empty() && SelectCond->hasOneUse())
2843     return true;
2844   
2845   // Scan the current block backward, looking for other uses of SI.
2846   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2847   
2848   while (BBI != BBFront) {
2849     --BBI;
2850     // If we found a call to a function, we can't assume it will return, so
2851     // information from below it cannot be propagated above it.
2852     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2853       break;
2854     
2855     // Replace uses of the select or its condition with the known values.
2856     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2857          I != E; ++I) {
2858       if (*I == SI) {
2859         *I = SI->getOperand(NonNullOperand);
2860         Worklist.Add(BBI);
2861       } else if (*I == SelectCond) {
2862         *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2863                                    ConstantInt::getFalse(*Context);
2864         Worklist.Add(BBI);
2865       }
2866     }
2867     
2868     // If we past the instruction, quit looking for it.
2869     if (&*BBI == SI)
2870       SI = 0;
2871     if (&*BBI == SelectCond)
2872       SelectCond = 0;
2873     
2874     // If we ran out of things to eliminate, break out of the loop.
2875     if (SelectCond == 0 && SI == 0)
2876       break;
2877     
2878   }
2879   return true;
2880 }
2881
2882
2883 /// This function implements the transforms on div instructions that work
2884 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2885 /// used by the visitors to those instructions.
2886 /// @brief Transforms common to all three div instructions
2887 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2888   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2889
2890   // undef / X -> 0        for integer.
2891   // undef / X -> undef    for FP (the undef could be a snan).
2892   if (isa<UndefValue>(Op0)) {
2893     if (Op0->getType()->isFPOrFPVector())
2894       return ReplaceInstUsesWith(I, Op0);
2895     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2896   }
2897
2898   // X / undef -> undef
2899   if (isa<UndefValue>(Op1))
2900     return ReplaceInstUsesWith(I, Op1);
2901
2902   return 0;
2903 }
2904
2905 /// This function implements the transforms common to both integer division
2906 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2907 /// division instructions.
2908 /// @brief Common integer divide transforms
2909 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2910   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2911
2912   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2913   if (Op0 == Op1) {
2914     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2915       Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
2916       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2917       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2918     }
2919
2920     Constant *CI = ConstantInt::get(I.getType(), 1);
2921     return ReplaceInstUsesWith(I, CI);
2922   }
2923   
2924   if (Instruction *Common = commonDivTransforms(I))
2925     return Common;
2926   
2927   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2928   // This does not apply for fdiv.
2929   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2930     return &I;
2931
2932   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2933     // div X, 1 == X
2934     if (RHS->equalsInt(1))
2935       return ReplaceInstUsesWith(I, Op0);
2936
2937     // (X / C1) / C2  -> X / (C1*C2)
2938     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2939       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2940         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2941           if (MultiplyOverflows(RHS, LHSRHS,
2942                                 I.getOpcode()==Instruction::SDiv))
2943             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2944           else 
2945             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2946                                       ConstantExpr::getMul(RHS, LHSRHS));
2947         }
2948
2949     if (!RHS->isZero()) { // avoid X udiv 0
2950       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2951         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2952           return R;
2953       if (isa<PHINode>(Op0))
2954         if (Instruction *NV = FoldOpIntoPhi(I))
2955           return NV;
2956     }
2957   }
2958
2959   // 0 / X == 0, we don't need to preserve faults!
2960   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2961     if (LHS->equalsInt(0))
2962       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2963
2964   // It can't be division by zero, hence it must be division by one.
2965   if (I.getType() == Type::getInt1Ty(*Context))
2966     return ReplaceInstUsesWith(I, Op0);
2967
2968   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2969     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2970       // div X, 1 == X
2971       if (X->isOne())
2972         return ReplaceInstUsesWith(I, Op0);
2973   }
2974
2975   return 0;
2976 }
2977
2978 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2979   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2980
2981   // Handle the integer div common cases
2982   if (Instruction *Common = commonIDivTransforms(I))
2983     return Common;
2984
2985   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2986     // X udiv C^2 -> X >> C
2987     // Check to see if this is an unsigned division with an exact power of 2,
2988     // if so, convert to a right shift.
2989     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2990       return BinaryOperator::CreateLShr(Op0, 
2991             ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2992
2993     // X udiv C, where C >= signbit
2994     if (C->getValue().isNegative()) {
2995       Value *IC = Builder->CreateICmpULT( Op0, C);
2996       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2997                                 ConstantInt::get(I.getType(), 1));
2998     }
2999   }
3000
3001   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3002   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3003     if (RHSI->getOpcode() == Instruction::Shl &&
3004         isa<ConstantInt>(RHSI->getOperand(0))) {
3005       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3006       if (C1.isPowerOf2()) {
3007         Value *N = RHSI->getOperand(1);
3008         const Type *NTy = N->getType();
3009         if (uint32_t C2 = C1.logBase2())
3010           N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
3011         return BinaryOperator::CreateLShr(Op0, N);
3012       }
3013     }
3014   }
3015   
3016   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3017   // where C1&C2 are powers of two.
3018   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3019     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3020       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3021         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3022         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3023           // Compute the shift amounts
3024           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3025           // Construct the "on true" case of the select
3026           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3027           Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
3028   
3029           // Construct the "on false" case of the select
3030           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3031           Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
3032
3033           // construct the select instruction and return it.
3034           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3035         }
3036       }
3037   return 0;
3038 }
3039
3040 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3041   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3042
3043   // Handle the integer div common cases
3044   if (Instruction *Common = commonIDivTransforms(I))
3045     return Common;
3046
3047   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3048     // sdiv X, -1 == -X
3049     if (RHS->isAllOnesValue())
3050       return BinaryOperator::CreateNeg(Op0);
3051
3052     // sdiv X, C  -->  ashr X, log2(C)
3053     if (cast<SDivOperator>(&I)->isExact() &&
3054         RHS->getValue().isNonNegative() &&
3055         RHS->getValue().isPowerOf2()) {
3056       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3057                                             RHS->getValue().exactLogBase2());
3058       return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3059     }
3060
3061     // -X/C  -->  X/-C  provided the negation doesn't overflow.
3062     if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3063       if (isa<Constant>(Sub->getOperand(0)) &&
3064           cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3065           Sub->hasNoSignedWrap())
3066         return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3067                                           ConstantExpr::getNeg(RHS));
3068   }
3069
3070   // If the sign bits of both operands are zero (i.e. we can prove they are
3071   // unsigned inputs), turn this into a udiv.
3072   if (I.getType()->isInteger()) {
3073     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3074     if (MaskedValueIsZero(Op0, Mask)) {
3075       if (MaskedValueIsZero(Op1, Mask)) {
3076         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3077         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3078       }
3079       ConstantInt *ShiftedInt;
3080       if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3081           ShiftedInt->getValue().isPowerOf2()) {
3082         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3083         // Safe because the only negative value (1 << Y) can take on is
3084         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3085         // the sign bit set.
3086         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3087       }
3088     }
3089   }
3090   
3091   return 0;
3092 }
3093
3094 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3095   return commonDivTransforms(I);
3096 }
3097
3098 /// This function implements the transforms on rem instructions that work
3099 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3100 /// is used by the visitors to those instructions.
3101 /// @brief Transforms common to all three rem instructions
3102 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3103   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3104
3105   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3106     if (I.getType()->isFPOrFPVector())
3107       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3108     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3109   }
3110   if (isa<UndefValue>(Op1))
3111     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3112
3113   // Handle cases involving: rem X, (select Cond, Y, Z)
3114   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3115     return &I;
3116
3117   return 0;
3118 }
3119
3120 /// This function implements the transforms common to both integer remainder
3121 /// instructions (urem and srem). It is called by the visitors to those integer
3122 /// remainder instructions.
3123 /// @brief Common integer remainder transforms
3124 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3125   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3126
3127   if (Instruction *common = commonRemTransforms(I))
3128     return common;
3129
3130   // 0 % X == 0 for integer, we don't need to preserve faults!
3131   if (Constant *LHS = dyn_cast<Constant>(Op0))
3132     if (LHS->isNullValue())
3133       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3134
3135   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3136     // X % 0 == undef, we don't need to preserve faults!
3137     if (RHS->equalsInt(0))
3138       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3139     
3140     if (RHS->equalsInt(1))  // X % 1 == 0
3141       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3142
3143     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3144       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3145         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3146           return R;
3147       } else if (isa<PHINode>(Op0I)) {
3148         if (Instruction *NV = FoldOpIntoPhi(I))
3149           return NV;
3150       }
3151
3152       // See if we can fold away this rem instruction.
3153       if (SimplifyDemandedInstructionBits(I))
3154         return &I;
3155     }
3156   }
3157
3158   return 0;
3159 }
3160
3161 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3162   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3163
3164   if (Instruction *common = commonIRemTransforms(I))
3165     return common;
3166   
3167   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3168     // X urem C^2 -> X and C
3169     // Check to see if this is an unsigned remainder with an exact power of 2,
3170     // if so, convert to a bitwise and.
3171     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3172       if (C->getValue().isPowerOf2())
3173         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3174   }
3175
3176   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3177     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3178     if (RHSI->getOpcode() == Instruction::Shl &&
3179         isa<ConstantInt>(RHSI->getOperand(0))) {
3180       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3181         Constant *N1 = Constant::getAllOnesValue(I.getType());
3182         Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
3183         return BinaryOperator::CreateAnd(Op0, Add);
3184       }
3185     }
3186   }
3187
3188   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3189   // where C1&C2 are powers of two.
3190   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3191     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3192       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3193         // STO == 0 and SFO == 0 handled above.
3194         if ((STO->getValue().isPowerOf2()) && 
3195             (SFO->getValue().isPowerOf2())) {
3196           Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3197                                               SI->getName()+".t");
3198           Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3199                                                SI->getName()+".f");
3200           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3201         }
3202       }
3203   }
3204   
3205   return 0;
3206 }
3207
3208 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3209   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3210
3211   // Handle the integer rem common cases
3212   if (Instruction *Common = commonIRemTransforms(I))
3213     return Common;
3214   
3215   if (Value *RHSNeg = dyn_castNegVal(Op1))
3216     if (!isa<Constant>(RHSNeg) ||
3217         (isa<ConstantInt>(RHSNeg) &&
3218          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3219       // X % -Y -> X % Y
3220       Worklist.AddValue(I.getOperand(1));
3221       I.setOperand(1, RHSNeg);
3222       return &I;
3223     }
3224
3225   // If the sign bits of both operands are zero (i.e. we can prove they are
3226   // unsigned inputs), turn this into a urem.
3227   if (I.getType()->isInteger()) {
3228     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3229     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3230       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3231       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3232     }
3233   }
3234
3235   // If it's a constant vector, flip any negative values positive.
3236   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3237     unsigned VWidth = RHSV->getNumOperands();
3238
3239     bool hasNegative = false;
3240     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3241       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3242         if (RHS->getValue().isNegative())
3243           hasNegative = true;
3244
3245     if (hasNegative) {
3246       std::vector<Constant *> Elts(VWidth);
3247       for (unsigned i = 0; i != VWidth; ++i) {
3248         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3249           if (RHS->getValue().isNegative())
3250             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3251           else
3252             Elts[i] = RHS;
3253         }
3254       }
3255
3256       Constant *NewRHSV = ConstantVector::get(Elts);
3257       if (NewRHSV != RHSV) {
3258         Worklist.AddValue(I.getOperand(1));
3259         I.setOperand(1, NewRHSV);
3260         return &I;
3261       }
3262     }
3263   }
3264
3265   return 0;
3266 }
3267
3268 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3269   return commonRemTransforms(I);
3270 }
3271
3272 // isOneBitSet - Return true if there is exactly one bit set in the specified
3273 // constant.
3274 static bool isOneBitSet(const ConstantInt *CI) {
3275   return CI->getValue().isPowerOf2();
3276 }
3277
3278 // isHighOnes - Return true if the constant is of the form 1+0+.
3279 // This is the same as lowones(~X).
3280 static bool isHighOnes(const ConstantInt *CI) {
3281   return (~CI->getValue() + 1).isPowerOf2();
3282 }
3283
3284 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3285 /// are carefully arranged to allow folding of expressions such as:
3286 ///
3287 ///      (A < B) | (A > B) --> (A != B)
3288 ///
3289 /// Note that this is only valid if the first and second predicates have the
3290 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3291 ///
3292 /// Three bits are used to represent the condition, as follows:
3293 ///   0  A > B
3294 ///   1  A == B
3295 ///   2  A < B
3296 ///
3297 /// <=>  Value  Definition
3298 /// 000     0   Always false
3299 /// 001     1   A >  B
3300 /// 010     2   A == B
3301 /// 011     3   A >= B
3302 /// 100     4   A <  B
3303 /// 101     5   A != B
3304 /// 110     6   A <= B
3305 /// 111     7   Always true
3306 ///  
3307 static unsigned getICmpCode(const ICmpInst *ICI) {
3308   switch (ICI->getPredicate()) {
3309     // False -> 0
3310   case ICmpInst::ICMP_UGT: return 1;  // 001
3311   case ICmpInst::ICMP_SGT: return 1;  // 001
3312   case ICmpInst::ICMP_EQ:  return 2;  // 010
3313   case ICmpInst::ICMP_UGE: return 3;  // 011
3314   case ICmpInst::ICMP_SGE: return 3;  // 011
3315   case ICmpInst::ICMP_ULT: return 4;  // 100
3316   case ICmpInst::ICMP_SLT: return 4;  // 100
3317   case ICmpInst::ICMP_NE:  return 5;  // 101
3318   case ICmpInst::ICMP_ULE: return 6;  // 110
3319   case ICmpInst::ICMP_SLE: return 6;  // 110
3320     // True -> 7
3321   default:
3322     llvm_unreachable("Invalid ICmp predicate!");
3323     return 0;
3324   }
3325 }
3326
3327 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3328 /// predicate into a three bit mask. It also returns whether it is an ordered
3329 /// predicate by reference.
3330 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3331   isOrdered = false;
3332   switch (CC) {
3333   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3334   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3335   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3336   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3337   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3338   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3339   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3340   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3341   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3342   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3343   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3344   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3345   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3346   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3347     // True -> 7
3348   default:
3349     // Not expecting FCMP_FALSE and FCMP_TRUE;
3350     llvm_unreachable("Unexpected FCmp predicate!");
3351     return 0;
3352   }
3353 }
3354
3355 /// getICmpValue - This is the complement of getICmpCode, which turns an
3356 /// opcode and two operands into either a constant true or false, or a brand 
3357 /// new ICmp instruction. The sign is passed in to determine which kind
3358 /// of predicate to use in the new icmp instruction.
3359 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3360                            LLVMContext *Context) {
3361   switch (code) {
3362   default: llvm_unreachable("Illegal ICmp code!");
3363   case  0: return ConstantInt::getFalse(*Context);
3364   case  1: 
3365     if (sign)
3366       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3367     else
3368       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3369   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3370   case  3: 
3371     if (sign)
3372       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3373     else
3374       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3375   case  4: 
3376     if (sign)
3377       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3378     else
3379       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3380   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3381   case  6: 
3382     if (sign)
3383       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3384     else
3385       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3386   case  7: return ConstantInt::getTrue(*Context);
3387   }
3388 }
3389
3390 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3391 /// opcode and two operands into either a FCmp instruction. isordered is passed
3392 /// in to determine which kind of predicate to use in the new fcmp instruction.
3393 static Value *getFCmpValue(bool isordered, unsigned code,
3394                            Value *LHS, Value *RHS, LLVMContext *Context) {
3395   switch (code) {
3396   default: llvm_unreachable("Illegal FCmp code!");
3397   case  0:
3398     if (isordered)
3399       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3400     else
3401       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3402   case  1: 
3403     if (isordered)
3404       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3405     else
3406       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3407   case  2: 
3408     if (isordered)
3409       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3410     else
3411       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3412   case  3: 
3413     if (isordered)
3414       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3415     else
3416       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3417   case  4: 
3418     if (isordered)
3419       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3420     else
3421       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3422   case  5: 
3423     if (isordered)
3424       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3425     else
3426       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3427   case  6: 
3428     if (isordered)
3429       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3430     else
3431       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3432   case  7: return ConstantInt::getTrue(*Context);
3433   }
3434 }
3435
3436 /// PredicatesFoldable - Return true if both predicates match sign or if at
3437 /// least one of them is an equality comparison (which is signless).
3438 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3439   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3440          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3441          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3442 }
3443
3444 namespace { 
3445 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3446 struct FoldICmpLogical {
3447   InstCombiner &IC;
3448   Value *LHS, *RHS;
3449   ICmpInst::Predicate pred;
3450   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3451     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3452       pred(ICI->getPredicate()) {}
3453   bool shouldApply(Value *V) const {
3454     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3455       if (PredicatesFoldable(pred, ICI->getPredicate()))
3456         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3457                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3458     return false;
3459   }
3460   Instruction *apply(Instruction &Log) const {
3461     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3462     if (ICI->getOperand(0) != LHS) {
3463       assert(ICI->getOperand(1) == LHS);
3464       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3465     }
3466
3467     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3468     unsigned LHSCode = getICmpCode(ICI);
3469     unsigned RHSCode = getICmpCode(RHSICI);
3470     unsigned Code;
3471     switch (Log.getOpcode()) {
3472     case Instruction::And: Code = LHSCode & RHSCode; break;
3473     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3474     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3475     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3476     }
3477
3478     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3479                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3480       
3481     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3482     if (Instruction *I = dyn_cast<Instruction>(RV))
3483       return I;
3484     // Otherwise, it's a constant boolean value...
3485     return IC.ReplaceInstUsesWith(Log, RV);
3486   }
3487 };
3488 } // end anonymous namespace
3489
3490 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3491 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3492 // guaranteed to be a binary operator.
3493 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3494                                     ConstantInt *OpRHS,
3495                                     ConstantInt *AndRHS,
3496                                     BinaryOperator &TheAnd) {
3497   Value *X = Op->getOperand(0);
3498   Constant *Together = 0;
3499   if (!Op->isShift())
3500     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3501
3502   switch (Op->getOpcode()) {
3503   case Instruction::Xor:
3504     if (Op->hasOneUse()) {
3505       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3506       Value *And = Builder->CreateAnd(X, AndRHS);
3507       And->takeName(Op);
3508       return BinaryOperator::CreateXor(And, Together);
3509     }
3510     break;
3511   case Instruction::Or:
3512     if (Together == AndRHS) // (X | C) & C --> C
3513       return ReplaceInstUsesWith(TheAnd, AndRHS);
3514
3515     if (Op->hasOneUse() && Together != OpRHS) {
3516       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3517       Value *Or = Builder->CreateOr(X, Together);
3518       Or->takeName(Op);
3519       return BinaryOperator::CreateAnd(Or, AndRHS);
3520     }
3521     break;
3522   case Instruction::Add:
3523     if (Op->hasOneUse()) {
3524       // Adding a one to a single bit bit-field should be turned into an XOR
3525       // of the bit.  First thing to check is to see if this AND is with a
3526       // single bit constant.
3527       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3528
3529       // If there is only one bit set...
3530       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3531         // Ok, at this point, we know that we are masking the result of the
3532         // ADD down to exactly one bit.  If the constant we are adding has
3533         // no bits set below this bit, then we can eliminate the ADD.
3534         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3535
3536         // Check to see if any bits below the one bit set in AndRHSV are set.
3537         if ((AddRHS & (AndRHSV-1)) == 0) {
3538           // If not, the only thing that can effect the output of the AND is
3539           // the bit specified by AndRHSV.  If that bit is set, the effect of
3540           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3541           // no effect.
3542           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3543             TheAnd.setOperand(0, X);
3544             return &TheAnd;
3545           } else {
3546             // Pull the XOR out of the AND.
3547             Value *NewAnd = Builder->CreateAnd(X, AndRHS);
3548             NewAnd->takeName(Op);
3549             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3550           }
3551         }
3552       }
3553     }
3554     break;
3555
3556   case Instruction::Shl: {
3557     // We know that the AND will not produce any of the bits shifted in, so if
3558     // the anded constant includes them, clear them now!
3559     //
3560     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3561     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3562     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3563     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3564
3565     if (CI->getValue() == ShlMask) { 
3566     // Masking out bits that the shift already masks
3567       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3568     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3569       TheAnd.setOperand(1, CI);
3570       return &TheAnd;
3571     }
3572     break;
3573   }
3574   case Instruction::LShr:
3575   {
3576     // We know that the AND will not produce any of the bits shifted in, so if
3577     // the anded constant includes them, clear them now!  This only applies to
3578     // unsigned shifts, because a signed shr may bring in set bits!
3579     //
3580     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3581     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3582     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3583     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3584
3585     if (CI->getValue() == ShrMask) {   
3586     // Masking out bits that the shift already masks.
3587       return ReplaceInstUsesWith(TheAnd, Op);
3588     } else if (CI != AndRHS) {
3589       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3590       return &TheAnd;
3591     }
3592     break;
3593   }
3594   case Instruction::AShr:
3595     // Signed shr.
3596     // See if this is shifting in some sign extension, then masking it out
3597     // with an and.
3598     if (Op->hasOneUse()) {
3599       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3600       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3601       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3602       Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3603       if (C == AndRHS) {          // Masking out bits shifted in.
3604         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3605         // Make the argument unsigned.
3606         Value *ShVal = Op->getOperand(0);
3607         ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
3608         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3609       }
3610     }
3611     break;
3612   }
3613   return 0;
3614 }
3615
3616
3617 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3618 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3619 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3620 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3621 /// insert new instructions.
3622 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3623                                            bool isSigned, bool Inside, 
3624                                            Instruction &IB) {
3625   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3626             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3627          "Lo is not <= Hi in range emission code!");
3628     
3629   if (Inside) {
3630     if (Lo == Hi)  // Trivially false.
3631       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3632
3633     // V >= Min && V < Hi --> V < Hi
3634     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3635       ICmpInst::Predicate pred = (isSigned ? 
3636         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3637       return new ICmpInst(pred, V, Hi);
3638     }
3639
3640     // Emit V-Lo <u Hi-Lo
3641     Constant *NegLo = ConstantExpr::getNeg(Lo);
3642     Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3643     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3644     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3645   }
3646
3647   if (Lo == Hi)  // Trivially true.
3648     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3649
3650   // V < Min || V >= Hi -> V > Hi-1
3651   Hi = SubOne(cast<ConstantInt>(Hi));
3652   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3653     ICmpInst::Predicate pred = (isSigned ? 
3654         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3655     return new ICmpInst(pred, V, Hi);
3656   }
3657
3658   // Emit V-Lo >u Hi-1-Lo
3659   // Note that Hi has already had one subtracted from it, above.
3660   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3661   Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3662   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3663   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3664 }
3665
3666 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3667 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3668 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3669 // not, since all 1s are not contiguous.
3670 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3671   const APInt& V = Val->getValue();
3672   uint32_t BitWidth = Val->getType()->getBitWidth();
3673   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3674
3675   // look for the first zero bit after the run of ones
3676   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3677   // look for the first non-zero bit
3678   ME = V.getActiveBits(); 
3679   return true;
3680 }
3681
3682 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3683 /// where isSub determines whether the operator is a sub.  If we can fold one of
3684 /// the following xforms:
3685 /// 
3686 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3687 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3688 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3689 ///
3690 /// return (A +/- B).
3691 ///
3692 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3693                                         ConstantInt *Mask, bool isSub,
3694                                         Instruction &I) {
3695   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3696   if (!LHSI || LHSI->getNumOperands() != 2 ||
3697       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3698
3699   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3700
3701   switch (LHSI->getOpcode()) {
3702   default: return 0;
3703   case Instruction::And:
3704     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3705       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3706       if ((Mask->getValue().countLeadingZeros() + 
3707            Mask->getValue().countPopulation()) == 
3708           Mask->getValue().getBitWidth())
3709         break;
3710
3711       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3712       // part, we don't need any explicit masks to take them out of A.  If that
3713       // is all N is, ignore it.
3714       uint32_t MB = 0, ME = 0;
3715       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3716         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3717         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3718         if (MaskedValueIsZero(RHS, Mask))
3719           break;
3720       }
3721     }
3722     return 0;
3723   case Instruction::Or:
3724   case Instruction::Xor:
3725     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3726     if ((Mask->getValue().countLeadingZeros() + 
3727          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3728         && ConstantExpr::getAnd(N, Mask)->isNullValue())
3729       break;
3730     return 0;
3731   }
3732   
3733   if (isSub)
3734     return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3735   return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
3736 }
3737
3738 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3739 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3740                                           ICmpInst *LHS, ICmpInst *RHS) {
3741   Value *Val, *Val2;
3742   ConstantInt *LHSCst, *RHSCst;
3743   ICmpInst::Predicate LHSCC, RHSCC;
3744   
3745   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3746   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3747                          m_ConstantInt(LHSCst))) ||
3748       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3749                          m_ConstantInt(RHSCst))))
3750     return 0;
3751   
3752   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3753   // where C is a power of 2
3754   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3755       LHSCst->getValue().isPowerOf2()) {
3756     Value *NewOr = Builder->CreateOr(Val, Val2);
3757     return new ICmpInst(LHSCC, NewOr, LHSCst);
3758   }
3759   
3760   // From here on, we only handle:
3761   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3762   if (Val != Val2) return 0;
3763   
3764   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3765   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3766       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3767       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3768       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3769     return 0;
3770   
3771   // We can't fold (ugt x, C) & (sgt x, C2).
3772   if (!PredicatesFoldable(LHSCC, RHSCC))
3773     return 0;
3774     
3775   // Ensure that the larger constant is on the RHS.
3776   bool ShouldSwap;
3777   if (ICmpInst::isSignedPredicate(LHSCC) ||
3778       (ICmpInst::isEquality(LHSCC) && 
3779        ICmpInst::isSignedPredicate(RHSCC)))
3780     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3781   else
3782     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3783     
3784   if (ShouldSwap) {
3785     std::swap(LHS, RHS);
3786     std::swap(LHSCst, RHSCst);
3787     std::swap(LHSCC, RHSCC);
3788   }
3789
3790   // At this point, we know we have have two icmp instructions
3791   // comparing a value against two constants and and'ing the result
3792   // together.  Because of the above check, we know that we only have
3793   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3794   // (from the FoldICmpLogical check above), that the two constants 
3795   // are not equal and that the larger constant is on the RHS
3796   assert(LHSCst != RHSCst && "Compares not folded above?");
3797
3798   switch (LHSCC) {
3799   default: llvm_unreachable("Unknown integer condition code!");
3800   case ICmpInst::ICMP_EQ:
3801     switch (RHSCC) {
3802     default: llvm_unreachable("Unknown integer condition code!");
3803     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3804     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3805     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3806       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3807     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3808     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3809     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3810       return ReplaceInstUsesWith(I, LHS);
3811     }
3812   case ICmpInst::ICMP_NE:
3813     switch (RHSCC) {
3814     default: llvm_unreachable("Unknown integer condition code!");
3815     case ICmpInst::ICMP_ULT:
3816       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3817         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3818       break;                        // (X != 13 & X u< 15) -> no change
3819     case ICmpInst::ICMP_SLT:
3820       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3821         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3822       break;                        // (X != 13 & X s< 15) -> no change
3823     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3824     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3825     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3826       return ReplaceInstUsesWith(I, RHS);
3827     case ICmpInst::ICMP_NE:
3828       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3829         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3830         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
3831         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3832                             ConstantInt::get(Add->getType(), 1));
3833       }
3834       break;                        // (X != 13 & X != 15) -> no change
3835     }
3836     break;
3837   case ICmpInst::ICMP_ULT:
3838     switch (RHSCC) {
3839     default: llvm_unreachable("Unknown integer condition code!");
3840     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3841     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3842       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3843     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3844       break;
3845     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3846     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3847       return ReplaceInstUsesWith(I, LHS);
3848     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3849       break;
3850     }
3851     break;
3852   case ICmpInst::ICMP_SLT:
3853     switch (RHSCC) {
3854     default: llvm_unreachable("Unknown integer condition code!");
3855     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3856     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3857       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3858     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3859       break;
3860     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3861     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3862       return ReplaceInstUsesWith(I, LHS);
3863     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3864       break;
3865     }
3866     break;
3867   case ICmpInst::ICMP_UGT:
3868     switch (RHSCC) {
3869     default: llvm_unreachable("Unknown integer condition code!");
3870     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3871     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3872       return ReplaceInstUsesWith(I, RHS);
3873     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3874       break;
3875     case ICmpInst::ICMP_NE:
3876       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3877         return new ICmpInst(LHSCC, Val, RHSCst);
3878       break;                        // (X u> 13 & X != 15) -> no change
3879     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3880       return InsertRangeTest(Val, AddOne(LHSCst),
3881                              RHSCst, false, true, I);
3882     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3883       break;
3884     }
3885     break;
3886   case ICmpInst::ICMP_SGT:
3887     switch (RHSCC) {
3888     default: llvm_unreachable("Unknown integer condition code!");
3889     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3890     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3891       return ReplaceInstUsesWith(I, RHS);
3892     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3893       break;
3894     case ICmpInst::ICMP_NE:
3895       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3896         return new ICmpInst(LHSCC, Val, RHSCst);
3897       break;                        // (X s> 13 & X != 15) -> no change
3898     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3899       return InsertRangeTest(Val, AddOne(LHSCst),
3900                              RHSCst, true, true, I);
3901     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3902       break;
3903     }
3904     break;
3905   }
3906  
3907   return 0;
3908 }
3909
3910 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3911                                           FCmpInst *RHS) {
3912   
3913   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3914       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3915     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3916     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3917       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3918         // If either of the constants are nans, then the whole thing returns
3919         // false.
3920         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3921           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3922         return new FCmpInst(FCmpInst::FCMP_ORD,
3923                             LHS->getOperand(0), RHS->getOperand(0));
3924       }
3925     
3926     // Handle vector zeros.  This occurs because the canonical form of
3927     // "fcmp ord x,x" is "fcmp ord x, 0".
3928     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3929         isa<ConstantAggregateZero>(RHS->getOperand(1)))
3930       return new FCmpInst(FCmpInst::FCMP_ORD,
3931                           LHS->getOperand(0), RHS->getOperand(0));
3932     return 0;
3933   }
3934   
3935   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3936   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3937   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3938   
3939   
3940   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3941     // Swap RHS operands to match LHS.
3942     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3943     std::swap(Op1LHS, Op1RHS);
3944   }
3945   
3946   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3947     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3948     if (Op0CC == Op1CC)
3949       return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
3950     
3951     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
3952       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3953     if (Op0CC == FCmpInst::FCMP_TRUE)
3954       return ReplaceInstUsesWith(I, RHS);
3955     if (Op1CC == FCmpInst::FCMP_TRUE)
3956       return ReplaceInstUsesWith(I, LHS);
3957     
3958     bool Op0Ordered;
3959     bool Op1Ordered;
3960     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3961     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3962     if (Op1Pred == 0) {
3963       std::swap(LHS, RHS);
3964       std::swap(Op0Pred, Op1Pred);
3965       std::swap(Op0Ordered, Op1Ordered);
3966     }
3967     if (Op0Pred == 0) {
3968       // uno && ueq -> uno && (uno || eq) -> ueq
3969       // ord && olt -> ord && (ord && lt) -> olt
3970       if (Op0Ordered == Op1Ordered)
3971         return ReplaceInstUsesWith(I, RHS);
3972       
3973       // uno && oeq -> uno && (ord && eq) -> false
3974       // uno && ord -> false
3975       if (!Op0Ordered)
3976         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3977       // ord && ueq -> ord && (uno || eq) -> oeq
3978       return cast<Instruction>(getFCmpValue(true, Op1Pred,
3979                                             Op0LHS, Op0RHS, Context));
3980     }
3981   }
3982
3983   return 0;
3984 }
3985
3986
3987 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3988   bool Changed = SimplifyCommutative(I);
3989   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3990
3991   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3992     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3993
3994   // and X, X = X
3995   if (Op0 == Op1)
3996     return ReplaceInstUsesWith(I, Op1);
3997
3998   // See if we can simplify any instructions used by the instruction whose sole 
3999   // purpose is to compute bits we don't care about.
4000   if (SimplifyDemandedInstructionBits(I))
4001     return &I;
4002   if (isa<VectorType>(I.getType())) {
4003     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4004       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
4005         return ReplaceInstUsesWith(I, I.getOperand(0));
4006     } else if (isa<ConstantAggregateZero>(Op1)) {
4007       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
4008     }
4009   }
4010
4011   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4012     const APInt& AndRHSMask = AndRHS->getValue();
4013     APInt NotAndRHS(~AndRHSMask);
4014
4015     // Optimize a variety of ((val OP C1) & C2) combinations...
4016     if (isa<BinaryOperator>(Op0)) {
4017       Instruction *Op0I = cast<Instruction>(Op0);
4018       Value *Op0LHS = Op0I->getOperand(0);
4019       Value *Op0RHS = Op0I->getOperand(1);
4020       switch (Op0I->getOpcode()) {
4021       case Instruction::Xor:
4022       case Instruction::Or:
4023         // If the mask is only needed on one incoming arm, push it up.
4024         if (Op0I->hasOneUse()) {
4025           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4026             // Not masking anything out for the LHS, move to RHS.
4027             Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4028                                                Op0RHS->getName()+".masked");
4029             return BinaryOperator::Create(
4030                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4031           }
4032           if (!isa<Constant>(Op0RHS) &&
4033               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4034             // Not masking anything out for the RHS, move to LHS.
4035             Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4036                                                Op0LHS->getName()+".masked");
4037             return BinaryOperator::Create(
4038                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4039           }
4040         }
4041
4042         break;
4043       case Instruction::Add:
4044         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4045         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4046         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4047         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4048           return BinaryOperator::CreateAnd(V, AndRHS);
4049         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4050           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4051         break;
4052
4053       case Instruction::Sub:
4054         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4055         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4056         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4057         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4058           return BinaryOperator::CreateAnd(V, AndRHS);
4059
4060         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4061         // has 1's for all bits that the subtraction with A might affect.
4062         if (Op0I->hasOneUse()) {
4063           uint32_t BitWidth = AndRHSMask.getBitWidth();
4064           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4065           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4066
4067           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4068           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4069               MaskedValueIsZero(Op0LHS, Mask)) {
4070             Value *NewNeg = Builder->CreateNeg(Op0RHS);
4071             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4072           }
4073         }
4074         break;
4075
4076       case Instruction::Shl:
4077       case Instruction::LShr:
4078         // (1 << x) & 1 --> zext(x == 0)
4079         // (1 >> x) & 1 --> zext(x == 0)
4080         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4081           Value *NewICmp =
4082             Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
4083           return new ZExtInst(NewICmp, I.getType());
4084         }
4085         break;
4086       }
4087
4088       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4089         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4090           return Res;
4091     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4092       // If this is an integer truncation or change from signed-to-unsigned, and
4093       // if the source is an and/or with immediate, transform it.  This
4094       // frequently occurs for bitfield accesses.
4095       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4096         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4097             CastOp->getNumOperands() == 2)
4098           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4099             if (CastOp->getOpcode() == Instruction::And) {
4100               // Change: and (cast (and X, C1) to T), C2
4101               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4102               // This will fold the two constants together, which may allow 
4103               // other simplifications.
4104               Value *NewCast = Builder->CreateTruncOrBitCast(
4105                 CastOp->getOperand(0), I.getType(), 
4106                 CastOp->getName()+".shrunk");
4107               // trunc_or_bitcast(C1)&C2
4108               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4109               C3 = ConstantExpr::getAnd(C3, AndRHS);
4110               return BinaryOperator::CreateAnd(NewCast, C3);
4111             } else if (CastOp->getOpcode() == Instruction::Or) {
4112               // Change: and (cast (or X, C1) to T), C2
4113               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4114               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4115               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4116                 // trunc(C1)&C2
4117                 return ReplaceInstUsesWith(I, AndRHS);
4118             }
4119           }
4120       }
4121     }
4122
4123     // Try to fold constant and into select arguments.
4124     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4125       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4126         return R;
4127     if (isa<PHINode>(Op0))
4128       if (Instruction *NV = FoldOpIntoPhi(I))
4129         return NV;
4130   }
4131
4132   Value *Op0NotVal = dyn_castNotVal(Op0);
4133   Value *Op1NotVal = dyn_castNotVal(Op1);
4134
4135   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4136     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4137
4138   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4139   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4140     Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4141                                   I.getName()+".demorgan");
4142     return BinaryOperator::CreateNot(Or);
4143   }
4144   
4145   {
4146     Value *A = 0, *B = 0, *C = 0, *D = 0;
4147     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4148       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4149         return ReplaceInstUsesWith(I, Op1);
4150     
4151       // (A|B) & ~(A&B) -> A^B
4152       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4153         if ((A == C && B == D) || (A == D && B == C))
4154           return BinaryOperator::CreateXor(A, B);
4155       }
4156     }
4157     
4158     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4159       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4160         return ReplaceInstUsesWith(I, Op0);
4161
4162       // ~(A&B) & (A|B) -> A^B
4163       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4164         if ((A == C && B == D) || (A == D && B == C))
4165           return BinaryOperator::CreateXor(A, B);
4166       }
4167     }
4168     
4169     if (Op0->hasOneUse() &&
4170         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4171       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4172         I.swapOperands();     // Simplify below
4173         std::swap(Op0, Op1);
4174       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4175         cast<BinaryOperator>(Op0)->swapOperands();
4176         I.swapOperands();     // Simplify below
4177         std::swap(Op0, Op1);
4178       }
4179     }
4180
4181     if (Op1->hasOneUse() &&
4182         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4183       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4184         cast<BinaryOperator>(Op1)->swapOperands();
4185         std::swap(A, B);
4186       }
4187       if (A == Op0)                                // A&(A^B) -> A & ~B
4188         return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
4189     }
4190
4191     // (A&((~A)|B)) -> A&B
4192     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4193         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4194       return BinaryOperator::CreateAnd(A, Op1);
4195     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4196         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4197       return BinaryOperator::CreateAnd(A, Op0);
4198   }
4199   
4200   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4201     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4202     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4203       return R;
4204
4205     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4206       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4207         return Res;
4208   }
4209
4210   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4211   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4212     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4213       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4214         const Type *SrcTy = Op0C->getOperand(0)->getType();
4215         if (SrcTy == Op1C->getOperand(0)->getType() &&
4216             SrcTy->isIntOrIntVector() &&
4217             // Only do this if the casts both really cause code to be generated.
4218             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4219                               I.getType(), TD) &&
4220             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4221                               I.getType(), TD)) {
4222           Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4223                                             Op1C->getOperand(0), I.getName());
4224           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4225         }
4226       }
4227     
4228   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4229   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4230     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4231       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4232           SI0->getOperand(1) == SI1->getOperand(1) &&
4233           (SI0->hasOneUse() || SI1->hasOneUse())) {
4234         Value *NewOp =
4235           Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4236                              SI0->getName());
4237         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4238                                       SI1->getOperand(1));
4239       }
4240   }
4241
4242   // If and'ing two fcmp, try combine them into one.
4243   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4244     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4245       if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4246         return Res;
4247   }
4248
4249   return Changed ? &I : 0;
4250 }
4251
4252 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4253 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4254 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4255 /// the expression came from the corresponding "byte swapped" byte in some other
4256 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4257 /// we know that the expression deposits the low byte of %X into the high byte
4258 /// of the bswap result and that all other bytes are zero.  This expression is
4259 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4260 /// match.
4261 ///
4262 /// This function returns true if the match was unsuccessful and false if so.
4263 /// On entry to the function the "OverallLeftShift" is a signed integer value
4264 /// indicating the number of bytes that the subexpression is later shifted.  For
4265 /// example, if the expression is later right shifted by 16 bits, the
4266 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4267 /// byte of ByteValues is actually being set.
4268 ///
4269 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4270 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4271 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4272 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4273 /// always in the local (OverallLeftShift) coordinate space.
4274 ///
4275 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4276                               SmallVector<Value*, 8> &ByteValues) {
4277   if (Instruction *I = dyn_cast<Instruction>(V)) {
4278     // If this is an or instruction, it may be an inner node of the bswap.
4279     if (I->getOpcode() == Instruction::Or) {
4280       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4281                                ByteValues) ||
4282              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4283                                ByteValues);
4284     }
4285   
4286     // If this is a logical shift by a constant multiple of 8, recurse with
4287     // OverallLeftShift and ByteMask adjusted.
4288     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4289       unsigned ShAmt = 
4290         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4291       // Ensure the shift amount is defined and of a byte value.
4292       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4293         return true;
4294
4295       unsigned ByteShift = ShAmt >> 3;
4296       if (I->getOpcode() == Instruction::Shl) {
4297         // X << 2 -> collect(X, +2)
4298         OverallLeftShift += ByteShift;
4299         ByteMask >>= ByteShift;
4300       } else {
4301         // X >>u 2 -> collect(X, -2)
4302         OverallLeftShift -= ByteShift;
4303         ByteMask <<= ByteShift;
4304         ByteMask &= (~0U >> (32-ByteValues.size()));
4305       }
4306
4307       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4308       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4309
4310       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4311                                ByteValues);
4312     }
4313
4314     // If this is a logical 'and' with a mask that clears bytes, clear the
4315     // corresponding bytes in ByteMask.
4316     if (I->getOpcode() == Instruction::And &&
4317         isa<ConstantInt>(I->getOperand(1))) {
4318       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4319       unsigned NumBytes = ByteValues.size();
4320       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4321       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4322       
4323       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4324         // If this byte is masked out by a later operation, we don't care what
4325         // the and mask is.
4326         if ((ByteMask & (1 << i)) == 0)
4327           continue;
4328         
4329         // If the AndMask is all zeros for this byte, clear the bit.
4330         APInt MaskB = AndMask & Byte;
4331         if (MaskB == 0) {
4332           ByteMask &= ~(1U << i);
4333           continue;
4334         }
4335         
4336         // If the AndMask is not all ones for this byte, it's not a bytezap.
4337         if (MaskB != Byte)
4338           return true;
4339
4340         // Otherwise, this byte is kept.
4341       }
4342
4343       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4344                                ByteValues);
4345     }
4346   }
4347   
4348   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4349   // the input value to the bswap.  Some observations: 1) if more than one byte
4350   // is demanded from this input, then it could not be successfully assembled
4351   // into a byteswap.  At least one of the two bytes would not be aligned with
4352   // their ultimate destination.
4353   if (!isPowerOf2_32(ByteMask)) return true;
4354   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4355   
4356   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4357   // is demanded, it needs to go into byte 0 of the result.  This means that the
4358   // byte needs to be shifted until it lands in the right byte bucket.  The
4359   // shift amount depends on the position: if the byte is coming from the high
4360   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4361   // low part, it must be shifted left.
4362   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4363   if (InputByteNo < ByteValues.size()/2) {
4364     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4365       return true;
4366   } else {
4367     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4368       return true;
4369   }
4370   
4371   // If the destination byte value is already defined, the values are or'd
4372   // together, which isn't a bswap (unless it's an or of the same bits).
4373   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4374     return true;
4375   ByteValues[DestByteNo] = V;
4376   return false;
4377 }
4378
4379 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4380 /// If so, insert the new bswap intrinsic and return it.
4381 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4382   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4383   if (!ITy || ITy->getBitWidth() % 16 || 
4384       // ByteMask only allows up to 32-byte values.
4385       ITy->getBitWidth() > 32*8) 
4386     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4387   
4388   /// ByteValues - For each byte of the result, we keep track of which value
4389   /// defines each byte.
4390   SmallVector<Value*, 8> ByteValues;
4391   ByteValues.resize(ITy->getBitWidth()/8);
4392     
4393   // Try to find all the pieces corresponding to the bswap.
4394   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4395   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4396     return 0;
4397   
4398   // Check to see if all of the bytes come from the same value.
4399   Value *V = ByteValues[0];
4400   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4401   
4402   // Check to make sure that all of the bytes come from the same value.
4403   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4404     if (ByteValues[i] != V)
4405       return 0;
4406   const Type *Tys[] = { ITy };
4407   Module *M = I.getParent()->getParent()->getParent();
4408   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4409   return CallInst::Create(F, V);
4410 }
4411
4412 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4413 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4414 /// we can simplify this expression to "cond ? C : D or B".
4415 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4416                                          Value *C, Value *D,
4417                                          LLVMContext *Context) {
4418   // If A is not a select of -1/0, this cannot match.
4419   Value *Cond = 0;
4420   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4421     return 0;
4422
4423   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4424   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4425     return SelectInst::Create(Cond, C, B);
4426   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4427     return SelectInst::Create(Cond, C, B);
4428   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4429   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4430     return SelectInst::Create(Cond, C, D);
4431   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4432     return SelectInst::Create(Cond, C, D);
4433   return 0;
4434 }
4435
4436 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4437 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4438                                          ICmpInst *LHS, ICmpInst *RHS) {
4439   Value *Val, *Val2;
4440   ConstantInt *LHSCst, *RHSCst;
4441   ICmpInst::Predicate LHSCC, RHSCC;
4442   
4443   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4444   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4445              m_ConstantInt(LHSCst))) ||
4446       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4447              m_ConstantInt(RHSCst))))
4448     return 0;
4449   
4450   // From here on, we only handle:
4451   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4452   if (Val != Val2) return 0;
4453   
4454   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4455   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4456       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4457       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4458       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4459     return 0;
4460   
4461   // We can't fold (ugt x, C) | (sgt x, C2).
4462   if (!PredicatesFoldable(LHSCC, RHSCC))
4463     return 0;
4464   
4465   // Ensure that the larger constant is on the RHS.
4466   bool ShouldSwap;
4467   if (ICmpInst::isSignedPredicate(LHSCC) ||
4468       (ICmpInst::isEquality(LHSCC) && 
4469        ICmpInst::isSignedPredicate(RHSCC)))
4470     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4471   else
4472     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4473   
4474   if (ShouldSwap) {
4475     std::swap(LHS, RHS);
4476     std::swap(LHSCst, RHSCst);
4477     std::swap(LHSCC, RHSCC);
4478   }
4479   
4480   // At this point, we know we have have two icmp instructions
4481   // comparing a value against two constants and or'ing the result
4482   // together.  Because of the above check, we know that we only have
4483   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4484   // FoldICmpLogical check above), that the two constants are not
4485   // equal.
4486   assert(LHSCst != RHSCst && "Compares not folded above?");
4487
4488   switch (LHSCC) {
4489   default: llvm_unreachable("Unknown integer condition code!");
4490   case ICmpInst::ICMP_EQ:
4491     switch (RHSCC) {
4492     default: llvm_unreachable("Unknown integer condition code!");
4493     case ICmpInst::ICMP_EQ:
4494       if (LHSCst == SubOne(RHSCst)) {
4495         // (X == 13 | X == 14) -> X-13 <u 2
4496         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4497         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4498         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4499         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4500       }
4501       break;                         // (X == 13 | X == 15) -> no change
4502     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4503     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4504       break;
4505     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4506     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4507     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4508       return ReplaceInstUsesWith(I, RHS);
4509     }
4510     break;
4511   case ICmpInst::ICMP_NE:
4512     switch (RHSCC) {
4513     default: llvm_unreachable("Unknown integer condition code!");
4514     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4515     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4516     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4517       return ReplaceInstUsesWith(I, LHS);
4518     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4519     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4520     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4521       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4522     }
4523     break;
4524   case ICmpInst::ICMP_ULT:
4525     switch (RHSCC) {
4526     default: llvm_unreachable("Unknown integer condition code!");
4527     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4528       break;
4529     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4530       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4531       // this can cause overflow.
4532       if (RHSCst->isMaxValue(false))
4533         return ReplaceInstUsesWith(I, LHS);
4534       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4535                              false, false, I);
4536     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4537       break;
4538     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4539     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4540       return ReplaceInstUsesWith(I, RHS);
4541     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4542       break;
4543     }
4544     break;
4545   case ICmpInst::ICMP_SLT:
4546     switch (RHSCC) {
4547     default: llvm_unreachable("Unknown integer condition code!");
4548     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4549       break;
4550     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4551       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4552       // this can cause overflow.
4553       if (RHSCst->isMaxValue(true))
4554         return ReplaceInstUsesWith(I, LHS);
4555       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4556                              true, false, I);
4557     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4558       break;
4559     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4560     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4561       return ReplaceInstUsesWith(I, RHS);
4562     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4563       break;
4564     }
4565     break;
4566   case ICmpInst::ICMP_UGT:
4567     switch (RHSCC) {
4568     default: llvm_unreachable("Unknown integer condition code!");
4569     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4570     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4571       return ReplaceInstUsesWith(I, LHS);
4572     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4573       break;
4574     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4575     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4576       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4577     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4578       break;
4579     }
4580     break;
4581   case ICmpInst::ICMP_SGT:
4582     switch (RHSCC) {
4583     default: llvm_unreachable("Unknown integer condition code!");
4584     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4585     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4586       return ReplaceInstUsesWith(I, LHS);
4587     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4588       break;
4589     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4590     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4591       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4592     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4593       break;
4594     }
4595     break;
4596   }
4597   return 0;
4598 }
4599
4600 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4601                                          FCmpInst *RHS) {
4602   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4603       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4604       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4605     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4606       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4607         // If either of the constants are nans, then the whole thing returns
4608         // true.
4609         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4610           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4611         
4612         // Otherwise, no need to compare the two constants, compare the
4613         // rest.
4614         return new FCmpInst(FCmpInst::FCMP_UNO,
4615                             LHS->getOperand(0), RHS->getOperand(0));
4616       }
4617     
4618     // Handle vector zeros.  This occurs because the canonical form of
4619     // "fcmp uno x,x" is "fcmp uno x, 0".
4620     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4621         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4622       return new FCmpInst(FCmpInst::FCMP_UNO,
4623                           LHS->getOperand(0), RHS->getOperand(0));
4624     
4625     return 0;
4626   }
4627   
4628   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4629   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4630   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4631   
4632   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4633     // Swap RHS operands to match LHS.
4634     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4635     std::swap(Op1LHS, Op1RHS);
4636   }
4637   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4638     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4639     if (Op0CC == Op1CC)
4640       return new FCmpInst((FCmpInst::Predicate)Op0CC,
4641                           Op0LHS, Op0RHS);
4642     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4643       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4644     if (Op0CC == FCmpInst::FCMP_FALSE)
4645       return ReplaceInstUsesWith(I, RHS);
4646     if (Op1CC == FCmpInst::FCMP_FALSE)
4647       return ReplaceInstUsesWith(I, LHS);
4648     bool Op0Ordered;
4649     bool Op1Ordered;
4650     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4651     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4652     if (Op0Ordered == Op1Ordered) {
4653       // If both are ordered or unordered, return a new fcmp with
4654       // or'ed predicates.
4655       Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4656                                Op0LHS, Op0RHS, Context);
4657       if (Instruction *I = dyn_cast<Instruction>(RV))
4658         return I;
4659       // Otherwise, it's a constant boolean value...
4660       return ReplaceInstUsesWith(I, RV);
4661     }
4662   }
4663   return 0;
4664 }
4665
4666 /// FoldOrWithConstants - This helper function folds:
4667 ///
4668 ///     ((A | B) & C1) | (B & C2)
4669 ///
4670 /// into:
4671 /// 
4672 ///     (A & C1) | B
4673 ///
4674 /// when the XOR of the two constants is "all ones" (-1).
4675 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4676                                                Value *A, Value *B, Value *C) {
4677   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4678   if (!CI1) return 0;
4679
4680   Value *V1 = 0;
4681   ConstantInt *CI2 = 0;
4682   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4683
4684   APInt Xor = CI1->getValue() ^ CI2->getValue();
4685   if (!Xor.isAllOnesValue()) return 0;
4686
4687   if (V1 == A || V1 == B) {
4688     Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
4689     return BinaryOperator::CreateOr(NewOp, V1);
4690   }
4691
4692   return 0;
4693 }
4694
4695 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4696   bool Changed = SimplifyCommutative(I);
4697   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4698
4699   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4700     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4701
4702   // or X, X = X
4703   if (Op0 == Op1)
4704     return ReplaceInstUsesWith(I, Op0);
4705
4706   // See if we can simplify any instructions used by the instruction whose sole 
4707   // purpose is to compute bits we don't care about.
4708   if (SimplifyDemandedInstructionBits(I))
4709     return &I;
4710   if (isa<VectorType>(I.getType())) {
4711     if (isa<ConstantAggregateZero>(Op1)) {
4712       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4713     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4714       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4715         return ReplaceInstUsesWith(I, I.getOperand(1));
4716     }
4717   }
4718
4719   // or X, -1 == -1
4720   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4721     ConstantInt *C1 = 0; Value *X = 0;
4722     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4723     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
4724         isOnlyUse(Op0)) {
4725       Value *Or = Builder->CreateOr(X, RHS);
4726       Or->takeName(Op0);
4727       return BinaryOperator::CreateAnd(Or, 
4728                ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
4729     }
4730
4731     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4732     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
4733         isOnlyUse(Op0)) {
4734       Value *Or = Builder->CreateOr(X, RHS);
4735       Or->takeName(Op0);
4736       return BinaryOperator::CreateXor(Or,
4737                  ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
4738     }
4739
4740     // Try to fold constant and into select arguments.
4741     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4742       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4743         return R;
4744     if (isa<PHINode>(Op0))
4745       if (Instruction *NV = FoldOpIntoPhi(I))
4746         return NV;
4747   }
4748
4749   Value *A = 0, *B = 0;
4750   ConstantInt *C1 = 0, *C2 = 0;
4751
4752   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4753     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4754       return ReplaceInstUsesWith(I, Op1);
4755   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4756     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4757       return ReplaceInstUsesWith(I, Op0);
4758
4759   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4760   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4761   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4762       match(Op1, m_Or(m_Value(), m_Value())) ||
4763       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4764        match(Op1, m_Shift(m_Value(), m_Value())))) {
4765     if (Instruction *BSwap = MatchBSwap(I))
4766       return BSwap;
4767   }
4768   
4769   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4770   if (Op0->hasOneUse() &&
4771       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4772       MaskedValueIsZero(Op1, C1->getValue())) {
4773     Value *NOr = Builder->CreateOr(A, Op1);
4774     NOr->takeName(Op0);
4775     return BinaryOperator::CreateXor(NOr, C1);
4776   }
4777
4778   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4779   if (Op1->hasOneUse() &&
4780       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4781       MaskedValueIsZero(Op0, C1->getValue())) {
4782     Value *NOr = Builder->CreateOr(A, Op0);
4783     NOr->takeName(Op0);
4784     return BinaryOperator::CreateXor(NOr, C1);
4785   }
4786
4787   // (A & C)|(B & D)
4788   Value *C = 0, *D = 0;
4789   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4790       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4791     Value *V1 = 0, *V2 = 0, *V3 = 0;
4792     C1 = dyn_cast<ConstantInt>(C);
4793     C2 = dyn_cast<ConstantInt>(D);
4794     if (C1 && C2) {  // (A & C1)|(B & C2)
4795       // If we have: ((V + N) & C1) | (V & C2)
4796       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4797       // replace with V+N.
4798       if (C1->getValue() == ~C2->getValue()) {
4799         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4800             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4801           // Add commutes, try both ways.
4802           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4803             return ReplaceInstUsesWith(I, A);
4804           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4805             return ReplaceInstUsesWith(I, A);
4806         }
4807         // Or commutes, try both ways.
4808         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4809             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4810           // Add commutes, try both ways.
4811           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4812             return ReplaceInstUsesWith(I, B);
4813           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4814             return ReplaceInstUsesWith(I, B);
4815         }
4816       }
4817       V1 = 0; V2 = 0; V3 = 0;
4818     }
4819     
4820     // Check to see if we have any common things being and'ed.  If so, find the
4821     // terms for V1 & (V2|V3).
4822     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4823       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4824         V1 = A, V2 = C, V3 = D;
4825       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4826         V1 = A, V2 = B, V3 = C;
4827       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4828         V1 = C, V2 = A, V3 = D;
4829       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4830         V1 = C, V2 = A, V3 = B;
4831       
4832       if (V1) {
4833         Value *Or = Builder->CreateOr(V2, V3, "tmp");
4834         return BinaryOperator::CreateAnd(V1, Or);
4835       }
4836     }
4837
4838     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4839     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4840       return Match;
4841     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4842       return Match;
4843     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4844       return Match;
4845     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4846       return Match;
4847
4848     // ((A&~B)|(~A&B)) -> A^B
4849     if ((match(C, m_Not(m_Specific(D))) &&
4850          match(B, m_Not(m_Specific(A)))))
4851       return BinaryOperator::CreateXor(A, D);
4852     // ((~B&A)|(~A&B)) -> A^B
4853     if ((match(A, m_Not(m_Specific(D))) &&
4854          match(B, m_Not(m_Specific(C)))))
4855       return BinaryOperator::CreateXor(C, D);
4856     // ((A&~B)|(B&~A)) -> A^B
4857     if ((match(C, m_Not(m_Specific(B))) &&
4858          match(D, m_Not(m_Specific(A)))))
4859       return BinaryOperator::CreateXor(A, B);
4860     // ((~B&A)|(B&~A)) -> A^B
4861     if ((match(A, m_Not(m_Specific(B))) &&
4862          match(D, m_Not(m_Specific(C)))))
4863       return BinaryOperator::CreateXor(C, B);
4864   }
4865   
4866   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4867   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4868     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4869       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4870           SI0->getOperand(1) == SI1->getOperand(1) &&
4871           (SI0->hasOneUse() || SI1->hasOneUse())) {
4872         Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4873                                          SI0->getName());
4874         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4875                                       SI1->getOperand(1));
4876       }
4877   }
4878
4879   // ((A|B)&1)|(B&-2) -> (A&1) | B
4880   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4881       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4882     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4883     if (Ret) return Ret;
4884   }
4885   // (B&-2)|((A|B)&1) -> (A&1) | B
4886   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4887       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4888     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4889     if (Ret) return Ret;
4890   }
4891
4892   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4893     if (A == Op1)   // ~A | A == -1
4894       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4895   } else {
4896     A = 0;
4897   }
4898   // Note, A is still live here!
4899   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4900     if (Op0 == B)
4901       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4902
4903     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4904     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4905       Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
4906       return BinaryOperator::CreateNot(And);
4907     }
4908   }
4909
4910   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4911   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4912     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4913       return R;
4914
4915     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4916       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4917         return Res;
4918   }
4919     
4920   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4921   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4922     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4923       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4924         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4925             !isa<ICmpInst>(Op1C->getOperand(0))) {
4926           const Type *SrcTy = Op0C->getOperand(0)->getType();
4927           if (SrcTy == Op1C->getOperand(0)->getType() &&
4928               SrcTy->isIntOrIntVector() &&
4929               // Only do this if the casts both really cause code to be
4930               // generated.
4931               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4932                                 I.getType(), TD) &&
4933               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4934                                 I.getType(), TD)) {
4935             Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
4936                                              Op1C->getOperand(0), I.getName());
4937             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4938           }
4939         }
4940       }
4941   }
4942   
4943     
4944   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4945   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4946     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4947       if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4948         return Res;
4949   }
4950
4951   return Changed ? &I : 0;
4952 }
4953
4954 namespace {
4955
4956 // XorSelf - Implements: X ^ X --> 0
4957 struct XorSelf {
4958   Value *RHS;
4959   XorSelf(Value *rhs) : RHS(rhs) {}
4960   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4961   Instruction *apply(BinaryOperator &Xor) const {
4962     return &Xor;
4963   }
4964 };
4965
4966 }
4967
4968 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4969   bool Changed = SimplifyCommutative(I);
4970   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4971
4972   if (isa<UndefValue>(Op1)) {
4973     if (isa<UndefValue>(Op0))
4974       // Handle undef ^ undef -> 0 special case. This is a common
4975       // idiom (misuse).
4976       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4977     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4978   }
4979
4980   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4981   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4982     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4983     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4984   }
4985   
4986   // See if we can simplify any instructions used by the instruction whose sole 
4987   // purpose is to compute bits we don't care about.
4988   if (SimplifyDemandedInstructionBits(I))
4989     return &I;
4990   if (isa<VectorType>(I.getType()))
4991     if (isa<ConstantAggregateZero>(Op1))
4992       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4993
4994   // Is this a ~ operation?
4995   if (Value *NotOp = dyn_castNotVal(&I)) {
4996     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4997     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4998     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4999       if (Op0I->getOpcode() == Instruction::And || 
5000           Op0I->getOpcode() == Instruction::Or) {
5001         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5002         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5003           Value *NotY =
5004             Builder->CreateNot(Op0I->getOperand(1),
5005                                Op0I->getOperand(1)->getName()+".not");
5006           if (Op0I->getOpcode() == Instruction::And)
5007             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5008           return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5009         }
5010       }
5011     }
5012   }
5013   
5014   
5015   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5016     if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
5017       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5018       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5019         return new ICmpInst(ICI->getInversePredicate(),
5020                             ICI->getOperand(0), ICI->getOperand(1));
5021
5022       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5023         return new FCmpInst(FCI->getInversePredicate(),
5024                             FCI->getOperand(0), FCI->getOperand(1));
5025     }
5026
5027     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5028     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5029       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5030         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5031           Instruction::CastOps Opcode = Op0C->getOpcode();
5032           if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5033               (RHS == ConstantExpr::getCast(Opcode, 
5034                                             ConstantInt::getTrue(*Context),
5035                                             Op0C->getDestTy()))) {
5036             CI->setPredicate(CI->getInversePredicate());
5037             return CastInst::Create(Opcode, CI, Op0C->getType());
5038           }
5039         }
5040       }
5041     }
5042
5043     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5044       // ~(c-X) == X-c-1 == X+(-c-1)
5045       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5046         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5047           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5048           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5049                                       ConstantInt::get(I.getType(), 1));
5050           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5051         }
5052           
5053       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5054         if (Op0I->getOpcode() == Instruction::Add) {
5055           // ~(X-c) --> (-c-1)-X
5056           if (RHS->isAllOnesValue()) {
5057             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5058             return BinaryOperator::CreateSub(
5059                            ConstantExpr::getSub(NegOp0CI,
5060                                       ConstantInt::get(I.getType(), 1)),
5061                                       Op0I->getOperand(0));
5062           } else if (RHS->getValue().isSignBit()) {
5063             // (X + C) ^ signbit -> (X + C + signbit)
5064             Constant *C = ConstantInt::get(*Context,
5065                                            RHS->getValue() + Op0CI->getValue());
5066             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5067
5068           }
5069         } else if (Op0I->getOpcode() == Instruction::Or) {
5070           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5071           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5072             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5073             // Anything in both C1 and C2 is known to be zero, remove it from
5074             // NewRHS.
5075             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5076             NewRHS = ConstantExpr::getAnd(NewRHS, 
5077                                        ConstantExpr::getNot(CommonBits));
5078             Worklist.Add(Op0I);
5079             I.setOperand(0, Op0I->getOperand(0));
5080             I.setOperand(1, NewRHS);
5081             return &I;
5082           }
5083         }
5084       }
5085     }
5086
5087     // Try to fold constant and into select arguments.
5088     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5089       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5090         return R;
5091     if (isa<PHINode>(Op0))
5092       if (Instruction *NV = FoldOpIntoPhi(I))
5093         return NV;
5094   }
5095
5096   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5097     if (X == Op1)
5098       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5099
5100   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5101     if (X == Op0)
5102       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5103
5104   
5105   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5106   if (Op1I) {
5107     Value *A, *B;
5108     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5109       if (A == Op0) {              // B^(B|A) == (A|B)^B
5110         Op1I->swapOperands();
5111         I.swapOperands();
5112         std::swap(Op0, Op1);
5113       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5114         I.swapOperands();     // Simplified below.
5115         std::swap(Op0, Op1);
5116       }
5117     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5118       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5119     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5120       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5121     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && 
5122                Op1I->hasOneUse()){
5123       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5124         Op1I->swapOperands();
5125         std::swap(A, B);
5126       }
5127       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5128         I.swapOperands();     // Simplified below.
5129         std::swap(Op0, Op1);
5130       }
5131     }
5132   }
5133   
5134   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5135   if (Op0I) {
5136     Value *A, *B;
5137     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5138         Op0I->hasOneUse()) {
5139       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5140         std::swap(A, B);
5141       if (B == Op1)                                  // (A|B)^B == A & ~B
5142         return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
5143     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5144       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5145     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5146       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5147     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && 
5148                Op0I->hasOneUse()){
5149       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5150         std::swap(A, B);
5151       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5152           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5153         return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
5154       }
5155     }
5156   }
5157   
5158   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5159   if (Op0I && Op1I && Op0I->isShift() && 
5160       Op0I->getOpcode() == Op1I->getOpcode() && 
5161       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5162       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5163     Value *NewOp =
5164       Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5165                          Op0I->getName());
5166     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5167                                   Op1I->getOperand(1));
5168   }
5169     
5170   if (Op0I && Op1I) {
5171     Value *A, *B, *C, *D;
5172     // (A & B)^(A | B) -> A ^ B
5173     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5174         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5175       if ((A == C && B == D) || (A == D && B == C)) 
5176         return BinaryOperator::CreateXor(A, B);
5177     }
5178     // (A | B)^(A & B) -> A ^ B
5179     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5180         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5181       if ((A == C && B == D) || (A == D && B == C)) 
5182         return BinaryOperator::CreateXor(A, B);
5183     }
5184     
5185     // (A & B)^(C & D)
5186     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5187         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5188         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5189       // (X & Y)^(X & Y) -> (Y^Z) & X
5190       Value *X = 0, *Y = 0, *Z = 0;
5191       if (A == C)
5192         X = A, Y = B, Z = D;
5193       else if (A == D)
5194         X = A, Y = B, Z = C;
5195       else if (B == C)
5196         X = B, Y = A, Z = D;
5197       else if (B == D)
5198         X = B, Y = A, Z = C;
5199       
5200       if (X) {
5201         Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
5202         return BinaryOperator::CreateAnd(NewOp, X);
5203       }
5204     }
5205   }
5206     
5207   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5208   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5209     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5210       return R;
5211
5212   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5213   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5214     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5215       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5216         const Type *SrcTy = Op0C->getOperand(0)->getType();
5217         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5218             // Only do this if the casts both really cause code to be generated.
5219             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5220                               I.getType(), TD) &&
5221             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5222                               I.getType(), TD)) {
5223           Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5224                                             Op1C->getOperand(0), I.getName());
5225           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5226         }
5227       }
5228   }
5229
5230   return Changed ? &I : 0;
5231 }
5232
5233 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5234                                    LLVMContext *Context) {
5235   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5236 }
5237
5238 static bool HasAddOverflow(ConstantInt *Result,
5239                            ConstantInt *In1, ConstantInt *In2,
5240                            bool IsSigned) {
5241   if (IsSigned)
5242     if (In2->getValue().isNegative())
5243       return Result->getValue().sgt(In1->getValue());
5244     else
5245       return Result->getValue().slt(In1->getValue());
5246   else
5247     return Result->getValue().ult(In1->getValue());
5248 }
5249
5250 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5251 /// overflowed for this type.
5252 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5253                             Constant *In2, LLVMContext *Context,
5254                             bool IsSigned = false) {
5255   Result = ConstantExpr::getAdd(In1, In2);
5256
5257   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5258     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5259       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5260       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5261                          ExtractElement(In1, Idx, Context),
5262                          ExtractElement(In2, Idx, Context),
5263                          IsSigned))
5264         return true;
5265     }
5266     return false;
5267   }
5268
5269   return HasAddOverflow(cast<ConstantInt>(Result),
5270                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5271                         IsSigned);
5272 }
5273
5274 static bool HasSubOverflow(ConstantInt *Result,
5275                            ConstantInt *In1, ConstantInt *In2,
5276                            bool IsSigned) {
5277   if (IsSigned)
5278     if (In2->getValue().isNegative())
5279       return Result->getValue().slt(In1->getValue());
5280     else
5281       return Result->getValue().sgt(In1->getValue());
5282   else
5283     return Result->getValue().ugt(In1->getValue());
5284 }
5285
5286 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5287 /// overflowed for this type.
5288 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5289                             Constant *In2, LLVMContext *Context,
5290                             bool IsSigned = false) {
5291   Result = ConstantExpr::getSub(In1, In2);
5292
5293   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5294     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5295       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5296       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5297                          ExtractElement(In1, Idx, Context),
5298                          ExtractElement(In2, Idx, Context),
5299                          IsSigned))
5300         return true;
5301     }
5302     return false;
5303   }
5304
5305   return HasSubOverflow(cast<ConstantInt>(Result),
5306                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5307                         IsSigned);
5308 }
5309
5310 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5311 /// code necessary to compute the offset from the base pointer (without adding
5312 /// in the base pointer).  Return the result as a signed integer of intptr size.
5313 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5314   TargetData &TD = *IC.getTargetData();
5315   gep_type_iterator GTI = gep_type_begin(GEP);
5316   const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
5317   Value *Result = Constant::getNullValue(IntPtrTy);
5318
5319   // Build a mask for high order bits.
5320   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5321   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5322
5323   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5324        ++i, ++GTI) {
5325     Value *Op = *i;
5326     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5327     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5328       if (OpC->isZero()) continue;
5329       
5330       // Handle a struct index, which adds its field offset to the pointer.
5331       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5332         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5333         
5334         Result = IC.Builder->CreateAdd(Result,
5335                                        ConstantInt::get(IntPtrTy, Size),
5336                                        GEP->getName()+".offs");
5337         continue;
5338       }
5339       
5340       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5341       Constant *OC =
5342               ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5343       Scale = ConstantExpr::getMul(OC, Scale);
5344       // Emit an add instruction.
5345       Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
5346       continue;
5347     }
5348     // Convert to correct type.
5349     if (Op->getType() != IntPtrTy)
5350       Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
5351     if (Size != 1) {
5352       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5353       // We'll let instcombine(mul) convert this to a shl if possible.
5354       Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
5355     }
5356
5357     // Emit an add instruction.
5358     Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
5359   }
5360   return Result;
5361 }
5362
5363
5364 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5365 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
5366 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
5367 /// be complex, and scales are involved.  The above expression would also be
5368 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5369 /// This later form is less amenable to optimization though, and we are allowed
5370 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5371 ///
5372 /// If we can't emit an optimized form for this expression, this returns null.
5373 /// 
5374 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5375                                           InstCombiner &IC) {
5376   TargetData &TD = *IC.getTargetData();
5377   gep_type_iterator GTI = gep_type_begin(GEP);
5378
5379   // Check to see if this gep only has a single variable index.  If so, and if
5380   // any constant indices are a multiple of its scale, then we can compute this
5381   // in terms of the scale of the variable index.  For example, if the GEP
5382   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5383   // because the expression will cross zero at the same point.
5384   unsigned i, e = GEP->getNumOperands();
5385   int64_t Offset = 0;
5386   for (i = 1; i != e; ++i, ++GTI) {
5387     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5388       // Compute the aggregate offset of constant indices.
5389       if (CI->isZero()) continue;
5390
5391       // Handle a struct index, which adds its field offset to the pointer.
5392       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5393         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5394       } else {
5395         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5396         Offset += Size*CI->getSExtValue();
5397       }
5398     } else {
5399       // Found our variable index.
5400       break;
5401     }
5402   }
5403   
5404   // If there are no variable indices, we must have a constant offset, just
5405   // evaluate it the general way.
5406   if (i == e) return 0;
5407   
5408   Value *VariableIdx = GEP->getOperand(i);
5409   // Determine the scale factor of the variable element.  For example, this is
5410   // 4 if the variable index is into an array of i32.
5411   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5412   
5413   // Verify that there are no other variable indices.  If so, emit the hard way.
5414   for (++i, ++GTI; i != e; ++i, ++GTI) {
5415     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5416     if (!CI) return 0;
5417    
5418     // Compute the aggregate offset of constant indices.
5419     if (CI->isZero()) continue;
5420     
5421     // Handle a struct index, which adds its field offset to the pointer.
5422     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5423       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5424     } else {
5425       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5426       Offset += Size*CI->getSExtValue();
5427     }
5428   }
5429   
5430   // Okay, we know we have a single variable index, which must be a
5431   // pointer/array/vector index.  If there is no offset, life is simple, return
5432   // the index.
5433   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5434   if (Offset == 0) {
5435     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5436     // we don't need to bother extending: the extension won't affect where the
5437     // computation crosses zero.
5438     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5439       VariableIdx = new TruncInst(VariableIdx, 
5440                                   TD.getIntPtrType(VariableIdx->getContext()),
5441                                   VariableIdx->getName(), &I);
5442     return VariableIdx;
5443   }
5444   
5445   // Otherwise, there is an index.  The computation we will do will be modulo
5446   // the pointer size, so get it.
5447   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5448   
5449   Offset &= PtrSizeMask;
5450   VariableScale &= PtrSizeMask;
5451
5452   // To do this transformation, any constant index must be a multiple of the
5453   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5454   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5455   // multiple of the variable scale.
5456   int64_t NewOffs = Offset / (int64_t)VariableScale;
5457   if (Offset != NewOffs*(int64_t)VariableScale)
5458     return 0;
5459
5460   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5461   const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
5462   if (VariableIdx->getType() != IntPtrTy)
5463     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5464                                               true /*SExt*/, 
5465                                               VariableIdx->getName(), &I);
5466   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5467   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5468 }
5469
5470
5471 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5472 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5473 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5474                                        ICmpInst::Predicate Cond,
5475                                        Instruction &I) {
5476   // Look through bitcasts.
5477   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5478     RHS = BCI->getOperand(0);
5479
5480   Value *PtrBase = GEPLHS->getOperand(0);
5481   if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5482     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5483     // This transformation (ignoring the base and scales) is valid because we
5484     // know pointers can't overflow since the gep is inbounds.  See if we can
5485     // output an optimized form.
5486     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5487     
5488     // If not, synthesize the offset the hard way.
5489     if (Offset == 0)
5490       Offset = EmitGEPOffset(GEPLHS, I, *this);
5491     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5492                         Constant::getNullValue(Offset->getType()));
5493   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5494     // If the base pointers are different, but the indices are the same, just
5495     // compare the base pointer.
5496     if (PtrBase != GEPRHS->getOperand(0)) {
5497       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5498       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5499                         GEPRHS->getOperand(0)->getType();
5500       if (IndicesTheSame)
5501         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5502           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5503             IndicesTheSame = false;
5504             break;
5505           }
5506
5507       // If all indices are the same, just compare the base pointers.
5508       if (IndicesTheSame)
5509         return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5510                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5511
5512       // Otherwise, the base pointers are different and the indices are
5513       // different, bail out.
5514       return 0;
5515     }
5516
5517     // If one of the GEPs has all zero indices, recurse.
5518     bool AllZeros = true;
5519     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5520       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5521           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5522         AllZeros = false;
5523         break;
5524       }
5525     if (AllZeros)
5526       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5527                           ICmpInst::getSwappedPredicate(Cond), I);
5528
5529     // If the other GEP has all zero indices, recurse.
5530     AllZeros = true;
5531     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5532       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5533           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5534         AllZeros = false;
5535         break;
5536       }
5537     if (AllZeros)
5538       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5539
5540     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5541       // If the GEPs only differ by one index, compare it.
5542       unsigned NumDifferences = 0;  // Keep track of # differences.
5543       unsigned DiffOperand = 0;     // The operand that differs.
5544       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5545         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5546           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5547                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5548             // Irreconcilable differences.
5549             NumDifferences = 2;
5550             break;
5551           } else {
5552             if (NumDifferences++) break;
5553             DiffOperand = i;
5554           }
5555         }
5556
5557       if (NumDifferences == 0)   // SAME GEP?
5558         return ReplaceInstUsesWith(I, // No comparison is needed here.
5559                                    ConstantInt::get(Type::getInt1Ty(*Context),
5560                                              ICmpInst::isTrueWhenEqual(Cond)));
5561
5562       else if (NumDifferences == 1) {
5563         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5564         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5565         // Make sure we do a signed comparison here.
5566         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5567       }
5568     }
5569
5570     // Only lower this if the icmp is the only user of the GEP or if we expect
5571     // the result to fold to a constant!
5572     if (TD &&
5573         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5574         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5575       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5576       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5577       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5578       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5579     }
5580   }
5581   return 0;
5582 }
5583
5584 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5585 ///
5586 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5587                                                 Instruction *LHSI,
5588                                                 Constant *RHSC) {
5589   if (!isa<ConstantFP>(RHSC)) return 0;
5590   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5591   
5592   // Get the width of the mantissa.  We don't want to hack on conversions that
5593   // might lose information from the integer, e.g. "i64 -> float"
5594   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5595   if (MantissaWidth == -1) return 0;  // Unknown.
5596   
5597   // Check to see that the input is converted from an integer type that is small
5598   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5599   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5600   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5601   
5602   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5603   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5604   if (LHSUnsigned)
5605     ++InputSize;
5606   
5607   // If the conversion would lose info, don't hack on this.
5608   if ((int)InputSize > MantissaWidth)
5609     return 0;
5610   
5611   // Otherwise, we can potentially simplify the comparison.  We know that it
5612   // will always come through as an integer value and we know the constant is
5613   // not a NAN (it would have been previously simplified).
5614   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5615   
5616   ICmpInst::Predicate Pred;
5617   switch (I.getPredicate()) {
5618   default: llvm_unreachable("Unexpected predicate!");
5619   case FCmpInst::FCMP_UEQ:
5620   case FCmpInst::FCMP_OEQ:
5621     Pred = ICmpInst::ICMP_EQ;
5622     break;
5623   case FCmpInst::FCMP_UGT:
5624   case FCmpInst::FCMP_OGT:
5625     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5626     break;
5627   case FCmpInst::FCMP_UGE:
5628   case FCmpInst::FCMP_OGE:
5629     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5630     break;
5631   case FCmpInst::FCMP_ULT:
5632   case FCmpInst::FCMP_OLT:
5633     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5634     break;
5635   case FCmpInst::FCMP_ULE:
5636   case FCmpInst::FCMP_OLE:
5637     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5638     break;
5639   case FCmpInst::FCMP_UNE:
5640   case FCmpInst::FCMP_ONE:
5641     Pred = ICmpInst::ICMP_NE;
5642     break;
5643   case FCmpInst::FCMP_ORD:
5644     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5645   case FCmpInst::FCMP_UNO:
5646     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5647   }
5648   
5649   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5650   
5651   // Now we know that the APFloat is a normal number, zero or inf.
5652   
5653   // See if the FP constant is too large for the integer.  For example,
5654   // comparing an i8 to 300.0.
5655   unsigned IntWidth = IntTy->getScalarSizeInBits();
5656   
5657   if (!LHSUnsigned) {
5658     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5659     // and large values.
5660     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5661     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5662                           APFloat::rmNearestTiesToEven);
5663     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5664       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5665           Pred == ICmpInst::ICMP_SLE)
5666         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5667       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5668     }
5669   } else {
5670     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5671     // +INF and large values.
5672     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5673     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5674                           APFloat::rmNearestTiesToEven);
5675     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5676       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5677           Pred == ICmpInst::ICMP_ULE)
5678         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5679       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5680     }
5681   }
5682   
5683   if (!LHSUnsigned) {
5684     // See if the RHS value is < SignedMin.
5685     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5686     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5687                           APFloat::rmNearestTiesToEven);
5688     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5689       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5690           Pred == ICmpInst::ICMP_SGE)
5691         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5692       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5693     }
5694   }
5695
5696   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5697   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5698   // casting the FP value to the integer value and back, checking for equality.
5699   // Don't do this for zero, because -0.0 is not fractional.
5700   Constant *RHSInt = LHSUnsigned
5701     ? ConstantExpr::getFPToUI(RHSC, IntTy)
5702     : ConstantExpr::getFPToSI(RHSC, IntTy);
5703   if (!RHS.isZero()) {
5704     bool Equal = LHSUnsigned
5705       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5706       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5707     if (!Equal) {
5708       // If we had a comparison against a fractional value, we have to adjust
5709       // the compare predicate and sometimes the value.  RHSC is rounded towards
5710       // zero at this point.
5711       switch (Pred) {
5712       default: llvm_unreachable("Unexpected integer comparison!");
5713       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5714         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5715       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5716         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5717       case ICmpInst::ICMP_ULE:
5718         // (float)int <= 4.4   --> int <= 4
5719         // (float)int <= -4.4  --> false
5720         if (RHS.isNegative())
5721           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5722         break;
5723       case ICmpInst::ICMP_SLE:
5724         // (float)int <= 4.4   --> int <= 4
5725         // (float)int <= -4.4  --> int < -4
5726         if (RHS.isNegative())
5727           Pred = ICmpInst::ICMP_SLT;
5728         break;
5729       case ICmpInst::ICMP_ULT:
5730         // (float)int < -4.4   --> false
5731         // (float)int < 4.4    --> int <= 4
5732         if (RHS.isNegative())
5733           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5734         Pred = ICmpInst::ICMP_ULE;
5735         break;
5736       case ICmpInst::ICMP_SLT:
5737         // (float)int < -4.4   --> int < -4
5738         // (float)int < 4.4    --> int <= 4
5739         if (!RHS.isNegative())
5740           Pred = ICmpInst::ICMP_SLE;
5741         break;
5742       case ICmpInst::ICMP_UGT:
5743         // (float)int > 4.4    --> int > 4
5744         // (float)int > -4.4   --> true
5745         if (RHS.isNegative())
5746           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5747         break;
5748       case ICmpInst::ICMP_SGT:
5749         // (float)int > 4.4    --> int > 4
5750         // (float)int > -4.4   --> int >= -4
5751         if (RHS.isNegative())
5752           Pred = ICmpInst::ICMP_SGE;
5753         break;
5754       case ICmpInst::ICMP_UGE:
5755         // (float)int >= -4.4   --> true
5756         // (float)int >= 4.4    --> int > 4
5757         if (!RHS.isNegative())
5758           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5759         Pred = ICmpInst::ICMP_UGT;
5760         break;
5761       case ICmpInst::ICMP_SGE:
5762         // (float)int >= -4.4   --> int >= -4
5763         // (float)int >= 4.4    --> int > 4
5764         if (!RHS.isNegative())
5765           Pred = ICmpInst::ICMP_SGT;
5766         break;
5767       }
5768     }
5769   }
5770
5771   // Lower this FP comparison into an appropriate integer version of the
5772   // comparison.
5773   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5774 }
5775
5776 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5777   bool Changed = SimplifyCompare(I);
5778   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5779
5780   // Fold trivial predicates.
5781   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5782     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5783   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5784     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5785   
5786   // Simplify 'fcmp pred X, X'
5787   if (Op0 == Op1) {
5788     switch (I.getPredicate()) {
5789     default: llvm_unreachable("Unknown predicate!");
5790     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5791     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5792     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5793       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5794     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5795     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5796     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5797       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5798       
5799     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5800     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5801     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5802     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5803       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5804       I.setPredicate(FCmpInst::FCMP_UNO);
5805       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5806       return &I;
5807       
5808     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5809     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5810     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5811     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5812       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5813       I.setPredicate(FCmpInst::FCMP_ORD);
5814       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5815       return &I;
5816     }
5817   }
5818     
5819   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5820     return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
5821
5822   // Handle fcmp with constant RHS
5823   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5824     // If the constant is a nan, see if we can fold the comparison based on it.
5825     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5826       if (CFP->getValueAPF().isNaN()) {
5827         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5828           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5829         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5830                "Comparison must be either ordered or unordered!");
5831         // True if unordered.
5832         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5833       }
5834     }
5835     
5836     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5837       switch (LHSI->getOpcode()) {
5838       case Instruction::PHI:
5839         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5840         // block.  If in the same block, we're encouraging jump threading.  If
5841         // not, we are just pessimizing the code by making an i1 phi.
5842         if (LHSI->getParent() == I.getParent())
5843           if (Instruction *NV = FoldOpIntoPhi(I))
5844             return NV;
5845         break;
5846       case Instruction::SIToFP:
5847       case Instruction::UIToFP:
5848         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5849           return NV;
5850         break;
5851       case Instruction::Select:
5852         // If either operand of the select is a constant, we can fold the
5853         // comparison into the select arms, which will cause one to be
5854         // constant folded and the select turned into a bitwise or.
5855         Value *Op1 = 0, *Op2 = 0;
5856         if (LHSI->hasOneUse()) {
5857           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5858             // Fold the known value into the constant operand.
5859             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5860             // Insert a new FCmp of the other select operand.
5861             Op2 = Builder->CreateFCmp(I.getPredicate(),
5862                                       LHSI->getOperand(2), RHSC, I.getName());
5863           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5864             // Fold the known value into the constant operand.
5865             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5866             // Insert a new FCmp of the other select operand.
5867             Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5868                                       RHSC, I.getName());
5869           }
5870         }
5871
5872         if (Op1)
5873           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5874         break;
5875       }
5876   }
5877
5878   return Changed ? &I : 0;
5879 }
5880
5881 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5882   bool Changed = SimplifyCompare(I);
5883   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5884   const Type *Ty = Op0->getType();
5885
5886   // icmp X, X
5887   if (Op0 == Op1)
5888     return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context), 
5889                                                    I.isTrueWhenEqual()));
5890
5891   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5892     return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
5893   
5894   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5895   // addresses never equal each other!  We already know that Op0 != Op1.
5896   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5897        isa<ConstantPointerNull>(Op0)) &&
5898       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5899        isa<ConstantPointerNull>(Op1)))
5900     return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context), 
5901                                                    !I.isTrueWhenEqual()));
5902
5903   // icmp's with boolean values can always be turned into bitwise operations
5904   if (Ty == Type::getInt1Ty(*Context)) {
5905     switch (I.getPredicate()) {
5906     default: llvm_unreachable("Invalid icmp instruction!");
5907     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5908       Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
5909       return BinaryOperator::CreateNot(Xor);
5910     }
5911     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5912       return BinaryOperator::CreateXor(Op0, Op1);
5913
5914     case ICmpInst::ICMP_UGT:
5915       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5916       // FALL THROUGH
5917     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5918       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
5919       return BinaryOperator::CreateAnd(Not, Op1);
5920     }
5921     case ICmpInst::ICMP_SGT:
5922       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5923       // FALL THROUGH
5924     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5925       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
5926       return BinaryOperator::CreateAnd(Not, Op0);
5927     }
5928     case ICmpInst::ICMP_UGE:
5929       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5930       // FALL THROUGH
5931     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5932       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
5933       return BinaryOperator::CreateOr(Not, Op1);
5934     }
5935     case ICmpInst::ICMP_SGE:
5936       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5937       // FALL THROUGH
5938     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5939       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
5940       return BinaryOperator::CreateOr(Not, Op0);
5941     }
5942     }
5943   }
5944
5945   unsigned BitWidth = 0;
5946   if (TD)
5947     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
5948   else if (Ty->isIntOrIntVector())
5949     BitWidth = Ty->getScalarSizeInBits();
5950
5951   bool isSignBit = false;
5952
5953   // See if we are doing a comparison with a constant.
5954   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5955     Value *A = 0, *B = 0;
5956     
5957     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5958     if (I.isEquality() && CI->isNullValue() &&
5959         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5960       // (icmp cond A B) if cond is equality
5961       return new ICmpInst(I.getPredicate(), A, B);
5962     }
5963     
5964     // If we have an icmp le or icmp ge instruction, turn it into the
5965     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
5966     // them being folded in the code below.
5967     switch (I.getPredicate()) {
5968     default: break;
5969     case ICmpInst::ICMP_ULE:
5970       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5971         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5972       return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
5973                           AddOne(CI));
5974     case ICmpInst::ICMP_SLE:
5975       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5976         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5977       return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5978                           AddOne(CI));
5979     case ICmpInst::ICMP_UGE:
5980       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5981         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5982       return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
5983                           SubOne(CI));
5984     case ICmpInst::ICMP_SGE:
5985       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5986         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5987       return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5988                           SubOne(CI));
5989     }
5990     
5991     // If this comparison is a normal comparison, it demands all
5992     // bits, if it is a sign bit comparison, it only demands the sign bit.
5993     bool UnusedBit;
5994     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5995   }
5996
5997   // See if we can fold the comparison based on range information we can get
5998   // by checking whether bits are known to be zero or one in the input.
5999   if (BitWidth != 0) {
6000     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6001     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6002
6003     if (SimplifyDemandedBits(I.getOperandUse(0),
6004                              isSignBit ? APInt::getSignBit(BitWidth)
6005                                        : APInt::getAllOnesValue(BitWidth),
6006                              Op0KnownZero, Op0KnownOne, 0))
6007       return &I;
6008     if (SimplifyDemandedBits(I.getOperandUse(1),
6009                              APInt::getAllOnesValue(BitWidth),
6010                              Op1KnownZero, Op1KnownOne, 0))
6011       return &I;
6012
6013     // Given the known and unknown bits, compute a range that the LHS could be
6014     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6015     // EQ and NE we use unsigned values.
6016     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6017     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6018     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6019       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6020                                              Op0Min, Op0Max);
6021       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6022                                              Op1Min, Op1Max);
6023     } else {
6024       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6025                                                Op0Min, Op0Max);
6026       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6027                                                Op1Min, Op1Max);
6028     }
6029
6030     // If Min and Max are known to be the same, then SimplifyDemandedBits
6031     // figured out that the LHS is a constant.  Just constant fold this now so
6032     // that code below can assume that Min != Max.
6033     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6034       return new ICmpInst(I.getPredicate(),
6035                           ConstantInt::get(*Context, Op0Min), Op1);
6036     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6037       return new ICmpInst(I.getPredicate(), Op0,
6038                           ConstantInt::get(*Context, Op1Min));
6039
6040     // Based on the range information we know about the LHS, see if we can
6041     // simplify this comparison.  For example, (x&4) < 8  is always true.
6042     switch (I.getPredicate()) {
6043     default: llvm_unreachable("Unknown icmp opcode!");
6044     case ICmpInst::ICMP_EQ:
6045       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6046         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6047       break;
6048     case ICmpInst::ICMP_NE:
6049       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6050         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6051       break;
6052     case ICmpInst::ICMP_ULT:
6053       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6054         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6055       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6056         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6057       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6058         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6059       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6060         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6061           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6062                               SubOne(CI));
6063
6064         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6065         if (CI->isMinValue(true))
6066           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6067                            Constant::getAllOnesValue(Op0->getType()));
6068       }
6069       break;
6070     case ICmpInst::ICMP_UGT:
6071       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6072         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6073       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6074         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6075
6076       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6077         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6078       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6079         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6080           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6081                               AddOne(CI));
6082
6083         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6084         if (CI->isMaxValue(true))
6085           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6086                               Constant::getNullValue(Op0->getType()));
6087       }
6088       break;
6089     case ICmpInst::ICMP_SLT:
6090       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6091         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6092       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6093         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6094       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6095         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6096       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6097         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6098           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6099                               SubOne(CI));
6100       }
6101       break;
6102     case ICmpInst::ICMP_SGT:
6103       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6104         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6105       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6106         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6107
6108       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6109         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6110       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6111         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6112           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6113                               AddOne(CI));
6114       }
6115       break;
6116     case ICmpInst::ICMP_SGE:
6117       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6118       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6119         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6120       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6121         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6122       break;
6123     case ICmpInst::ICMP_SLE:
6124       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6125       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6126         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6127       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6128         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6129       break;
6130     case ICmpInst::ICMP_UGE:
6131       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6132       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6133         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6134       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6135         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6136       break;
6137     case ICmpInst::ICMP_ULE:
6138       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6139       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6140         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6141       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6142         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6143       break;
6144     }
6145
6146     // Turn a signed comparison into an unsigned one if both operands
6147     // are known to have the same sign.
6148     if (I.isSignedPredicate() &&
6149         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6150          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6151       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6152   }
6153
6154   // Test if the ICmpInst instruction is used exclusively by a select as
6155   // part of a minimum or maximum operation. If so, refrain from doing
6156   // any other folding. This helps out other analyses which understand
6157   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6158   // and CodeGen. And in this case, at least one of the comparison
6159   // operands has at least one user besides the compare (the select),
6160   // which would often largely negate the benefit of folding anyway.
6161   if (I.hasOneUse())
6162     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6163       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6164           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6165         return 0;
6166
6167   // See if we are doing a comparison between a constant and an instruction that
6168   // can be folded into the comparison.
6169   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6170     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6171     // instruction, see if that instruction also has constants so that the 
6172     // instruction can be folded into the icmp 
6173     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6174       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6175         return Res;
6176   }
6177
6178   // Handle icmp with constant (but not simple integer constant) RHS
6179   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6180     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6181       switch (LHSI->getOpcode()) {
6182       case Instruction::GetElementPtr:
6183         if (RHSC->isNullValue()) {
6184           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6185           bool isAllZeros = true;
6186           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6187             if (!isa<Constant>(LHSI->getOperand(i)) ||
6188                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6189               isAllZeros = false;
6190               break;
6191             }
6192           if (isAllZeros)
6193             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6194                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6195         }
6196         break;
6197
6198       case Instruction::PHI:
6199         // Only fold icmp into the PHI if the phi and fcmp are in the same
6200         // block.  If in the same block, we're encouraging jump threading.  If
6201         // not, we are just pessimizing the code by making an i1 phi.
6202         if (LHSI->getParent() == I.getParent())
6203           if (Instruction *NV = FoldOpIntoPhi(I))
6204             return NV;
6205         break;
6206       case Instruction::Select: {
6207         // If either operand of the select is a constant, we can fold the
6208         // comparison into the select arms, which will cause one to be
6209         // constant folded and the select turned into a bitwise or.
6210         Value *Op1 = 0, *Op2 = 0;
6211         if (LHSI->hasOneUse()) {
6212           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6213             // Fold the known value into the constant operand.
6214             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6215             // Insert a new ICmp of the other select operand.
6216             Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6217                                       RHSC, I.getName());
6218           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6219             // Fold the known value into the constant operand.
6220             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6221             // Insert a new ICmp of the other select operand.
6222             Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6223                                       RHSC, I.getName());
6224           }
6225         }
6226
6227         if (Op1)
6228           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6229         break;
6230       }
6231       case Instruction::Malloc:
6232         // If we have (malloc != null), and if the malloc has a single use, we
6233         // can assume it is successful and remove the malloc.
6234         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6235           Worklist.Add(LHSI);
6236           return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
6237                                                          !I.isTrueWhenEqual()));
6238         }
6239         break;
6240       }
6241   }
6242
6243   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6244   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6245     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6246       return NI;
6247   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6248     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6249                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6250       return NI;
6251
6252   // Test to see if the operands of the icmp are casted versions of other
6253   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6254   // now.
6255   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6256     if (isa<PointerType>(Op0->getType()) && 
6257         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6258       // We keep moving the cast from the left operand over to the right
6259       // operand, where it can often be eliminated completely.
6260       Op0 = CI->getOperand(0);
6261
6262       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6263       // so eliminate it as well.
6264       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6265         Op1 = CI2->getOperand(0);
6266
6267       // If Op1 is a constant, we can fold the cast into the constant.
6268       if (Op0->getType() != Op1->getType()) {
6269         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6270           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6271         } else {
6272           // Otherwise, cast the RHS right before the icmp
6273           Op1 = Builder->CreateBitCast(Op1, Op0->getType());
6274         }
6275       }
6276       return new ICmpInst(I.getPredicate(), Op0, Op1);
6277     }
6278   }
6279   
6280   if (isa<CastInst>(Op0)) {
6281     // Handle the special case of: icmp (cast bool to X), <cst>
6282     // This comes up when you have code like
6283     //   int X = A < B;
6284     //   if (X) ...
6285     // For generality, we handle any zero-extension of any operand comparison
6286     // with a constant or another cast from the same type.
6287     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6288       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6289         return R;
6290   }
6291   
6292   // See if it's the same type of instruction on the left and right.
6293   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6294     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6295       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6296           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6297         switch (Op0I->getOpcode()) {
6298         default: break;
6299         case Instruction::Add:
6300         case Instruction::Sub:
6301         case Instruction::Xor:
6302           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6303             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6304                                 Op1I->getOperand(0));
6305           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6306           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6307             if (CI->getValue().isSignBit()) {
6308               ICmpInst::Predicate Pred = I.isSignedPredicate()
6309                                              ? I.getUnsignedPredicate()
6310                                              : I.getSignedPredicate();
6311               return new ICmpInst(Pred, Op0I->getOperand(0),
6312                                   Op1I->getOperand(0));
6313             }
6314             
6315             if (CI->getValue().isMaxSignedValue()) {
6316               ICmpInst::Predicate Pred = I.isSignedPredicate()
6317                                              ? I.getUnsignedPredicate()
6318                                              : I.getSignedPredicate();
6319               Pred = I.getSwappedPredicate(Pred);
6320               return new ICmpInst(Pred, Op0I->getOperand(0),
6321                                   Op1I->getOperand(0));
6322             }
6323           }
6324           break;
6325         case Instruction::Mul:
6326           if (!I.isEquality())
6327             break;
6328
6329           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6330             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6331             // Mask = -1 >> count-trailing-zeros(Cst).
6332             if (!CI->isZero() && !CI->isOne()) {
6333               const APInt &AP = CI->getValue();
6334               ConstantInt *Mask = ConstantInt::get(*Context, 
6335                                       APInt::getLowBitsSet(AP.getBitWidth(),
6336                                                            AP.getBitWidth() -
6337                                                       AP.countTrailingZeros()));
6338               Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6339               Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
6340               return new ICmpInst(I.getPredicate(), And1, And2);
6341             }
6342           }
6343           break;
6344         }
6345       }
6346     }
6347   }
6348   
6349   // ~x < ~y --> y < x
6350   { Value *A, *B;
6351     if (match(Op0, m_Not(m_Value(A))) &&
6352         match(Op1, m_Not(m_Value(B))))
6353       return new ICmpInst(I.getPredicate(), B, A);
6354   }
6355   
6356   if (I.isEquality()) {
6357     Value *A, *B, *C, *D;
6358     
6359     // -x == -y --> x == y
6360     if (match(Op0, m_Neg(m_Value(A))) &&
6361         match(Op1, m_Neg(m_Value(B))))
6362       return new ICmpInst(I.getPredicate(), A, B);
6363     
6364     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6365       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6366         Value *OtherVal = A == Op1 ? B : A;
6367         return new ICmpInst(I.getPredicate(), OtherVal,
6368                             Constant::getNullValue(A->getType()));
6369       }
6370
6371       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6372         // A^c1 == C^c2 --> A == C^(c1^c2)
6373         ConstantInt *C1, *C2;
6374         if (match(B, m_ConstantInt(C1)) &&
6375             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6376           Constant *NC = 
6377                    ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6378           Value *Xor = Builder->CreateXor(C, NC, "tmp");
6379           return new ICmpInst(I.getPredicate(), A, Xor);
6380         }
6381         
6382         // A^B == A^D -> B == D
6383         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6384         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6385         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6386         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6387       }
6388     }
6389     
6390     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6391         (A == Op0 || B == Op0)) {
6392       // A == (A^B)  ->  B == 0
6393       Value *OtherVal = A == Op0 ? B : A;
6394       return new ICmpInst(I.getPredicate(), OtherVal,
6395                           Constant::getNullValue(A->getType()));
6396     }
6397
6398     // (A-B) == A  ->  B == 0
6399     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6400       return new ICmpInst(I.getPredicate(), B, 
6401                           Constant::getNullValue(B->getType()));
6402
6403     // A == (A-B)  ->  B == 0
6404     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6405       return new ICmpInst(I.getPredicate(), B,
6406                           Constant::getNullValue(B->getType()));
6407     
6408     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6409     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6410         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6411         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6412       Value *X = 0, *Y = 0, *Z = 0;
6413       
6414       if (A == C) {
6415         X = B; Y = D; Z = A;
6416       } else if (A == D) {
6417         X = B; Y = C; Z = A;
6418       } else if (B == C) {
6419         X = A; Y = D; Z = B;
6420       } else if (B == D) {
6421         X = A; Y = C; Z = B;
6422       }
6423       
6424       if (X) {   // Build (X^Y) & Z
6425         Op1 = Builder->CreateXor(X, Y, "tmp");
6426         Op1 = Builder->CreateAnd(Op1, Z, "tmp");
6427         I.setOperand(0, Op1);
6428         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6429         return &I;
6430       }
6431     }
6432   }
6433   return Changed ? &I : 0;
6434 }
6435
6436
6437 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6438 /// and CmpRHS are both known to be integer constants.
6439 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6440                                           ConstantInt *DivRHS) {
6441   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6442   const APInt &CmpRHSV = CmpRHS->getValue();
6443   
6444   // FIXME: If the operand types don't match the type of the divide 
6445   // then don't attempt this transform. The code below doesn't have the
6446   // logic to deal with a signed divide and an unsigned compare (and
6447   // vice versa). This is because (x /s C1) <s C2  produces different 
6448   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6449   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6450   // work. :(  The if statement below tests that condition and bails 
6451   // if it finds it. 
6452   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6453   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6454     return 0;
6455   if (DivRHS->isZero())
6456     return 0; // The ProdOV computation fails on divide by zero.
6457   if (DivIsSigned && DivRHS->isAllOnesValue())
6458     return 0; // The overflow computation also screws up here
6459   if (DivRHS->isOne())
6460     return 0; // Not worth bothering, and eliminates some funny cases
6461               // with INT_MIN.
6462
6463   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6464   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6465   // C2 (CI). By solving for X we can turn this into a range check 
6466   // instead of computing a divide. 
6467   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6468
6469   // Determine if the product overflows by seeing if the product is
6470   // not equal to the divide. Make sure we do the same kind of divide
6471   // as in the LHS instruction that we're folding. 
6472   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6473                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6474
6475   // Get the ICmp opcode
6476   ICmpInst::Predicate Pred = ICI.getPredicate();
6477
6478   // Figure out the interval that is being checked.  For example, a comparison
6479   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6480   // Compute this interval based on the constants involved and the signedness of
6481   // the compare/divide.  This computes a half-open interval, keeping track of
6482   // whether either value in the interval overflows.  After analysis each
6483   // overflow variable is set to 0 if it's corresponding bound variable is valid
6484   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6485   int LoOverflow = 0, HiOverflow = 0;
6486   Constant *LoBound = 0, *HiBound = 0;
6487   
6488   if (!DivIsSigned) {  // udiv
6489     // e.g. X/5 op 3  --> [15, 20)
6490     LoBound = Prod;
6491     HiOverflow = LoOverflow = ProdOV;
6492     if (!HiOverflow)
6493       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6494   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6495     if (CmpRHSV == 0) {       // (X / pos) op 0
6496       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6497       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6498       HiBound = DivRHS;
6499     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6500       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6501       HiOverflow = LoOverflow = ProdOV;
6502       if (!HiOverflow)
6503         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6504     } else {                       // (X / pos) op neg
6505       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6506       HiBound = AddOne(Prod);
6507       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6508       if (!LoOverflow) {
6509         ConstantInt* DivNeg =
6510                          cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6511         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6512                                      true) ? -1 : 0;
6513        }
6514     }
6515   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6516     if (CmpRHSV == 0) {       // (X / neg) op 0
6517       // e.g. X/-5 op 0  --> [-4, 5)
6518       LoBound = AddOne(DivRHS);
6519       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6520       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6521         HiOverflow = 1;            // [INTMIN+1, overflow)
6522         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6523       }
6524     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6525       // e.g. X/-5 op 3  --> [-19, -14)
6526       HiBound = AddOne(Prod);
6527       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6528       if (!LoOverflow)
6529         LoOverflow = AddWithOverflow(LoBound, HiBound,
6530                                      DivRHS, Context, true) ? -1 : 0;
6531     } else {                       // (X / neg) op neg
6532       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6533       LoOverflow = HiOverflow = ProdOV;
6534       if (!HiOverflow)
6535         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6536     }
6537     
6538     // Dividing by a negative swaps the condition.  LT <-> GT
6539     Pred = ICmpInst::getSwappedPredicate(Pred);
6540   }
6541
6542   Value *X = DivI->getOperand(0);
6543   switch (Pred) {
6544   default: llvm_unreachable("Unhandled icmp opcode!");
6545   case ICmpInst::ICMP_EQ:
6546     if (LoOverflow && HiOverflow)
6547       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6548     else if (HiOverflow)
6549       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6550                           ICmpInst::ICMP_UGE, X, LoBound);
6551     else if (LoOverflow)
6552       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6553                           ICmpInst::ICMP_ULT, X, HiBound);
6554     else
6555       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6556   case ICmpInst::ICMP_NE:
6557     if (LoOverflow && HiOverflow)
6558       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6559     else if (HiOverflow)
6560       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6561                           ICmpInst::ICMP_ULT, X, LoBound);
6562     else if (LoOverflow)
6563       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6564                           ICmpInst::ICMP_UGE, X, HiBound);
6565     else
6566       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6567   case ICmpInst::ICMP_ULT:
6568   case ICmpInst::ICMP_SLT:
6569     if (LoOverflow == +1)   // Low bound is greater than input range.
6570       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6571     if (LoOverflow == -1)   // Low bound is less than input range.
6572       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6573     return new ICmpInst(Pred, X, LoBound);
6574   case ICmpInst::ICMP_UGT:
6575   case ICmpInst::ICMP_SGT:
6576     if (HiOverflow == +1)       // High bound greater than input range.
6577       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6578     else if (HiOverflow == -1)  // High bound less than input range.
6579       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6580     if (Pred == ICmpInst::ICMP_UGT)
6581       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6582     else
6583       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6584   }
6585 }
6586
6587
6588 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6589 ///
6590 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6591                                                           Instruction *LHSI,
6592                                                           ConstantInt *RHS) {
6593   const APInt &RHSV = RHS->getValue();
6594   
6595   switch (LHSI->getOpcode()) {
6596   case Instruction::Trunc:
6597     if (ICI.isEquality() && LHSI->hasOneUse()) {
6598       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6599       // of the high bits truncated out of x are known.
6600       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6601              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6602       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6603       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6604       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6605       
6606       // If all the high bits are known, we can do this xform.
6607       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6608         // Pull in the high bits from known-ones set.
6609         APInt NewRHS(RHS->getValue());
6610         NewRHS.zext(SrcBits);
6611         NewRHS |= KnownOne;
6612         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6613                             ConstantInt::get(*Context, NewRHS));
6614       }
6615     }
6616     break;
6617       
6618   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6619     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6620       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6621       // fold the xor.
6622       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6623           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6624         Value *CompareVal = LHSI->getOperand(0);
6625         
6626         // If the sign bit of the XorCST is not set, there is no change to
6627         // the operation, just stop using the Xor.
6628         if (!XorCST->getValue().isNegative()) {
6629           ICI.setOperand(0, CompareVal);
6630           Worklist.Add(LHSI);
6631           return &ICI;
6632         }
6633         
6634         // Was the old condition true if the operand is positive?
6635         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6636         
6637         // If so, the new one isn't.
6638         isTrueIfPositive ^= true;
6639         
6640         if (isTrueIfPositive)
6641           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
6642                               SubOne(RHS));
6643         else
6644           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
6645                               AddOne(RHS));
6646       }
6647
6648       if (LHSI->hasOneUse()) {
6649         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6650         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6651           const APInt &SignBit = XorCST->getValue();
6652           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6653                                          ? ICI.getUnsignedPredicate()
6654                                          : ICI.getSignedPredicate();
6655           return new ICmpInst(Pred, LHSI->getOperand(0),
6656                               ConstantInt::get(*Context, RHSV ^ SignBit));
6657         }
6658
6659         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6660         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6661           const APInt &NotSignBit = XorCST->getValue();
6662           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6663                                          ? ICI.getUnsignedPredicate()
6664                                          : ICI.getSignedPredicate();
6665           Pred = ICI.getSwappedPredicate(Pred);
6666           return new ICmpInst(Pred, LHSI->getOperand(0),
6667                               ConstantInt::get(*Context, RHSV ^ NotSignBit));
6668         }
6669       }
6670     }
6671     break;
6672   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6673     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6674         LHSI->getOperand(0)->hasOneUse()) {
6675       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6676       
6677       // If the LHS is an AND of a truncating cast, we can widen the
6678       // and/compare to be the input width without changing the value
6679       // produced, eliminating a cast.
6680       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6681         // We can do this transformation if either the AND constant does not
6682         // have its sign bit set or if it is an equality comparison. 
6683         // Extending a relational comparison when we're checking the sign
6684         // bit would not work.
6685         if (Cast->hasOneUse() &&
6686             (ICI.isEquality() ||
6687              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6688           uint32_t BitWidth = 
6689             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6690           APInt NewCST = AndCST->getValue();
6691           NewCST.zext(BitWidth);
6692           APInt NewCI = RHSV;
6693           NewCI.zext(BitWidth);
6694           Value *NewAnd = 
6695             Builder->CreateAnd(Cast->getOperand(0),
6696                            ConstantInt::get(*Context, NewCST), LHSI->getName());
6697           return new ICmpInst(ICI.getPredicate(), NewAnd,
6698                               ConstantInt::get(*Context, NewCI));
6699         }
6700       }
6701       
6702       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6703       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6704       // happens a LOT in code produced by the C front-end, for bitfield
6705       // access.
6706       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6707       if (Shift && !Shift->isShift())
6708         Shift = 0;
6709       
6710       ConstantInt *ShAmt;
6711       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6712       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6713       const Type *AndTy = AndCST->getType();          // Type of the and.
6714       
6715       // We can fold this as long as we can't shift unknown bits
6716       // into the mask.  This can only happen with signed shift
6717       // rights, as they sign-extend.
6718       if (ShAmt) {
6719         bool CanFold = Shift->isLogicalShift();
6720         if (!CanFold) {
6721           // To test for the bad case of the signed shr, see if any
6722           // of the bits shifted in could be tested after the mask.
6723           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6724           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6725           
6726           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6727           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6728                AndCST->getValue()) == 0)
6729             CanFold = true;
6730         }
6731         
6732         if (CanFold) {
6733           Constant *NewCst;
6734           if (Shift->getOpcode() == Instruction::Shl)
6735             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6736           else
6737             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6738           
6739           // Check to see if we are shifting out any of the bits being
6740           // compared.
6741           if (ConstantExpr::get(Shift->getOpcode(),
6742                                        NewCst, ShAmt) != RHS) {
6743             // If we shifted bits out, the fold is not going to work out.
6744             // As a special case, check to see if this means that the
6745             // result is always true or false now.
6746             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6747               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6748             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6749               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6750           } else {
6751             ICI.setOperand(1, NewCst);
6752             Constant *NewAndCST;
6753             if (Shift->getOpcode() == Instruction::Shl)
6754               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6755             else
6756               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6757             LHSI->setOperand(1, NewAndCST);
6758             LHSI->setOperand(0, Shift->getOperand(0));
6759             Worklist.Add(Shift); // Shift is dead.
6760             return &ICI;
6761           }
6762         }
6763       }
6764       
6765       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6766       // preferable because it allows the C<<Y expression to be hoisted out
6767       // of a loop if Y is invariant and X is not.
6768       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6769           ICI.isEquality() && !Shift->isArithmeticShift() &&
6770           !isa<Constant>(Shift->getOperand(0))) {
6771         // Compute C << Y.
6772         Value *NS;
6773         if (Shift->getOpcode() == Instruction::LShr) {
6774           NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
6775         } else {
6776           // Insert a logical shift.
6777           NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
6778         }
6779         
6780         // Compute X & (C << Y).
6781         Value *NewAnd = 
6782           Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6783         
6784         ICI.setOperand(0, NewAnd);
6785         return &ICI;
6786       }
6787     }
6788     break;
6789     
6790   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6791     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6792     if (!ShAmt) break;
6793     
6794     uint32_t TypeBits = RHSV.getBitWidth();
6795     
6796     // Check that the shift amount is in range.  If not, don't perform
6797     // undefined shifts.  When the shift is visited it will be
6798     // simplified.
6799     if (ShAmt->uge(TypeBits))
6800       break;
6801     
6802     if (ICI.isEquality()) {
6803       // If we are comparing against bits always shifted out, the
6804       // comparison cannot succeed.
6805       Constant *Comp =
6806         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
6807                                                                  ShAmt);
6808       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6809         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6810         Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6811         return ReplaceInstUsesWith(ICI, Cst);
6812       }
6813       
6814       if (LHSI->hasOneUse()) {
6815         // Otherwise strength reduce the shift into an and.
6816         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6817         Constant *Mask =
6818           ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits, 
6819                                                        TypeBits-ShAmtVal));
6820         
6821         Value *And =
6822           Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
6823         return new ICmpInst(ICI.getPredicate(), And,
6824                             ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
6825       }
6826     }
6827     
6828     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6829     bool TrueIfSigned = false;
6830     if (LHSI->hasOneUse() &&
6831         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6832       // (X << 31) <s 0  --> (X&1) != 0
6833       Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
6834                                            (TypeBits-ShAmt->getZExtValue()-1));
6835       Value *And =
6836         Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
6837       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6838                           And, Constant::getNullValue(And->getType()));
6839     }
6840     break;
6841   }
6842     
6843   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6844   case Instruction::AShr: {
6845     // Only handle equality comparisons of shift-by-constant.
6846     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6847     if (!ShAmt || !ICI.isEquality()) break;
6848
6849     // Check that the shift amount is in range.  If not, don't perform
6850     // undefined shifts.  When the shift is visited it will be
6851     // simplified.
6852     uint32_t TypeBits = RHSV.getBitWidth();
6853     if (ShAmt->uge(TypeBits))
6854       break;
6855     
6856     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6857       
6858     // If we are comparing against bits always shifted out, the
6859     // comparison cannot succeed.
6860     APInt Comp = RHSV << ShAmtVal;
6861     if (LHSI->getOpcode() == Instruction::LShr)
6862       Comp = Comp.lshr(ShAmtVal);
6863     else
6864       Comp = Comp.ashr(ShAmtVal);
6865     
6866     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6867       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6868       Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6869       return ReplaceInstUsesWith(ICI, Cst);
6870     }
6871     
6872     // Otherwise, check to see if the bits shifted out are known to be zero.
6873     // If so, we can compare against the unshifted value:
6874     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6875     if (LHSI->hasOneUse() &&
6876         MaskedValueIsZero(LHSI->getOperand(0), 
6877                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6878       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6879                           ConstantExpr::getShl(RHS, ShAmt));
6880     }
6881       
6882     if (LHSI->hasOneUse()) {
6883       // Otherwise strength reduce the shift into an and.
6884       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6885       Constant *Mask = ConstantInt::get(*Context, Val);
6886       
6887       Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6888                                       Mask, LHSI->getName()+".mask");
6889       return new ICmpInst(ICI.getPredicate(), And,
6890                           ConstantExpr::getShl(RHS, ShAmt));
6891     }
6892     break;
6893   }
6894     
6895   case Instruction::SDiv:
6896   case Instruction::UDiv:
6897     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6898     // Fold this div into the comparison, producing a range check. 
6899     // Determine, based on the divide type, what the range is being 
6900     // checked.  If there is an overflow on the low or high side, remember 
6901     // it, otherwise compute the range [low, hi) bounding the new value.
6902     // See: InsertRangeTest above for the kinds of replacements possible.
6903     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6904       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6905                                           DivRHS))
6906         return R;
6907     break;
6908
6909   case Instruction::Add:
6910     // Fold: icmp pred (add, X, C1), C2
6911
6912     if (!ICI.isEquality()) {
6913       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6914       if (!LHSC) break;
6915       const APInt &LHSV = LHSC->getValue();
6916
6917       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6918                             .subtract(LHSV);
6919
6920       if (ICI.isSignedPredicate()) {
6921         if (CR.getLower().isSignBit()) {
6922           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6923                               ConstantInt::get(*Context, CR.getUpper()));
6924         } else if (CR.getUpper().isSignBit()) {
6925           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6926                               ConstantInt::get(*Context, CR.getLower()));
6927         }
6928       } else {
6929         if (CR.getLower().isMinValue()) {
6930           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6931                               ConstantInt::get(*Context, CR.getUpper()));
6932         } else if (CR.getUpper().isMinValue()) {
6933           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6934                               ConstantInt::get(*Context, CR.getLower()));
6935         }
6936       }
6937     }
6938     break;
6939   }
6940   
6941   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6942   if (ICI.isEquality()) {
6943     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6944     
6945     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6946     // the second operand is a constant, simplify a bit.
6947     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6948       switch (BO->getOpcode()) {
6949       case Instruction::SRem:
6950         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6951         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6952           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6953           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6954             Value *NewRem =
6955               Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
6956                                   BO->getName());
6957             return new ICmpInst(ICI.getPredicate(), NewRem,
6958                                 Constant::getNullValue(BO->getType()));
6959           }
6960         }
6961         break;
6962       case Instruction::Add:
6963         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6964         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6965           if (BO->hasOneUse())
6966             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6967                                 ConstantExpr::getSub(RHS, BOp1C));
6968         } else if (RHSV == 0) {
6969           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6970           // efficiently invertible, or if the add has just this one use.
6971           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6972           
6973           if (Value *NegVal = dyn_castNegVal(BOp1))
6974             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6975           else if (Value *NegVal = dyn_castNegVal(BOp0))
6976             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6977           else if (BO->hasOneUse()) {
6978             Value *Neg = Builder->CreateNeg(BOp1);
6979             Neg->takeName(BO);
6980             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6981           }
6982         }
6983         break;
6984       case Instruction::Xor:
6985         // For the xor case, we can xor two constants together, eliminating
6986         // the explicit xor.
6987         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6988           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6989                               ConstantExpr::getXor(RHS, BOC));
6990         
6991         // FALLTHROUGH
6992       case Instruction::Sub:
6993         // Replace (([sub|xor] A, B) != 0) with (A != B)
6994         if (RHSV == 0)
6995           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6996                               BO->getOperand(1));
6997         break;
6998         
6999       case Instruction::Or:
7000         // If bits are being or'd in that are not present in the constant we
7001         // are comparing against, then the comparison could never succeed!
7002         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7003           Constant *NotCI = ConstantExpr::getNot(RHS);
7004           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7005             return ReplaceInstUsesWith(ICI,
7006                                        ConstantInt::get(Type::getInt1Ty(*Context), 
7007                                        isICMP_NE));
7008         }
7009         break;
7010         
7011       case Instruction::And:
7012         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7013           // If bits are being compared against that are and'd out, then the
7014           // comparison can never succeed!
7015           if ((RHSV & ~BOC->getValue()) != 0)
7016             return ReplaceInstUsesWith(ICI,
7017                                        ConstantInt::get(Type::getInt1Ty(*Context),
7018                                        isICMP_NE));
7019           
7020           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7021           if (RHS == BOC && RHSV.isPowerOf2())
7022             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7023                                 ICmpInst::ICMP_NE, LHSI,
7024                                 Constant::getNullValue(RHS->getType()));
7025           
7026           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7027           if (BOC->getValue().isSignBit()) {
7028             Value *X = BO->getOperand(0);
7029             Constant *Zero = Constant::getNullValue(X->getType());
7030             ICmpInst::Predicate pred = isICMP_NE ? 
7031               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7032             return new ICmpInst(pred, X, Zero);
7033           }
7034           
7035           // ((X & ~7) == 0) --> X < 8
7036           if (RHSV == 0 && isHighOnes(BOC)) {
7037             Value *X = BO->getOperand(0);
7038             Constant *NegX = ConstantExpr::getNeg(BOC);
7039             ICmpInst::Predicate pred = isICMP_NE ? 
7040               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7041             return new ICmpInst(pred, X, NegX);
7042           }
7043         }
7044       default: break;
7045       }
7046     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7047       // Handle icmp {eq|ne} <intrinsic>, intcst.
7048       if (II->getIntrinsicID() == Intrinsic::bswap) {
7049         Worklist.Add(II);
7050         ICI.setOperand(0, II->getOperand(1));
7051         ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7052         return &ICI;
7053       }
7054     }
7055   }
7056   return 0;
7057 }
7058
7059 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7060 /// We only handle extending casts so far.
7061 ///
7062 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7063   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7064   Value *LHSCIOp        = LHSCI->getOperand(0);
7065   const Type *SrcTy     = LHSCIOp->getType();
7066   const Type *DestTy    = LHSCI->getType();
7067   Value *RHSCIOp;
7068
7069   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7070   // integer type is the same size as the pointer type.
7071   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7072       TD->getPointerSizeInBits() ==
7073          cast<IntegerType>(DestTy)->getBitWidth()) {
7074     Value *RHSOp = 0;
7075     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7076       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7077     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7078       RHSOp = RHSC->getOperand(0);
7079       // If the pointer types don't match, insert a bitcast.
7080       if (LHSCIOp->getType() != RHSOp->getType())
7081         RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
7082     }
7083
7084     if (RHSOp)
7085       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7086   }
7087   
7088   // The code below only handles extension cast instructions, so far.
7089   // Enforce this.
7090   if (LHSCI->getOpcode() != Instruction::ZExt &&
7091       LHSCI->getOpcode() != Instruction::SExt)
7092     return 0;
7093
7094   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7095   bool isSignedCmp = ICI.isSignedPredicate();
7096
7097   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7098     // Not an extension from the same type?
7099     RHSCIOp = CI->getOperand(0);
7100     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7101       return 0;
7102     
7103     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7104     // and the other is a zext), then we can't handle this.
7105     if (CI->getOpcode() != LHSCI->getOpcode())
7106       return 0;
7107
7108     // Deal with equality cases early.
7109     if (ICI.isEquality())
7110       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7111
7112     // A signed comparison of sign extended values simplifies into a
7113     // signed comparison.
7114     if (isSignedCmp && isSignedExt)
7115       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7116
7117     // The other three cases all fold into an unsigned comparison.
7118     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7119   }
7120
7121   // If we aren't dealing with a constant on the RHS, exit early
7122   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7123   if (!CI)
7124     return 0;
7125
7126   // Compute the constant that would happen if we truncated to SrcTy then
7127   // reextended to DestTy.
7128   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7129   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7130                                                 Res1, DestTy);
7131
7132   // If the re-extended constant didn't change...
7133   if (Res2 == CI) {
7134     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7135     // For example, we might have:
7136     //    %A = sext i16 %X to i32
7137     //    %B = icmp ugt i32 %A, 1330
7138     // It is incorrect to transform this into 
7139     //    %B = icmp ugt i16 %X, 1330
7140     // because %A may have negative value. 
7141     //
7142     // However, we allow this when the compare is EQ/NE, because they are
7143     // signless.
7144     if (isSignedExt == isSignedCmp || ICI.isEquality())
7145       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7146     return 0;
7147   }
7148
7149   // The re-extended constant changed so the constant cannot be represented 
7150   // in the shorter type. Consequently, we cannot emit a simple comparison.
7151
7152   // First, handle some easy cases. We know the result cannot be equal at this
7153   // point so handle the ICI.isEquality() cases
7154   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7155     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7156   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7157     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7158
7159   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7160   // should have been folded away previously and not enter in here.
7161   Value *Result;
7162   if (isSignedCmp) {
7163     // We're performing a signed comparison.
7164     if (cast<ConstantInt>(CI)->getValue().isNegative())
7165       Result = ConstantInt::getFalse(*Context);          // X < (small) --> false
7166     else
7167       Result = ConstantInt::getTrue(*Context);           // X < (large) --> true
7168   } else {
7169     // We're performing an unsigned comparison.
7170     if (isSignedExt) {
7171       // We're performing an unsigned comp with a sign extended value.
7172       // This is true if the input is >= 0. [aka >s -1]
7173       Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7174       Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
7175     } else {
7176       // Unsigned extend & unsigned compare -> always true.
7177       Result = ConstantInt::getTrue(*Context);
7178     }
7179   }
7180
7181   // Finally, return the value computed.
7182   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7183       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7184     return ReplaceInstUsesWith(ICI, Result);
7185
7186   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7187           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7188          "ICmp should be folded!");
7189   if (Constant *CI = dyn_cast<Constant>(Result))
7190     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7191   return BinaryOperator::CreateNot(Result);
7192 }
7193
7194 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7195   return commonShiftTransforms(I);
7196 }
7197
7198 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7199   return commonShiftTransforms(I);
7200 }
7201
7202 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7203   if (Instruction *R = commonShiftTransforms(I))
7204     return R;
7205   
7206   Value *Op0 = I.getOperand(0);
7207   
7208   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7209   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7210     if (CSI->isAllOnesValue())
7211       return ReplaceInstUsesWith(I, CSI);
7212
7213   // See if we can turn a signed shr into an unsigned shr.
7214   if (MaskedValueIsZero(Op0,
7215                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7216     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7217
7218   // Arithmetic shifting an all-sign-bit value is a no-op.
7219   unsigned NumSignBits = ComputeNumSignBits(Op0);
7220   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7221     return ReplaceInstUsesWith(I, Op0);
7222
7223   return 0;
7224 }
7225
7226 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7227   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7228   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7229
7230   // shl X, 0 == X and shr X, 0 == X
7231   // shl 0, X == 0 and shr 0, X == 0
7232   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7233       Op0 == Constant::getNullValue(Op0->getType()))
7234     return ReplaceInstUsesWith(I, Op0);
7235   
7236   if (isa<UndefValue>(Op0)) {            
7237     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7238       return ReplaceInstUsesWith(I, Op0);
7239     else                                    // undef << X -> 0, undef >>u X -> 0
7240       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7241   }
7242   if (isa<UndefValue>(Op1)) {
7243     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7244       return ReplaceInstUsesWith(I, Op0);          
7245     else                                     // X << undef, X >>u undef -> 0
7246       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7247   }
7248
7249   // See if we can fold away this shift.
7250   if (SimplifyDemandedInstructionBits(I))
7251     return &I;
7252
7253   // Try to fold constant and into select arguments.
7254   if (isa<Constant>(Op0))
7255     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7256       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7257         return R;
7258
7259   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7260     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7261       return Res;
7262   return 0;
7263 }
7264
7265 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7266                                                BinaryOperator &I) {
7267   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7268
7269   // See if we can simplify any instructions used by the instruction whose sole 
7270   // purpose is to compute bits we don't care about.
7271   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7272   
7273   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7274   // a signed shift.
7275   //
7276   if (Op1->uge(TypeBits)) {
7277     if (I.getOpcode() != Instruction::AShr)
7278       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7279     else {
7280       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7281       return &I;
7282     }
7283   }
7284   
7285   // ((X*C1) << C2) == (X * (C1 << C2))
7286   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7287     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7288       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7289         return BinaryOperator::CreateMul(BO->getOperand(0),
7290                                         ConstantExpr::getShl(BOOp, Op1));
7291   
7292   // Try to fold constant and into select arguments.
7293   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7294     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7295       return R;
7296   if (isa<PHINode>(Op0))
7297     if (Instruction *NV = FoldOpIntoPhi(I))
7298       return NV;
7299   
7300   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7301   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7302     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7303     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7304     // place.  Don't try to do this transformation in this case.  Also, we
7305     // require that the input operand is a shift-by-constant so that we have
7306     // confidence that the shifts will get folded together.  We could do this
7307     // xform in more cases, but it is unlikely to be profitable.
7308     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7309         isa<ConstantInt>(TrOp->getOperand(1))) {
7310       // Okay, we'll do this xform.  Make the shift of shift.
7311       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7312       // (shift2 (shift1 & 0x00FF), c2)
7313       Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
7314
7315       // For logical shifts, the truncation has the effect of making the high
7316       // part of the register be zeros.  Emulate this by inserting an AND to
7317       // clear the top bits as needed.  This 'and' will usually be zapped by
7318       // other xforms later if dead.
7319       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7320       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7321       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7322       
7323       // The mask we constructed says what the trunc would do if occurring
7324       // between the shifts.  We want to know the effect *after* the second
7325       // shift.  We know that it is a logical shift by a constant, so adjust the
7326       // mask as appropriate.
7327       if (I.getOpcode() == Instruction::Shl)
7328         MaskV <<= Op1->getZExtValue();
7329       else {
7330         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7331         MaskV = MaskV.lshr(Op1->getZExtValue());
7332       }
7333
7334       // shift1 & 0x00FF
7335       Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7336                                       TI->getName());
7337
7338       // Return the value truncated to the interesting size.
7339       return new TruncInst(And, I.getType());
7340     }
7341   }
7342   
7343   if (Op0->hasOneUse()) {
7344     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7345       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7346       Value *V1, *V2;
7347       ConstantInt *CC;
7348       switch (Op0BO->getOpcode()) {
7349         default: break;
7350         case Instruction::Add:
7351         case Instruction::And:
7352         case Instruction::Or:
7353         case Instruction::Xor: {
7354           // These operators commute.
7355           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7356           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7357               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7358                     m_Specific(Op1)))) {
7359             Value *YS =         // (Y << C)
7360               Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7361             // (X + (Y << C))
7362             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7363                                             Op0BO->getOperand(1)->getName());
7364             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7365             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7366                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7367           }
7368           
7369           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7370           Value *Op0BOOp1 = Op0BO->getOperand(1);
7371           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7372               match(Op0BOOp1, 
7373                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7374                           m_ConstantInt(CC))) &&
7375               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7376             Value *YS =   // (Y << C)
7377               Builder->CreateShl(Op0BO->getOperand(0), Op1,
7378                                            Op0BO->getName());
7379             // X & (CC << C)
7380             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7381                                            V1->getName()+".mask");
7382             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7383           }
7384         }
7385           
7386         // FALL THROUGH.
7387         case Instruction::Sub: {
7388           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7389           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7390               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7391                     m_Specific(Op1)))) {
7392             Value *YS =  // (Y << C)
7393               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7394             // (X + (Y << C))
7395             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7396                                             Op0BO->getOperand(0)->getName());
7397             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7398             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7399                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7400           }
7401           
7402           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7403           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7404               match(Op0BO->getOperand(0),
7405                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7406                           m_ConstantInt(CC))) && V2 == Op1 &&
7407               cast<BinaryOperator>(Op0BO->getOperand(0))
7408                   ->getOperand(0)->hasOneUse()) {
7409             Value *YS = // (Y << C)
7410               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7411             // X & (CC << C)
7412             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7413                                            V1->getName()+".mask");
7414             
7415             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7416           }
7417           
7418           break;
7419         }
7420       }
7421       
7422       
7423       // If the operand is an bitwise operator with a constant RHS, and the
7424       // shift is the only use, we can pull it out of the shift.
7425       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7426         bool isValid = true;     // Valid only for And, Or, Xor
7427         bool highBitSet = false; // Transform if high bit of constant set?
7428         
7429         switch (Op0BO->getOpcode()) {
7430           default: isValid = false; break;   // Do not perform transform!
7431           case Instruction::Add:
7432             isValid = isLeftShift;
7433             break;
7434           case Instruction::Or:
7435           case Instruction::Xor:
7436             highBitSet = false;
7437             break;
7438           case Instruction::And:
7439             highBitSet = true;
7440             break;
7441         }
7442         
7443         // If this is a signed shift right, and the high bit is modified
7444         // by the logical operation, do not perform the transformation.
7445         // The highBitSet boolean indicates the value of the high bit of
7446         // the constant which would cause it to be modified for this
7447         // operation.
7448         //
7449         if (isValid && I.getOpcode() == Instruction::AShr)
7450           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7451         
7452         if (isValid) {
7453           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7454           
7455           Value *NewShift =
7456             Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
7457           NewShift->takeName(Op0BO);
7458           
7459           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7460                                         NewRHS);
7461         }
7462       }
7463     }
7464   }
7465   
7466   // Find out if this is a shift of a shift by a constant.
7467   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7468   if (ShiftOp && !ShiftOp->isShift())
7469     ShiftOp = 0;
7470   
7471   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7472     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7473     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7474     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7475     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7476     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7477     Value *X = ShiftOp->getOperand(0);
7478     
7479     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7480     
7481     const IntegerType *Ty = cast<IntegerType>(I.getType());
7482     
7483     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7484     if (I.getOpcode() == ShiftOp->getOpcode()) {
7485       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7486       // saturates.
7487       if (AmtSum >= TypeBits) {
7488         if (I.getOpcode() != Instruction::AShr)
7489           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7490         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7491       }
7492       
7493       return BinaryOperator::Create(I.getOpcode(), X,
7494                                     ConstantInt::get(Ty, AmtSum));
7495     }
7496     
7497     if (ShiftOp->getOpcode() == Instruction::LShr &&
7498         I.getOpcode() == Instruction::AShr) {
7499       if (AmtSum >= TypeBits)
7500         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7501       
7502       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7503       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7504     }
7505     
7506     if (ShiftOp->getOpcode() == Instruction::AShr &&
7507         I.getOpcode() == Instruction::LShr) {
7508       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7509       if (AmtSum >= TypeBits)
7510         AmtSum = TypeBits-1;
7511       
7512       Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7513
7514       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7515       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7516     }
7517     
7518     // Okay, if we get here, one shift must be left, and the other shift must be
7519     // right.  See if the amounts are equal.
7520     if (ShiftAmt1 == ShiftAmt2) {
7521       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7522       if (I.getOpcode() == Instruction::Shl) {
7523         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7524         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7525       }
7526       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7527       if (I.getOpcode() == Instruction::LShr) {
7528         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7529         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7530       }
7531       // We can simplify ((X << C) >>s C) into a trunc + sext.
7532       // NOTE: we could do this for any C, but that would make 'unusual' integer
7533       // types.  For now, just stick to ones well-supported by the code
7534       // generators.
7535       const Type *SExtType = 0;
7536       switch (Ty->getBitWidth() - ShiftAmt1) {
7537       case 1  :
7538       case 8  :
7539       case 16 :
7540       case 32 :
7541       case 64 :
7542       case 128:
7543         SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
7544         break;
7545       default: break;
7546       }
7547       if (SExtType)
7548         return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
7549       // Otherwise, we can't handle it yet.
7550     } else if (ShiftAmt1 < ShiftAmt2) {
7551       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7552       
7553       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7554       if (I.getOpcode() == Instruction::Shl) {
7555         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7556                ShiftOp->getOpcode() == Instruction::AShr);
7557         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7558         
7559         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7560         return BinaryOperator::CreateAnd(Shift,
7561                                          ConstantInt::get(*Context, Mask));
7562       }
7563       
7564       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7565       if (I.getOpcode() == Instruction::LShr) {
7566         assert(ShiftOp->getOpcode() == Instruction::Shl);
7567         Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7568         
7569         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7570         return BinaryOperator::CreateAnd(Shift,
7571                                          ConstantInt::get(*Context, Mask));
7572       }
7573       
7574       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7575     } else {
7576       assert(ShiftAmt2 < ShiftAmt1);
7577       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7578
7579       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7580       if (I.getOpcode() == Instruction::Shl) {
7581         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7582                ShiftOp->getOpcode() == Instruction::AShr);
7583         Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7584                                             ConstantInt::get(Ty, ShiftDiff));
7585         
7586         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7587         return BinaryOperator::CreateAnd(Shift,
7588                                          ConstantInt::get(*Context, Mask));
7589       }
7590       
7591       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7592       if (I.getOpcode() == Instruction::LShr) {
7593         assert(ShiftOp->getOpcode() == Instruction::Shl);
7594         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7595         
7596         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7597         return BinaryOperator::CreateAnd(Shift,
7598                                          ConstantInt::get(*Context, Mask));
7599       }
7600       
7601       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7602     }
7603   }
7604   return 0;
7605 }
7606
7607
7608 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7609 /// expression.  If so, decompose it, returning some value X, such that Val is
7610 /// X*Scale+Offset.
7611 ///
7612 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7613                                         int &Offset, LLVMContext *Context) {
7614   assert(Val->getType() == Type::getInt32Ty(*Context) && 
7615          "Unexpected allocation size type!");
7616   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7617     Offset = CI->getZExtValue();
7618     Scale  = 0;
7619     return ConstantInt::get(Type::getInt32Ty(*Context), 0);
7620   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7621     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7622       if (I->getOpcode() == Instruction::Shl) {
7623         // This is a value scaled by '1 << the shift amt'.
7624         Scale = 1U << RHS->getZExtValue();
7625         Offset = 0;
7626         return I->getOperand(0);
7627       } else if (I->getOpcode() == Instruction::Mul) {
7628         // This value is scaled by 'RHS'.
7629         Scale = RHS->getZExtValue();
7630         Offset = 0;
7631         return I->getOperand(0);
7632       } else if (I->getOpcode() == Instruction::Add) {
7633         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7634         // where C1 is divisible by C2.
7635         unsigned SubScale;
7636         Value *SubVal = 
7637           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7638                                     Offset, Context);
7639         Offset += RHS->getZExtValue();
7640         Scale = SubScale;
7641         return SubVal;
7642       }
7643     }
7644   }
7645
7646   // Otherwise, we can't look past this.
7647   Scale = 1;
7648   Offset = 0;
7649   return Val;
7650 }
7651
7652
7653 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7654 /// try to eliminate the cast by moving the type information into the alloc.
7655 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7656                                                    AllocationInst &AI) {
7657   const PointerType *PTy = cast<PointerType>(CI.getType());
7658   
7659   BuilderTy AllocaBuilder(*Builder);
7660   AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7661   
7662   // Remove any uses of AI that are dead.
7663   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7664   
7665   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7666     Instruction *User = cast<Instruction>(*UI++);
7667     if (isInstructionTriviallyDead(User)) {
7668       while (UI != E && *UI == User)
7669         ++UI; // If this instruction uses AI more than once, don't break UI.
7670       
7671       ++NumDeadInst;
7672       DEBUG(errs() << "IC: DCE: " << *User << '\n');
7673       EraseInstFromFunction(*User);
7674     }
7675   }
7676
7677   // This requires TargetData to get the alloca alignment and size information.
7678   if (!TD) return 0;
7679
7680   // Get the type really allocated and the type casted to.
7681   const Type *AllocElTy = AI.getAllocatedType();
7682   const Type *CastElTy = PTy->getElementType();
7683   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7684
7685   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7686   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7687   if (CastElTyAlign < AllocElTyAlign) return 0;
7688
7689   // If the allocation has multiple uses, only promote it if we are strictly
7690   // increasing the alignment of the resultant allocation.  If we keep it the
7691   // same, we open the door to infinite loops of various kinds.  (A reference
7692   // from a dbg.declare doesn't count as a use for this purpose.)
7693   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7694       CastElTyAlign == AllocElTyAlign) return 0;
7695
7696   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7697   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7698   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7699
7700   // See if we can satisfy the modulus by pulling a scale out of the array
7701   // size argument.
7702   unsigned ArraySizeScale;
7703   int ArrayOffset;
7704   Value *NumElements = // See if the array size is a decomposable linear expr.
7705     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7706                               ArrayOffset, Context);
7707  
7708   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7709   // do the xform.
7710   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7711       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7712
7713   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7714   Value *Amt = 0;
7715   if (Scale == 1) {
7716     Amt = NumElements;
7717   } else {
7718     Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
7719     // Insert before the alloca, not before the cast.
7720     Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
7721   }
7722   
7723   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7724     Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
7725     Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
7726   }
7727   
7728   AllocationInst *New;
7729   if (isa<MallocInst>(AI))
7730     New = AllocaBuilder.CreateMalloc(CastElTy, Amt);
7731   else
7732     New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7733   New->setAlignment(AI.getAlignment());
7734   New->takeName(&AI);
7735   
7736   // If the allocation has one real use plus a dbg.declare, just remove the
7737   // declare.
7738   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7739     EraseInstFromFunction(*DI);
7740   }
7741   // If the allocation has multiple real uses, insert a cast and change all
7742   // things that used it to use the new cast.  This will also hack on CI, but it
7743   // will die soon.
7744   else if (!AI.hasOneUse()) {
7745     // New is the allocation instruction, pointer typed. AI is the original
7746     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7747     Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
7748     AI.replaceAllUsesWith(NewCast);
7749   }
7750   return ReplaceInstUsesWith(CI, New);
7751 }
7752
7753 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7754 /// and return it as type Ty without inserting any new casts and without
7755 /// changing the computed value.  This is used by code that tries to decide
7756 /// whether promoting or shrinking integer operations to wider or smaller types
7757 /// will allow us to eliminate a truncate or extend.
7758 ///
7759 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7760 /// extension operation if Ty is larger.
7761 ///
7762 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7763 /// should return true if trunc(V) can be computed by computing V in the smaller
7764 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7765 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7766 /// efficiently truncated.
7767 ///
7768 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7769 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7770 /// the final result.
7771 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7772                                               unsigned CastOpc,
7773                                               int &NumCastsRemoved){
7774   // We can always evaluate constants in another type.
7775   if (isa<Constant>(V))
7776     return true;
7777   
7778   Instruction *I = dyn_cast<Instruction>(V);
7779   if (!I) return false;
7780   
7781   const Type *OrigTy = V->getType();
7782   
7783   // If this is an extension or truncate, we can often eliminate it.
7784   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7785     // If this is a cast from the destination type, we can trivially eliminate
7786     // it, and this will remove a cast overall.
7787     if (I->getOperand(0)->getType() == Ty) {
7788       // If the first operand is itself a cast, and is eliminable, do not count
7789       // this as an eliminable cast.  We would prefer to eliminate those two
7790       // casts first.
7791       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7792         ++NumCastsRemoved;
7793       return true;
7794     }
7795   }
7796
7797   // We can't extend or shrink something that has multiple uses: doing so would
7798   // require duplicating the instruction in general, which isn't profitable.
7799   if (!I->hasOneUse()) return false;
7800
7801   unsigned Opc = I->getOpcode();
7802   switch (Opc) {
7803   case Instruction::Add:
7804   case Instruction::Sub:
7805   case Instruction::Mul:
7806   case Instruction::And:
7807   case Instruction::Or:
7808   case Instruction::Xor:
7809     // These operators can all arbitrarily be extended or truncated.
7810     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7811                                       NumCastsRemoved) &&
7812            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7813                                       NumCastsRemoved);
7814
7815   case Instruction::UDiv:
7816   case Instruction::URem: {
7817     // UDiv and URem can be truncated if all the truncated bits are zero.
7818     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7819     uint32_t BitWidth = Ty->getScalarSizeInBits();
7820     if (BitWidth < OrigBitWidth) {
7821       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7822       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7823           MaskedValueIsZero(I->getOperand(1), Mask)) {
7824         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7825                                           NumCastsRemoved) &&
7826                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7827                                           NumCastsRemoved);
7828       }
7829     }
7830     break;
7831   }
7832   case Instruction::Shl:
7833     // If we are truncating the result of this SHL, and if it's a shift of a
7834     // constant amount, we can always perform a SHL in a smaller type.
7835     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7836       uint32_t BitWidth = Ty->getScalarSizeInBits();
7837       if (BitWidth < OrigTy->getScalarSizeInBits() &&
7838           CI->getLimitedValue(BitWidth) < BitWidth)
7839         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7840                                           NumCastsRemoved);
7841     }
7842     break;
7843   case Instruction::LShr:
7844     // If this is a truncate of a logical shr, we can truncate it to a smaller
7845     // lshr iff we know that the bits we would otherwise be shifting in are
7846     // already zeros.
7847     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7848       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7849       uint32_t BitWidth = Ty->getScalarSizeInBits();
7850       if (BitWidth < OrigBitWidth &&
7851           MaskedValueIsZero(I->getOperand(0),
7852             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7853           CI->getLimitedValue(BitWidth) < BitWidth) {
7854         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7855                                           NumCastsRemoved);
7856       }
7857     }
7858     break;
7859   case Instruction::ZExt:
7860   case Instruction::SExt:
7861   case Instruction::Trunc:
7862     // If this is the same kind of case as our original (e.g. zext+zext), we
7863     // can safely replace it.  Note that replacing it does not reduce the number
7864     // of casts in the input.
7865     if (Opc == CastOpc)
7866       return true;
7867
7868     // sext (zext ty1), ty2 -> zext ty2
7869     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7870       return true;
7871     break;
7872   case Instruction::Select: {
7873     SelectInst *SI = cast<SelectInst>(I);
7874     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7875                                       NumCastsRemoved) &&
7876            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7877                                       NumCastsRemoved);
7878   }
7879   case Instruction::PHI: {
7880     // We can change a phi if we can change all operands.
7881     PHINode *PN = cast<PHINode>(I);
7882     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7883       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7884                                       NumCastsRemoved))
7885         return false;
7886     return true;
7887   }
7888   default:
7889     // TODO: Can handle more cases here.
7890     break;
7891   }
7892   
7893   return false;
7894 }
7895
7896 /// EvaluateInDifferentType - Given an expression that 
7897 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7898 /// evaluate the expression.
7899 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7900                                              bool isSigned) {
7901   if (Constant *C = dyn_cast<Constant>(V))
7902     return ConstantExpr::getIntegerCast(C, Ty,
7903                                                isSigned /*Sext or ZExt*/);
7904
7905   // Otherwise, it must be an instruction.
7906   Instruction *I = cast<Instruction>(V);
7907   Instruction *Res = 0;
7908   unsigned Opc = I->getOpcode();
7909   switch (Opc) {
7910   case Instruction::Add:
7911   case Instruction::Sub:
7912   case Instruction::Mul:
7913   case Instruction::And:
7914   case Instruction::Or:
7915   case Instruction::Xor:
7916   case Instruction::AShr:
7917   case Instruction::LShr:
7918   case Instruction::Shl:
7919   case Instruction::UDiv:
7920   case Instruction::URem: {
7921     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7922     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7923     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7924     break;
7925   }    
7926   case Instruction::Trunc:
7927   case Instruction::ZExt:
7928   case Instruction::SExt:
7929     // If the source type of the cast is the type we're trying for then we can
7930     // just return the source.  There's no need to insert it because it is not
7931     // new.
7932     if (I->getOperand(0)->getType() == Ty)
7933       return I->getOperand(0);
7934     
7935     // Otherwise, must be the same type of cast, so just reinsert a new one.
7936     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7937                            Ty);
7938     break;
7939   case Instruction::Select: {
7940     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7941     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7942     Res = SelectInst::Create(I->getOperand(0), True, False);
7943     break;
7944   }
7945   case Instruction::PHI: {
7946     PHINode *OPN = cast<PHINode>(I);
7947     PHINode *NPN = PHINode::Create(Ty);
7948     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7949       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7950       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7951     }
7952     Res = NPN;
7953     break;
7954   }
7955   default: 
7956     // TODO: Can handle more cases here.
7957     llvm_unreachable("Unreachable!");
7958     break;
7959   }
7960   
7961   Res->takeName(I);
7962   return InsertNewInstBefore(Res, *I);
7963 }
7964
7965 /// @brief Implement the transforms common to all CastInst visitors.
7966 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7967   Value *Src = CI.getOperand(0);
7968
7969   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7970   // eliminate it now.
7971   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7972     if (Instruction::CastOps opc = 
7973         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7974       // The first cast (CSrc) is eliminable so we need to fix up or replace
7975       // the second cast (CI). CSrc will then have a good chance of being dead.
7976       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7977     }
7978   }
7979
7980   // If we are casting a select then fold the cast into the select
7981   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7982     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7983       return NV;
7984
7985   // If we are casting a PHI then fold the cast into the PHI
7986   if (isa<PHINode>(Src))
7987     if (Instruction *NV = FoldOpIntoPhi(CI))
7988       return NV;
7989   
7990   return 0;
7991 }
7992
7993 /// FindElementAtOffset - Given a type and a constant offset, determine whether
7994 /// or not there is a sequence of GEP indices into the type that will land us at
7995 /// the specified offset.  If so, fill them into NewIndices and return the
7996 /// resultant element type, otherwise return null.
7997 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
7998                                        SmallVectorImpl<Value*> &NewIndices,
7999                                        const TargetData *TD,
8000                                        LLVMContext *Context) {
8001   if (!TD) return 0;
8002   if (!Ty->isSized()) return 0;
8003   
8004   // Start with the index over the outer type.  Note that the type size
8005   // might be zero (even if the offset isn't zero) if the indexed type
8006   // is something like [0 x {int, int}]
8007   const Type *IntPtrTy = TD->getIntPtrType(*Context);
8008   int64_t FirstIdx = 0;
8009   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8010     FirstIdx = Offset/TySize;
8011     Offset -= FirstIdx*TySize;
8012     
8013     // Handle hosts where % returns negative instead of values [0..TySize).
8014     if (Offset < 0) {
8015       --FirstIdx;
8016       Offset += TySize;
8017       assert(Offset >= 0);
8018     }
8019     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8020   }
8021   
8022   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8023     
8024   // Index into the types.  If we fail, set OrigBase to null.
8025   while (Offset) {
8026     // Indexing into tail padding between struct/array elements.
8027     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8028       return 0;
8029     
8030     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8031       const StructLayout *SL = TD->getStructLayout(STy);
8032       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8033              "Offset must stay within the indexed type");
8034       
8035       unsigned Elt = SL->getElementContainingOffset(Offset);
8036       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8037       
8038       Offset -= SL->getElementOffset(Elt);
8039       Ty = STy->getElementType(Elt);
8040     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8041       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8042       assert(EltSize && "Cannot index into a zero-sized array");
8043       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8044       Offset %= EltSize;
8045       Ty = AT->getElementType();
8046     } else {
8047       // Otherwise, we can't index into the middle of this atomic type, bail.
8048       return 0;
8049     }
8050   }
8051   
8052   return Ty;
8053 }
8054
8055 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8056 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8057   Value *Src = CI.getOperand(0);
8058   
8059   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8060     // If casting the result of a getelementptr instruction with no offset, turn
8061     // this into a cast of the original pointer!
8062     if (GEP->hasAllZeroIndices()) {
8063       // Changing the cast operand is usually not a good idea but it is safe
8064       // here because the pointer operand is being replaced with another 
8065       // pointer operand so the opcode doesn't need to change.
8066       Worklist.Add(GEP);
8067       CI.setOperand(0, GEP->getOperand(0));
8068       return &CI;
8069     }
8070     
8071     // If the GEP has a single use, and the base pointer is a bitcast, and the
8072     // GEP computes a constant offset, see if we can convert these three
8073     // instructions into fewer.  This typically happens with unions and other
8074     // non-type-safe code.
8075     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8076       if (GEP->hasAllConstantIndices()) {
8077         // We are guaranteed to get a constant from EmitGEPOffset.
8078         ConstantInt *OffsetV =
8079                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8080         int64_t Offset = OffsetV->getSExtValue();
8081         
8082         // Get the base pointer input of the bitcast, and the type it points to.
8083         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8084         const Type *GEPIdxTy =
8085           cast<PointerType>(OrigBase->getType())->getElementType();
8086         SmallVector<Value*, 8> NewIndices;
8087         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8088           // If we were able to index down into an element, create the GEP
8089           // and bitcast the result.  This eliminates one bitcast, potentially
8090           // two.
8091           Value *NGEP = Builder->CreateGEP(OrigBase, NewIndices.begin(),
8092                                            NewIndices.end());
8093           NGEP->takeName(GEP);
8094           if (isa<Instruction>(NGEP) && cast<GEPOperator>(GEP)->isInBounds())
8095             cast<GEPOperator>(NGEP)->setIsInBounds(true);
8096           
8097           if (isa<BitCastInst>(CI))
8098             return new BitCastInst(NGEP, CI.getType());
8099           assert(isa<PtrToIntInst>(CI));
8100           return new PtrToIntInst(NGEP, CI.getType());
8101         }
8102       }      
8103     }
8104   }
8105     
8106   return commonCastTransforms(CI);
8107 }
8108
8109 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8110 /// type like i42.  We don't want to introduce operations on random non-legal
8111 /// integer types where they don't already exist in the code.  In the future,
8112 /// we should consider making this based off target-data, so that 32-bit targets
8113 /// won't get i64 operations etc.
8114 static bool isSafeIntegerType(const Type *Ty) {
8115   switch (Ty->getPrimitiveSizeInBits()) {
8116   case 8:
8117   case 16:
8118   case 32:
8119   case 64:
8120     return true;
8121   default: 
8122     return false;
8123   }
8124 }
8125
8126 /// commonIntCastTransforms - This function implements the common transforms
8127 /// for trunc, zext, and sext.
8128 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8129   if (Instruction *Result = commonCastTransforms(CI))
8130     return Result;
8131
8132   Value *Src = CI.getOperand(0);
8133   const Type *SrcTy = Src->getType();
8134   const Type *DestTy = CI.getType();
8135   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8136   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8137
8138   // See if we can simplify any instructions used by the LHS whose sole 
8139   // purpose is to compute bits we don't care about.
8140   if (SimplifyDemandedInstructionBits(CI))
8141     return &CI;
8142
8143   // If the source isn't an instruction or has more than one use then we
8144   // can't do anything more. 
8145   Instruction *SrcI = dyn_cast<Instruction>(Src);
8146   if (!SrcI || !Src->hasOneUse())
8147     return 0;
8148
8149   // Attempt to propagate the cast into the instruction for int->int casts.
8150   int NumCastsRemoved = 0;
8151   // Only do this if the dest type is a simple type, don't convert the
8152   // expression tree to something weird like i93 unless the source is also
8153   // strange.
8154   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8155        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8156       CanEvaluateInDifferentType(SrcI, DestTy,
8157                                  CI.getOpcode(), NumCastsRemoved)) {
8158     // If this cast is a truncate, evaluting in a different type always
8159     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8160     // we need to do an AND to maintain the clear top-part of the computation,
8161     // so we require that the input have eliminated at least one cast.  If this
8162     // is a sign extension, we insert two new casts (to do the extension) so we
8163     // require that two casts have been eliminated.
8164     bool DoXForm = false;
8165     bool JustReplace = false;
8166     switch (CI.getOpcode()) {
8167     default:
8168       // All the others use floating point so we shouldn't actually 
8169       // get here because of the check above.
8170       llvm_unreachable("Unknown cast type");
8171     case Instruction::Trunc:
8172       DoXForm = true;
8173       break;
8174     case Instruction::ZExt: {
8175       DoXForm = NumCastsRemoved >= 1;
8176       if (!DoXForm && 0) {
8177         // If it's unnecessary to issue an AND to clear the high bits, it's
8178         // always profitable to do this xform.
8179         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8180         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8181         if (MaskedValueIsZero(TryRes, Mask))
8182           return ReplaceInstUsesWith(CI, TryRes);
8183         
8184         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8185           if (TryI->use_empty())
8186             EraseInstFromFunction(*TryI);
8187       }
8188       break;
8189     }
8190     case Instruction::SExt: {
8191       DoXForm = NumCastsRemoved >= 2;
8192       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8193         // If we do not have to emit the truncate + sext pair, then it's always
8194         // profitable to do this xform.
8195         //
8196         // It's not safe to eliminate the trunc + sext pair if one of the
8197         // eliminated cast is a truncate. e.g.
8198         // t2 = trunc i32 t1 to i16
8199         // t3 = sext i16 t2 to i32
8200         // !=
8201         // i32 t1
8202         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8203         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8204         if (NumSignBits > (DestBitSize - SrcBitSize))
8205           return ReplaceInstUsesWith(CI, TryRes);
8206         
8207         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8208           if (TryI->use_empty())
8209             EraseInstFromFunction(*TryI);
8210       }
8211       break;
8212     }
8213     }
8214     
8215     if (DoXForm) {
8216       DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8217             " to avoid cast: " << CI);
8218       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8219                                            CI.getOpcode() == Instruction::SExt);
8220       if (JustReplace)
8221         // Just replace this cast with the result.
8222         return ReplaceInstUsesWith(CI, Res);
8223
8224       assert(Res->getType() == DestTy);
8225       switch (CI.getOpcode()) {
8226       default: llvm_unreachable("Unknown cast type!");
8227       case Instruction::Trunc:
8228         // Just replace this cast with the result.
8229         return ReplaceInstUsesWith(CI, Res);
8230       case Instruction::ZExt: {
8231         assert(SrcBitSize < DestBitSize && "Not a zext?");
8232
8233         // If the high bits are already zero, just replace this cast with the
8234         // result.
8235         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8236         if (MaskedValueIsZero(Res, Mask))
8237           return ReplaceInstUsesWith(CI, Res);
8238
8239         // We need to emit an AND to clear the high bits.
8240         Constant *C = ConstantInt::get(*Context, 
8241                                  APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8242         return BinaryOperator::CreateAnd(Res, C);
8243       }
8244       case Instruction::SExt: {
8245         // If the high bits are already filled with sign bit, just replace this
8246         // cast with the result.
8247         unsigned NumSignBits = ComputeNumSignBits(Res);
8248         if (NumSignBits > (DestBitSize - SrcBitSize))
8249           return ReplaceInstUsesWith(CI, Res);
8250
8251         // We need to emit a cast to truncate, then a cast to sext.
8252         return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
8253       }
8254       }
8255     }
8256   }
8257   
8258   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8259   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8260
8261   switch (SrcI->getOpcode()) {
8262   case Instruction::Add:
8263   case Instruction::Mul:
8264   case Instruction::And:
8265   case Instruction::Or:
8266   case Instruction::Xor:
8267     // If we are discarding information, rewrite.
8268     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8269       // Don't insert two casts unless at least one can be eliminated.
8270       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8271           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8272         Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8273         Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8274         return BinaryOperator::Create(
8275             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8276       }
8277     }
8278
8279     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8280     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8281         SrcI->getOpcode() == Instruction::Xor &&
8282         Op1 == ConstantInt::getTrue(*Context) &&
8283         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8284       Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
8285       return BinaryOperator::CreateXor(New,
8286                                       ConstantInt::get(CI.getType(), 1));
8287     }
8288     break;
8289
8290   case Instruction::Shl: {
8291     // Canonicalize trunc inside shl, if we can.
8292     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8293     if (CI && DestBitSize < SrcBitSize &&
8294         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8295       Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8296       Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8297       return BinaryOperator::CreateShl(Op0c, Op1c);
8298     }
8299     break;
8300   }
8301   }
8302   return 0;
8303 }
8304
8305 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8306   if (Instruction *Result = commonIntCastTransforms(CI))
8307     return Result;
8308   
8309   Value *Src = CI.getOperand(0);
8310   const Type *Ty = CI.getType();
8311   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8312   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8313
8314   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8315   if (DestBitWidth == 1) {
8316     Constant *One = ConstantInt::get(Src->getType(), 1);
8317     Src = Builder->CreateAnd(Src, One, "tmp");
8318     Value *Zero = Constant::getNullValue(Src->getType());
8319     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8320   }
8321
8322   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8323   ConstantInt *ShAmtV = 0;
8324   Value *ShiftOp = 0;
8325   if (Src->hasOneUse() &&
8326       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8327     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8328     
8329     // Get a mask for the bits shifting in.
8330     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8331     if (MaskedValueIsZero(ShiftOp, Mask)) {
8332       if (ShAmt >= DestBitWidth)        // All zeros.
8333         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8334       
8335       // Okay, we can shrink this.  Truncate the input, then return a new
8336       // shift.
8337       Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
8338       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8339       return BinaryOperator::CreateLShr(V1, V2);
8340     }
8341   }
8342   
8343   return 0;
8344 }
8345
8346 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8347 /// in order to eliminate the icmp.
8348 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8349                                              bool DoXform) {
8350   // If we are just checking for a icmp eq of a single bit and zext'ing it
8351   // to an integer, then shift the bit to the appropriate place and then
8352   // cast to integer to avoid the comparison.
8353   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8354     const APInt &Op1CV = Op1C->getValue();
8355       
8356     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8357     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8358     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8359         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8360       if (!DoXform) return ICI;
8361
8362       Value *In = ICI->getOperand(0);
8363       Value *Sh = ConstantInt::get(In->getType(),
8364                                    In->getType()->getScalarSizeInBits()-1);
8365       In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
8366       if (In->getType() != CI.getType())
8367         In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
8368
8369       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8370         Constant *One = ConstantInt::get(In->getType(), 1);
8371         In = Builder->CreateXor(In, One, In->getName()+".not");
8372       }
8373
8374       return ReplaceInstUsesWith(CI, In);
8375     }
8376       
8377       
8378       
8379     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8380     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8381     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8382     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8383     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8384     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8385     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8386     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8387     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8388         // This only works for EQ and NE
8389         ICI->isEquality()) {
8390       // If Op1C some other power of two, convert:
8391       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8392       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8393       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8394       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8395         
8396       APInt KnownZeroMask(~KnownZero);
8397       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8398         if (!DoXform) return ICI;
8399
8400         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8401         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8402           // (X&4) == 2 --> false
8403           // (X&4) != 2 --> true
8404           Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8405           Res = ConstantExpr::getZExt(Res, CI.getType());
8406           return ReplaceInstUsesWith(CI, Res);
8407         }
8408           
8409         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8410         Value *In = ICI->getOperand(0);
8411         if (ShiftAmt) {
8412           // Perform a logical shr by shiftamt.
8413           // Insert the shift to put the result in the low bit.
8414           In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8415                                    In->getName()+".lobit");
8416         }
8417           
8418         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8419           Constant *One = ConstantInt::get(In->getType(), 1);
8420           In = Builder->CreateXor(In, One, "tmp");
8421         }
8422           
8423         if (CI.getType() == In->getType())
8424           return ReplaceInstUsesWith(CI, In);
8425         else
8426           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8427       }
8428     }
8429   }
8430
8431   return 0;
8432 }
8433
8434 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8435   // If one of the common conversion will work ..
8436   if (Instruction *Result = commonIntCastTransforms(CI))
8437     return Result;
8438
8439   Value *Src = CI.getOperand(0);
8440
8441   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8442   // types and if the sizes are just right we can convert this into a logical
8443   // 'and' which will be much cheaper than the pair of casts.
8444   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8445     // Get the sizes of the types involved.  We know that the intermediate type
8446     // will be smaller than A or C, but don't know the relation between A and C.
8447     Value *A = CSrc->getOperand(0);
8448     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8449     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8450     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8451     // If we're actually extending zero bits, then if
8452     // SrcSize <  DstSize: zext(a & mask)
8453     // SrcSize == DstSize: a & mask
8454     // SrcSize  > DstSize: trunc(a) & mask
8455     if (SrcSize < DstSize) {
8456       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8457       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8458       Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
8459       return new ZExtInst(And, CI.getType());
8460     }
8461     
8462     if (SrcSize == DstSize) {
8463       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8464       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8465                                                            AndValue));
8466     }
8467     if (SrcSize > DstSize) {
8468       Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
8469       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8470       return BinaryOperator::CreateAnd(Trunc, 
8471                                        ConstantInt::get(Trunc->getType(),
8472                                                                AndValue));
8473     }
8474   }
8475
8476   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8477     return transformZExtICmp(ICI, CI);
8478
8479   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8480   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8481     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8482     // of the (zext icmp) will be transformed.
8483     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8484     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8485     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8486         (transformZExtICmp(LHS, CI, false) ||
8487          transformZExtICmp(RHS, CI, false))) {
8488       Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8489       Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
8490       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8491     }
8492   }
8493
8494   // zext(trunc(t) & C) -> (t & zext(C)).
8495   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8496     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8497       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8498         Value *TI0 = TI->getOperand(0);
8499         if (TI0->getType() == CI.getType())
8500           return
8501             BinaryOperator::CreateAnd(TI0,
8502                                 ConstantExpr::getZExt(C, CI.getType()));
8503       }
8504
8505   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8506   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8507     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8508       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8509         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8510             And->getOperand(1) == C)
8511           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8512             Value *TI0 = TI->getOperand(0);
8513             if (TI0->getType() == CI.getType()) {
8514               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8515               Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
8516               return BinaryOperator::CreateXor(NewAnd, ZC);
8517             }
8518           }
8519
8520   return 0;
8521 }
8522
8523 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8524   if (Instruction *I = commonIntCastTransforms(CI))
8525     return I;
8526   
8527   Value *Src = CI.getOperand(0);
8528   
8529   // Canonicalize sign-extend from i1 to a select.
8530   if (Src->getType() == Type::getInt1Ty(*Context))
8531     return SelectInst::Create(Src,
8532                               Constant::getAllOnesValue(CI.getType()),
8533                               Constant::getNullValue(CI.getType()));
8534
8535   // See if the value being truncated is already sign extended.  If so, just
8536   // eliminate the trunc/sext pair.
8537   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8538     Value *Op = cast<User>(Src)->getOperand(0);
8539     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8540     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8541     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8542     unsigned NumSignBits = ComputeNumSignBits(Op);
8543
8544     if (OpBits == DestBits) {
8545       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8546       // bits, it is already ready.
8547       if (NumSignBits > DestBits-MidBits)
8548         return ReplaceInstUsesWith(CI, Op);
8549     } else if (OpBits < DestBits) {
8550       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8551       // bits, just sext from i32.
8552       if (NumSignBits > OpBits-MidBits)
8553         return new SExtInst(Op, CI.getType(), "tmp");
8554     } else {
8555       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8556       // bits, just truncate to i32.
8557       if (NumSignBits > OpBits-MidBits)
8558         return new TruncInst(Op, CI.getType(), "tmp");
8559     }
8560   }
8561
8562   // If the input is a shl/ashr pair of a same constant, then this is a sign
8563   // extension from a smaller value.  If we could trust arbitrary bitwidth
8564   // integers, we could turn this into a truncate to the smaller bit and then
8565   // use a sext for the whole extension.  Since we don't, look deeper and check
8566   // for a truncate.  If the source and dest are the same type, eliminate the
8567   // trunc and extend and just do shifts.  For example, turn:
8568   //   %a = trunc i32 %i to i8
8569   //   %b = shl i8 %a, 6
8570   //   %c = ashr i8 %b, 6
8571   //   %d = sext i8 %c to i32
8572   // into:
8573   //   %a = shl i32 %i, 30
8574   //   %d = ashr i32 %a, 30
8575   Value *A = 0;
8576   ConstantInt *BA = 0, *CA = 0;
8577   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8578                         m_ConstantInt(CA))) &&
8579       BA == CA && isa<TruncInst>(A)) {
8580     Value *I = cast<TruncInst>(A)->getOperand(0);
8581     if (I->getType() == CI.getType()) {
8582       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8583       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8584       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8585       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8586       I = Builder->CreateShl(I, ShAmtV, CI.getName());
8587       return BinaryOperator::CreateAShr(I, ShAmtV);
8588     }
8589   }
8590   
8591   return 0;
8592 }
8593
8594 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8595 /// in the specified FP type without changing its value.
8596 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8597                               LLVMContext *Context) {
8598   bool losesInfo;
8599   APFloat F = CFP->getValueAPF();
8600   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8601   if (!losesInfo)
8602     return ConstantFP::get(*Context, F);
8603   return 0;
8604 }
8605
8606 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8607 /// through it until we get the source value.
8608 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8609   if (Instruction *I = dyn_cast<Instruction>(V))
8610     if (I->getOpcode() == Instruction::FPExt)
8611       return LookThroughFPExtensions(I->getOperand(0), Context);
8612   
8613   // If this value is a constant, return the constant in the smallest FP type
8614   // that can accurately represent it.  This allows us to turn
8615   // (float)((double)X+2.0) into x+2.0f.
8616   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8617     if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
8618       return V;  // No constant folding of this.
8619     // See if the value can be truncated to float and then reextended.
8620     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8621       return V;
8622     if (CFP->getType() == Type::getDoubleTy(*Context))
8623       return V;  // Won't shrink.
8624     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8625       return V;
8626     // Don't try to shrink to various long double types.
8627   }
8628   
8629   return V;
8630 }
8631
8632 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8633   if (Instruction *I = commonCastTransforms(CI))
8634     return I;
8635   
8636   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8637   // smaller than the destination type, we can eliminate the truncate by doing
8638   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8639   // many builtins (sqrt, etc).
8640   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8641   if (OpI && OpI->hasOneUse()) {
8642     switch (OpI->getOpcode()) {
8643     default: break;
8644     case Instruction::FAdd:
8645     case Instruction::FSub:
8646     case Instruction::FMul:
8647     case Instruction::FDiv:
8648     case Instruction::FRem:
8649       const Type *SrcTy = OpI->getType();
8650       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8651       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8652       if (LHSTrunc->getType() != SrcTy && 
8653           RHSTrunc->getType() != SrcTy) {
8654         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8655         // If the source types were both smaller than the destination type of
8656         // the cast, do this xform.
8657         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8658             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8659           LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8660           RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
8661           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8662         }
8663       }
8664       break;  
8665     }
8666   }
8667   return 0;
8668 }
8669
8670 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8671   return commonCastTransforms(CI);
8672 }
8673
8674 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8675   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8676   if (OpI == 0)
8677     return commonCastTransforms(FI);
8678
8679   // fptoui(uitofp(X)) --> X
8680   // fptoui(sitofp(X)) --> X
8681   // This is safe if the intermediate type has enough bits in its mantissa to
8682   // accurately represent all values of X.  For example, do not do this with
8683   // i64->float->i64.  This is also safe for sitofp case, because any negative
8684   // 'X' value would cause an undefined result for the fptoui. 
8685   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8686       OpI->getOperand(0)->getType() == FI.getType() &&
8687       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8688                     OpI->getType()->getFPMantissaWidth())
8689     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8690
8691   return commonCastTransforms(FI);
8692 }
8693
8694 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8695   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8696   if (OpI == 0)
8697     return commonCastTransforms(FI);
8698   
8699   // fptosi(sitofp(X)) --> X
8700   // fptosi(uitofp(X)) --> X
8701   // This is safe if the intermediate type has enough bits in its mantissa to
8702   // accurately represent all values of X.  For example, do not do this with
8703   // i64->float->i64.  This is also safe for sitofp case, because any negative
8704   // 'X' value would cause an undefined result for the fptoui. 
8705   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8706       OpI->getOperand(0)->getType() == FI.getType() &&
8707       (int)FI.getType()->getScalarSizeInBits() <=
8708                     OpI->getType()->getFPMantissaWidth())
8709     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8710   
8711   return commonCastTransforms(FI);
8712 }
8713
8714 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8715   return commonCastTransforms(CI);
8716 }
8717
8718 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8719   return commonCastTransforms(CI);
8720 }
8721
8722 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8723   // If the destination integer type is smaller than the intptr_t type for
8724   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8725   // trunc to be exposed to other transforms.  Don't do this for extending
8726   // ptrtoint's, because we don't know if the target sign or zero extends its
8727   // pointers.
8728   if (TD &&
8729       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8730     Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8731                                        TD->getIntPtrType(CI.getContext()),
8732                                        "tmp");
8733     return new TruncInst(P, CI.getType());
8734   }
8735   
8736   return commonPointerCastTransforms(CI);
8737 }
8738
8739 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8740   // If the source integer type is larger than the intptr_t type for
8741   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8742   // allows the trunc to be exposed to other transforms.  Don't do this for
8743   // extending inttoptr's, because we don't know if the target sign or zero
8744   // extends to pointers.
8745   if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
8746       TD->getPointerSizeInBits()) {
8747     Value *P = Builder->CreateTrunc(CI.getOperand(0),
8748                                     TD->getIntPtrType(CI.getContext()), "tmp");
8749     return new IntToPtrInst(P, CI.getType());
8750   }
8751   
8752   if (Instruction *I = commonCastTransforms(CI))
8753     return I;
8754
8755   return 0;
8756 }
8757
8758 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8759   // If the operands are integer typed then apply the integer transforms,
8760   // otherwise just apply the common ones.
8761   Value *Src = CI.getOperand(0);
8762   const Type *SrcTy = Src->getType();
8763   const Type *DestTy = CI.getType();
8764
8765   if (isa<PointerType>(SrcTy)) {
8766     if (Instruction *I = commonPointerCastTransforms(CI))
8767       return I;
8768   } else {
8769     if (Instruction *Result = commonCastTransforms(CI))
8770       return Result;
8771   }
8772
8773
8774   // Get rid of casts from one type to the same type. These are useless and can
8775   // be replaced by the operand.
8776   if (DestTy == Src->getType())
8777     return ReplaceInstUsesWith(CI, Src);
8778
8779   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8780     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8781     const Type *DstElTy = DstPTy->getElementType();
8782     const Type *SrcElTy = SrcPTy->getElementType();
8783     
8784     // If the address spaces don't match, don't eliminate the bitcast, which is
8785     // required for changing types.
8786     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8787       return 0;
8788     
8789     // If we are casting a malloc or alloca to a pointer to a type of the same
8790     // size, rewrite the allocation instruction to allocate the "right" type.
8791     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8792       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8793         return V;
8794     
8795     // If the source and destination are pointers, and this cast is equivalent
8796     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8797     // This can enhance SROA and other transforms that want type-safe pointers.
8798     Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
8799     unsigned NumZeros = 0;
8800     while (SrcElTy != DstElTy && 
8801            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8802            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8803       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8804       ++NumZeros;
8805     }
8806
8807     // If we found a path from the src to dest, create the getelementptr now.
8808     if (SrcElTy == DstElTy) {
8809       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8810       Instruction *GEP = GetElementPtrInst::Create(Src,
8811                                                    Idxs.begin(), Idxs.end(), "",
8812                                                    ((Instruction*) NULL));
8813       cast<GEPOperator>(GEP)->setIsInBounds(true);
8814       return GEP;
8815     }
8816   }
8817
8818   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8819     if (DestVTy->getNumElements() == 1) {
8820       if (!isa<VectorType>(SrcTy)) {
8821         Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
8822         return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
8823                             Constant::getNullValue(Type::getInt32Ty(*Context)));
8824       }
8825       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8826     }
8827   }
8828
8829   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8830     if (SrcVTy->getNumElements() == 1) {
8831       if (!isa<VectorType>(DestTy)) {
8832         Value *Elem = 
8833           Builder->CreateExtractElement(Src,
8834                             Constant::getNullValue(Type::getInt32Ty(*Context)));
8835         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8836       }
8837     }
8838   }
8839
8840   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8841     if (SVI->hasOneUse()) {
8842       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8843       // a bitconvert to a vector with the same # elts.
8844       if (isa<VectorType>(DestTy) && 
8845           cast<VectorType>(DestTy)->getNumElements() ==
8846                 SVI->getType()->getNumElements() &&
8847           SVI->getType()->getNumElements() ==
8848             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8849         CastInst *Tmp;
8850         // If either of the operands is a cast from CI.getType(), then
8851         // evaluating the shuffle in the casted destination's type will allow
8852         // us to eliminate at least one cast.
8853         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8854              Tmp->getOperand(0)->getType() == DestTy) ||
8855             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8856              Tmp->getOperand(0)->getType() == DestTy)) {
8857           Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8858           Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
8859           // Return a new shuffle vector.  Use the same element ID's, as we
8860           // know the vector types match #elts.
8861           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8862         }
8863       }
8864     }
8865   }
8866   return 0;
8867 }
8868
8869 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8870 ///   %C = or %A, %B
8871 ///   %D = select %cond, %C, %A
8872 /// into:
8873 ///   %C = select %cond, %B, 0
8874 ///   %D = or %A, %C
8875 ///
8876 /// Assuming that the specified instruction is an operand to the select, return
8877 /// a bitmask indicating which operands of this instruction are foldable if they
8878 /// equal the other incoming value of the select.
8879 ///
8880 static unsigned GetSelectFoldableOperands(Instruction *I) {
8881   switch (I->getOpcode()) {
8882   case Instruction::Add:
8883   case Instruction::Mul:
8884   case Instruction::And:
8885   case Instruction::Or:
8886   case Instruction::Xor:
8887     return 3;              // Can fold through either operand.
8888   case Instruction::Sub:   // Can only fold on the amount subtracted.
8889   case Instruction::Shl:   // Can only fold on the shift amount.
8890   case Instruction::LShr:
8891   case Instruction::AShr:
8892     return 1;
8893   default:
8894     return 0;              // Cannot fold
8895   }
8896 }
8897
8898 /// GetSelectFoldableConstant - For the same transformation as the previous
8899 /// function, return the identity constant that goes into the select.
8900 static Constant *GetSelectFoldableConstant(Instruction *I,
8901                                            LLVMContext *Context) {
8902   switch (I->getOpcode()) {
8903   default: llvm_unreachable("This cannot happen!");
8904   case Instruction::Add:
8905   case Instruction::Sub:
8906   case Instruction::Or:
8907   case Instruction::Xor:
8908   case Instruction::Shl:
8909   case Instruction::LShr:
8910   case Instruction::AShr:
8911     return Constant::getNullValue(I->getType());
8912   case Instruction::And:
8913     return Constant::getAllOnesValue(I->getType());
8914   case Instruction::Mul:
8915     return ConstantInt::get(I->getType(), 1);
8916   }
8917 }
8918
8919 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8920 /// have the same opcode and only one use each.  Try to simplify this.
8921 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8922                                           Instruction *FI) {
8923   if (TI->getNumOperands() == 1) {
8924     // If this is a non-volatile load or a cast from the same type,
8925     // merge.
8926     if (TI->isCast()) {
8927       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8928         return 0;
8929     } else {
8930       return 0;  // unknown unary op.
8931     }
8932
8933     // Fold this by inserting a select from the input values.
8934     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8935                                           FI->getOperand(0), SI.getName()+".v");
8936     InsertNewInstBefore(NewSI, SI);
8937     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8938                             TI->getType());
8939   }
8940
8941   // Only handle binary operators here.
8942   if (!isa<BinaryOperator>(TI))
8943     return 0;
8944
8945   // Figure out if the operations have any operands in common.
8946   Value *MatchOp, *OtherOpT, *OtherOpF;
8947   bool MatchIsOpZero;
8948   if (TI->getOperand(0) == FI->getOperand(0)) {
8949     MatchOp  = TI->getOperand(0);
8950     OtherOpT = TI->getOperand(1);
8951     OtherOpF = FI->getOperand(1);
8952     MatchIsOpZero = true;
8953   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8954     MatchOp  = TI->getOperand(1);
8955     OtherOpT = TI->getOperand(0);
8956     OtherOpF = FI->getOperand(0);
8957     MatchIsOpZero = false;
8958   } else if (!TI->isCommutative()) {
8959     return 0;
8960   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8961     MatchOp  = TI->getOperand(0);
8962     OtherOpT = TI->getOperand(1);
8963     OtherOpF = FI->getOperand(0);
8964     MatchIsOpZero = true;
8965   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8966     MatchOp  = TI->getOperand(1);
8967     OtherOpT = TI->getOperand(0);
8968     OtherOpF = FI->getOperand(1);
8969     MatchIsOpZero = true;
8970   } else {
8971     return 0;
8972   }
8973
8974   // If we reach here, they do have operations in common.
8975   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8976                                          OtherOpF, SI.getName()+".v");
8977   InsertNewInstBefore(NewSI, SI);
8978
8979   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8980     if (MatchIsOpZero)
8981       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8982     else
8983       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8984   }
8985   llvm_unreachable("Shouldn't get here");
8986   return 0;
8987 }
8988
8989 static bool isSelect01(Constant *C1, Constant *C2) {
8990   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
8991   if (!C1I)
8992     return false;
8993   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
8994   if (!C2I)
8995     return false;
8996   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
8997 }
8998
8999 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9000 /// facilitate further optimization.
9001 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9002                                             Value *FalseVal) {
9003   // See the comment above GetSelectFoldableOperands for a description of the
9004   // transformation we are doing here.
9005   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9006     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9007         !isa<Constant>(FalseVal)) {
9008       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9009         unsigned OpToFold = 0;
9010         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9011           OpToFold = 1;
9012         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9013           OpToFold = 2;
9014         }
9015
9016         if (OpToFold) {
9017           Constant *C = GetSelectFoldableConstant(TVI, Context);
9018           Value *OOp = TVI->getOperand(2-OpToFold);
9019           // Avoid creating select between 2 constants unless it's selecting
9020           // between 0 and 1.
9021           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9022             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9023             InsertNewInstBefore(NewSel, SI);
9024             NewSel->takeName(TVI);
9025             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9026               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9027             llvm_unreachable("Unknown instruction!!");
9028           }
9029         }
9030       }
9031     }
9032   }
9033
9034   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9035     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9036         !isa<Constant>(TrueVal)) {
9037       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9038         unsigned OpToFold = 0;
9039         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9040           OpToFold = 1;
9041         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9042           OpToFold = 2;
9043         }
9044
9045         if (OpToFold) {
9046           Constant *C = GetSelectFoldableConstant(FVI, Context);
9047           Value *OOp = FVI->getOperand(2-OpToFold);
9048           // Avoid creating select between 2 constants unless it's selecting
9049           // between 0 and 1.
9050           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9051             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9052             InsertNewInstBefore(NewSel, SI);
9053             NewSel->takeName(FVI);
9054             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9055               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9056             llvm_unreachable("Unknown instruction!!");
9057           }
9058         }
9059       }
9060     }
9061   }
9062
9063   return 0;
9064 }
9065
9066 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9067 /// ICmpInst as its first operand.
9068 ///
9069 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9070                                                    ICmpInst *ICI) {
9071   bool Changed = false;
9072   ICmpInst::Predicate Pred = ICI->getPredicate();
9073   Value *CmpLHS = ICI->getOperand(0);
9074   Value *CmpRHS = ICI->getOperand(1);
9075   Value *TrueVal = SI.getTrueValue();
9076   Value *FalseVal = SI.getFalseValue();
9077
9078   // Check cases where the comparison is with a constant that
9079   // can be adjusted to fit the min/max idiom. We may edit ICI in
9080   // place here, so make sure the select is the only user.
9081   if (ICI->hasOneUse())
9082     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9083       switch (Pred) {
9084       default: break;
9085       case ICmpInst::ICMP_ULT:
9086       case ICmpInst::ICMP_SLT: {
9087         // X < MIN ? T : F  -->  F
9088         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9089           return ReplaceInstUsesWith(SI, FalseVal);
9090         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9091         Constant *AdjustedRHS = SubOne(CI);
9092         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9093             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9094           Pred = ICmpInst::getSwappedPredicate(Pred);
9095           CmpRHS = AdjustedRHS;
9096           std::swap(FalseVal, TrueVal);
9097           ICI->setPredicate(Pred);
9098           ICI->setOperand(1, CmpRHS);
9099           SI.setOperand(1, TrueVal);
9100           SI.setOperand(2, FalseVal);
9101           Changed = true;
9102         }
9103         break;
9104       }
9105       case ICmpInst::ICMP_UGT:
9106       case ICmpInst::ICMP_SGT: {
9107         // X > MAX ? T : F  -->  F
9108         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9109           return ReplaceInstUsesWith(SI, FalseVal);
9110         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9111         Constant *AdjustedRHS = AddOne(CI);
9112         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9113             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9114           Pred = ICmpInst::getSwappedPredicate(Pred);
9115           CmpRHS = AdjustedRHS;
9116           std::swap(FalseVal, TrueVal);
9117           ICI->setPredicate(Pred);
9118           ICI->setOperand(1, CmpRHS);
9119           SI.setOperand(1, TrueVal);
9120           SI.setOperand(2, FalseVal);
9121           Changed = true;
9122         }
9123         break;
9124       }
9125       }
9126
9127       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9128       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9129       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9130       if (match(TrueVal, m_ConstantInt<-1>()) &&
9131           match(FalseVal, m_ConstantInt<0>()))
9132         Pred = ICI->getPredicate();
9133       else if (match(TrueVal, m_ConstantInt<0>()) &&
9134                match(FalseVal, m_ConstantInt<-1>()))
9135         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9136       
9137       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9138         // If we are just checking for a icmp eq of a single bit and zext'ing it
9139         // to an integer, then shift the bit to the appropriate place and then
9140         // cast to integer to avoid the comparison.
9141         const APInt &Op1CV = CI->getValue();
9142     
9143         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9144         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9145         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9146             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9147           Value *In = ICI->getOperand(0);
9148           Value *Sh = ConstantInt::get(In->getType(),
9149                                        In->getType()->getScalarSizeInBits()-1);
9150           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9151                                                         In->getName()+".lobit"),
9152                                    *ICI);
9153           if (In->getType() != SI.getType())
9154             In = CastInst::CreateIntegerCast(In, SI.getType(),
9155                                              true/*SExt*/, "tmp", ICI);
9156     
9157           if (Pred == ICmpInst::ICMP_SGT)
9158             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9159                                        In->getName()+".not"), *ICI);
9160     
9161           return ReplaceInstUsesWith(SI, In);
9162         }
9163       }
9164     }
9165
9166   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9167     // Transform (X == Y) ? X : Y  -> Y
9168     if (Pred == ICmpInst::ICMP_EQ)
9169       return ReplaceInstUsesWith(SI, FalseVal);
9170     // Transform (X != Y) ? X : Y  -> X
9171     if (Pred == ICmpInst::ICMP_NE)
9172       return ReplaceInstUsesWith(SI, TrueVal);
9173     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9174
9175   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9176     // Transform (X == Y) ? Y : X  -> X
9177     if (Pred == ICmpInst::ICMP_EQ)
9178       return ReplaceInstUsesWith(SI, FalseVal);
9179     // Transform (X != Y) ? Y : X  -> Y
9180     if (Pred == ICmpInst::ICMP_NE)
9181       return ReplaceInstUsesWith(SI, TrueVal);
9182     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9183   }
9184
9185   /// NOTE: if we wanted to, this is where to detect integer ABS
9186
9187   return Changed ? &SI : 0;
9188 }
9189
9190 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9191   Value *CondVal = SI.getCondition();
9192   Value *TrueVal = SI.getTrueValue();
9193   Value *FalseVal = SI.getFalseValue();
9194
9195   // select true, X, Y  -> X
9196   // select false, X, Y -> Y
9197   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9198     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9199
9200   // select C, X, X -> X
9201   if (TrueVal == FalseVal)
9202     return ReplaceInstUsesWith(SI, TrueVal);
9203
9204   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9205     return ReplaceInstUsesWith(SI, FalseVal);
9206   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9207     return ReplaceInstUsesWith(SI, TrueVal);
9208   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9209     if (isa<Constant>(TrueVal))
9210       return ReplaceInstUsesWith(SI, TrueVal);
9211     else
9212       return ReplaceInstUsesWith(SI, FalseVal);
9213   }
9214
9215   if (SI.getType() == Type::getInt1Ty(*Context)) {
9216     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9217       if (C->getZExtValue()) {
9218         // Change: A = select B, true, C --> A = or B, C
9219         return BinaryOperator::CreateOr(CondVal, FalseVal);
9220       } else {
9221         // Change: A = select B, false, C --> A = and !B, C
9222         Value *NotCond =
9223           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9224                                              "not."+CondVal->getName()), SI);
9225         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9226       }
9227     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9228       if (C->getZExtValue() == false) {
9229         // Change: A = select B, C, false --> A = and B, C
9230         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9231       } else {
9232         // Change: A = select B, C, true --> A = or !B, C
9233         Value *NotCond =
9234           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9235                                              "not."+CondVal->getName()), SI);
9236         return BinaryOperator::CreateOr(NotCond, TrueVal);
9237       }
9238     }
9239     
9240     // select a, b, a  -> a&b
9241     // select a, a, b  -> a|b
9242     if (CondVal == TrueVal)
9243       return BinaryOperator::CreateOr(CondVal, FalseVal);
9244     else if (CondVal == FalseVal)
9245       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9246   }
9247
9248   // Selecting between two integer constants?
9249   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9250     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9251       // select C, 1, 0 -> zext C to int
9252       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9253         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9254       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9255         // select C, 0, 1 -> zext !C to int
9256         Value *NotCond =
9257           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9258                                                "not."+CondVal->getName()), SI);
9259         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9260       }
9261
9262       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9263         // If one of the constants is zero (we know they can't both be) and we
9264         // have an icmp instruction with zero, and we have an 'and' with the
9265         // non-constant value, eliminate this whole mess.  This corresponds to
9266         // cases like this: ((X & 27) ? 27 : 0)
9267         if (TrueValC->isZero() || FalseValC->isZero())
9268           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9269               cast<Constant>(IC->getOperand(1))->isNullValue())
9270             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9271               if (ICA->getOpcode() == Instruction::And &&
9272                   isa<ConstantInt>(ICA->getOperand(1)) &&
9273                   (ICA->getOperand(1) == TrueValC ||
9274                    ICA->getOperand(1) == FalseValC) &&
9275                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9276                 // Okay, now we know that everything is set up, we just don't
9277                 // know whether we have a icmp_ne or icmp_eq and whether the 
9278                 // true or false val is the zero.
9279                 bool ShouldNotVal = !TrueValC->isZero();
9280                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9281                 Value *V = ICA;
9282                 if (ShouldNotVal)
9283                   V = InsertNewInstBefore(BinaryOperator::Create(
9284                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9285                 return ReplaceInstUsesWith(SI, V);
9286               }
9287       }
9288     }
9289
9290   // See if we are selecting two values based on a comparison of the two values.
9291   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9292     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9293       // Transform (X == Y) ? X : Y  -> Y
9294       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9295         // This is not safe in general for floating point:  
9296         // consider X== -0, Y== +0.
9297         // It becomes safe if either operand is a nonzero constant.
9298         ConstantFP *CFPt, *CFPf;
9299         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9300               !CFPt->getValueAPF().isZero()) ||
9301             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9302              !CFPf->getValueAPF().isZero()))
9303         return ReplaceInstUsesWith(SI, FalseVal);
9304       }
9305       // Transform (X != Y) ? X : Y  -> X
9306       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9307         return ReplaceInstUsesWith(SI, TrueVal);
9308       // NOTE: if we wanted to, this is where to detect MIN/MAX
9309
9310     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9311       // Transform (X == Y) ? Y : X  -> X
9312       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9313         // This is not safe in general for floating point:  
9314         // consider X== -0, Y== +0.
9315         // It becomes safe if either operand is a nonzero constant.
9316         ConstantFP *CFPt, *CFPf;
9317         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9318               !CFPt->getValueAPF().isZero()) ||
9319             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9320              !CFPf->getValueAPF().isZero()))
9321           return ReplaceInstUsesWith(SI, FalseVal);
9322       }
9323       // Transform (X != Y) ? Y : X  -> Y
9324       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9325         return ReplaceInstUsesWith(SI, TrueVal);
9326       // NOTE: if we wanted to, this is where to detect MIN/MAX
9327     }
9328     // NOTE: if we wanted to, this is where to detect ABS
9329   }
9330
9331   // See if we are selecting two values based on a comparison of the two values.
9332   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9333     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9334       return Result;
9335
9336   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9337     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9338       if (TI->hasOneUse() && FI->hasOneUse()) {
9339         Instruction *AddOp = 0, *SubOp = 0;
9340
9341         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9342         if (TI->getOpcode() == FI->getOpcode())
9343           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9344             return IV;
9345
9346         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9347         // even legal for FP.
9348         if ((TI->getOpcode() == Instruction::Sub &&
9349              FI->getOpcode() == Instruction::Add) ||
9350             (TI->getOpcode() == Instruction::FSub &&
9351              FI->getOpcode() == Instruction::FAdd)) {
9352           AddOp = FI; SubOp = TI;
9353         } else if ((FI->getOpcode() == Instruction::Sub &&
9354                     TI->getOpcode() == Instruction::Add) ||
9355                    (FI->getOpcode() == Instruction::FSub &&
9356                     TI->getOpcode() == Instruction::FAdd)) {
9357           AddOp = TI; SubOp = FI;
9358         }
9359
9360         if (AddOp) {
9361           Value *OtherAddOp = 0;
9362           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9363             OtherAddOp = AddOp->getOperand(1);
9364           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9365             OtherAddOp = AddOp->getOperand(0);
9366           }
9367
9368           if (OtherAddOp) {
9369             // So at this point we know we have (Y -> OtherAddOp):
9370             //        select C, (add X, Y), (sub X, Z)
9371             Value *NegVal;  // Compute -Z
9372             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9373               NegVal = ConstantExpr::getNeg(C);
9374             } else {
9375               NegVal = InsertNewInstBefore(
9376                     BinaryOperator::CreateNeg(SubOp->getOperand(1),
9377                                               "tmp"), SI);
9378             }
9379
9380             Value *NewTrueOp = OtherAddOp;
9381             Value *NewFalseOp = NegVal;
9382             if (AddOp != TI)
9383               std::swap(NewTrueOp, NewFalseOp);
9384             Instruction *NewSel =
9385               SelectInst::Create(CondVal, NewTrueOp,
9386                                  NewFalseOp, SI.getName() + ".p");
9387
9388             NewSel = InsertNewInstBefore(NewSel, SI);
9389             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9390           }
9391         }
9392       }
9393
9394   // See if we can fold the select into one of our operands.
9395   if (SI.getType()->isInteger()) {
9396     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9397     if (FoldI)
9398       return FoldI;
9399   }
9400
9401   if (BinaryOperator::isNot(CondVal)) {
9402     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9403     SI.setOperand(1, FalseVal);
9404     SI.setOperand(2, TrueVal);
9405     return &SI;
9406   }
9407
9408   return 0;
9409 }
9410
9411 /// EnforceKnownAlignment - If the specified pointer points to an object that
9412 /// we control, modify the object's alignment to PrefAlign. This isn't
9413 /// often possible though. If alignment is important, a more reliable approach
9414 /// is to simply align all global variables and allocation instructions to
9415 /// their preferred alignment from the beginning.
9416 ///
9417 static unsigned EnforceKnownAlignment(Value *V,
9418                                       unsigned Align, unsigned PrefAlign) {
9419
9420   User *U = dyn_cast<User>(V);
9421   if (!U) return Align;
9422
9423   switch (Operator::getOpcode(U)) {
9424   default: break;
9425   case Instruction::BitCast:
9426     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9427   case Instruction::GetElementPtr: {
9428     // If all indexes are zero, it is just the alignment of the base pointer.
9429     bool AllZeroOperands = true;
9430     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9431       if (!isa<Constant>(*i) ||
9432           !cast<Constant>(*i)->isNullValue()) {
9433         AllZeroOperands = false;
9434         break;
9435       }
9436
9437     if (AllZeroOperands) {
9438       // Treat this like a bitcast.
9439       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9440     }
9441     break;
9442   }
9443   }
9444
9445   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9446     // If there is a large requested alignment and we can, bump up the alignment
9447     // of the global.
9448     if (!GV->isDeclaration()) {
9449       if (GV->getAlignment() >= PrefAlign)
9450         Align = GV->getAlignment();
9451       else {
9452         GV->setAlignment(PrefAlign);
9453         Align = PrefAlign;
9454       }
9455     }
9456   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9457     // If there is a requested alignment and if this is an alloca, round up.  We
9458     // don't do this for malloc, because some systems can't respect the request.
9459     if (isa<AllocaInst>(AI)) {
9460       if (AI->getAlignment() >= PrefAlign)
9461         Align = AI->getAlignment();
9462       else {
9463         AI->setAlignment(PrefAlign);
9464         Align = PrefAlign;
9465       }
9466     }
9467   }
9468
9469   return Align;
9470 }
9471
9472 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9473 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9474 /// and it is more than the alignment of the ultimate object, see if we can
9475 /// increase the alignment of the ultimate object, making this check succeed.
9476 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9477                                                   unsigned PrefAlign) {
9478   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9479                       sizeof(PrefAlign) * CHAR_BIT;
9480   APInt Mask = APInt::getAllOnesValue(BitWidth);
9481   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9482   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9483   unsigned TrailZ = KnownZero.countTrailingOnes();
9484   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9485
9486   if (PrefAlign > Align)
9487     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9488   
9489     // We don't need to make any adjustment.
9490   return Align;
9491 }
9492
9493 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9494   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9495   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9496   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9497   unsigned CopyAlign = MI->getAlignment();
9498
9499   if (CopyAlign < MinAlign) {
9500     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 
9501                                              MinAlign, false));
9502     return MI;
9503   }
9504   
9505   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9506   // load/store.
9507   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9508   if (MemOpLength == 0) return 0;
9509   
9510   // Source and destination pointer types are always "i8*" for intrinsic.  See
9511   // if the size is something we can handle with a single primitive load/store.
9512   // A single load+store correctly handles overlapping memory in the memmove
9513   // case.
9514   unsigned Size = MemOpLength->getZExtValue();
9515   if (Size == 0) return MI;  // Delete this mem transfer.
9516   
9517   if (Size > 8 || (Size&(Size-1)))
9518     return 0;  // If not 1/2/4/8 bytes, exit.
9519   
9520   // Use an integer load+store unless we can find something better.
9521   Type *NewPtrTy =
9522                 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
9523   
9524   // Memcpy forces the use of i8* for the source and destination.  That means
9525   // that if you're using memcpy to move one double around, you'll get a cast
9526   // from double* to i8*.  We'd much rather use a double load+store rather than
9527   // an i64 load+store, here because this improves the odds that the source or
9528   // dest address will be promotable.  See if we can find a better type than the
9529   // integer datatype.
9530   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9531     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9532     if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9533       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9534       // down through these levels if so.
9535       while (!SrcETy->isSingleValueType()) {
9536         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9537           if (STy->getNumElements() == 1)
9538             SrcETy = STy->getElementType(0);
9539           else
9540             break;
9541         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9542           if (ATy->getNumElements() == 1)
9543             SrcETy = ATy->getElementType();
9544           else
9545             break;
9546         } else
9547           break;
9548       }
9549       
9550       if (SrcETy->isSingleValueType())
9551         NewPtrTy = PointerType::getUnqual(SrcETy);
9552     }
9553   }
9554   
9555   
9556   // If the memcpy/memmove provides better alignment info than we can
9557   // infer, use it.
9558   SrcAlign = std::max(SrcAlign, CopyAlign);
9559   DstAlign = std::max(DstAlign, CopyAlign);
9560   
9561   Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9562   Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
9563   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9564   InsertNewInstBefore(L, *MI);
9565   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9566
9567   // Set the size of the copy to 0, it will be deleted on the next iteration.
9568   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9569   return MI;
9570 }
9571
9572 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9573   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9574   if (MI->getAlignment() < Alignment) {
9575     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9576                                              Alignment, false));
9577     return MI;
9578   }
9579   
9580   // Extract the length and alignment and fill if they are constant.
9581   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9582   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9583   if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
9584     return 0;
9585   uint64_t Len = LenC->getZExtValue();
9586   Alignment = MI->getAlignment();
9587   
9588   // If the length is zero, this is a no-op
9589   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9590   
9591   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9592   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9593     const Type *ITy = IntegerType::get(*Context, Len*8);  // n=1 -> i8.
9594     
9595     Value *Dest = MI->getDest();
9596     Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
9597
9598     // Alignment 0 is identity for alignment 1 for memset, but not store.
9599     if (Alignment == 0) Alignment = 1;
9600     
9601     // Extract the fill value and store.
9602     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9603     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9604                                       Dest, false, Alignment), *MI);
9605     
9606     // Set the size of the copy to 0, it will be deleted on the next iteration.
9607     MI->setLength(Constant::getNullValue(LenC->getType()));
9608     return MI;
9609   }
9610
9611   return 0;
9612 }
9613
9614
9615 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9616 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9617 /// the heavy lifting.
9618 ///
9619 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9620   // If the caller function is nounwind, mark the call as nounwind, even if the
9621   // callee isn't.
9622   if (CI.getParent()->getParent()->doesNotThrow() &&
9623       !CI.doesNotThrow()) {
9624     CI.setDoesNotThrow();
9625     return &CI;
9626   }
9627   
9628   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9629   if (!II) return visitCallSite(&CI);
9630   
9631   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9632   // visitCallSite.
9633   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9634     bool Changed = false;
9635
9636     // memmove/cpy/set of zero bytes is a noop.
9637     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9638       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9639
9640       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9641         if (CI->getZExtValue() == 1) {
9642           // Replace the instruction with just byte operations.  We would
9643           // transform other cases to loads/stores, but we don't know if
9644           // alignment is sufficient.
9645         }
9646     }
9647
9648     // If we have a memmove and the source operation is a constant global,
9649     // then the source and dest pointers can't alias, so we can change this
9650     // into a call to memcpy.
9651     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9652       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9653         if (GVSrc->isConstant()) {
9654           Module *M = CI.getParent()->getParent()->getParent();
9655           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9656           const Type *Tys[1];
9657           Tys[0] = CI.getOperand(3)->getType();
9658           CI.setOperand(0, 
9659                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9660           Changed = true;
9661         }
9662
9663       // memmove(x,x,size) -> noop.
9664       if (MMI->getSource() == MMI->getDest())
9665         return EraseInstFromFunction(CI);
9666     }
9667
9668     // If we can determine a pointer alignment that is bigger than currently
9669     // set, update the alignment.
9670     if (isa<MemTransferInst>(MI)) {
9671       if (Instruction *I = SimplifyMemTransfer(MI))
9672         return I;
9673     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9674       if (Instruction *I = SimplifyMemSet(MSI))
9675         return I;
9676     }
9677           
9678     if (Changed) return II;
9679   }
9680   
9681   switch (II->getIntrinsicID()) {
9682   default: break;
9683   case Intrinsic::bswap:
9684     // bswap(bswap(x)) -> x
9685     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9686       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9687         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9688     break;
9689   case Intrinsic::ppc_altivec_lvx:
9690   case Intrinsic::ppc_altivec_lvxl:
9691   case Intrinsic::x86_sse_loadu_ps:
9692   case Intrinsic::x86_sse2_loadu_pd:
9693   case Intrinsic::x86_sse2_loadu_dq:
9694     // Turn PPC lvx     -> load if the pointer is known aligned.
9695     // Turn X86 loadups -> load if the pointer is known aligned.
9696     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9697       Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9698                                          PointerType::getUnqual(II->getType()));
9699       return new LoadInst(Ptr);
9700     }
9701     break;
9702   case Intrinsic::ppc_altivec_stvx:
9703   case Intrinsic::ppc_altivec_stvxl:
9704     // Turn stvx -> store if the pointer is known aligned.
9705     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9706       const Type *OpPtrTy = 
9707         PointerType::getUnqual(II->getOperand(1)->getType());
9708       Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
9709       return new StoreInst(II->getOperand(1), Ptr);
9710     }
9711     break;
9712   case Intrinsic::x86_sse_storeu_ps:
9713   case Intrinsic::x86_sse2_storeu_pd:
9714   case Intrinsic::x86_sse2_storeu_dq:
9715     // Turn X86 storeu -> store if the pointer is known aligned.
9716     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9717       const Type *OpPtrTy = 
9718         PointerType::getUnqual(II->getOperand(2)->getType());
9719       Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
9720       return new StoreInst(II->getOperand(2), Ptr);
9721     }
9722     break;
9723     
9724   case Intrinsic::x86_sse_cvttss2si: {
9725     // These intrinsics only demands the 0th element of its input vector.  If
9726     // we can simplify the input based on that, do so now.
9727     unsigned VWidth =
9728       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9729     APInt DemandedElts(VWidth, 1);
9730     APInt UndefElts(VWidth, 0);
9731     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9732                                               UndefElts)) {
9733       II->setOperand(1, V);
9734       return II;
9735     }
9736     break;
9737   }
9738     
9739   case Intrinsic::ppc_altivec_vperm:
9740     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9741     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9742       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9743       
9744       // Check that all of the elements are integer constants or undefs.
9745       bool AllEltsOk = true;
9746       for (unsigned i = 0; i != 16; ++i) {
9747         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9748             !isa<UndefValue>(Mask->getOperand(i))) {
9749           AllEltsOk = false;
9750           break;
9751         }
9752       }
9753       
9754       if (AllEltsOk) {
9755         // Cast the input vectors to byte vectors.
9756         Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9757         Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
9758         Value *Result = UndefValue::get(Op0->getType());
9759         
9760         // Only extract each element once.
9761         Value *ExtractedElts[32];
9762         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9763         
9764         for (unsigned i = 0; i != 16; ++i) {
9765           if (isa<UndefValue>(Mask->getOperand(i)))
9766             continue;
9767           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9768           Idx &= 31;  // Match the hardware behavior.
9769           
9770           if (ExtractedElts[Idx] == 0) {
9771             ExtractedElts[Idx] = 
9772               Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1, 
9773                   ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9774                                             "tmp");
9775           }
9776         
9777           // Insert this value into the result vector.
9778           Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9779                          ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9780                                                 "tmp");
9781         }
9782         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9783       }
9784     }
9785     break;
9786
9787   case Intrinsic::stackrestore: {
9788     // If the save is right next to the restore, remove the restore.  This can
9789     // happen when variable allocas are DCE'd.
9790     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9791       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9792         BasicBlock::iterator BI = SS;
9793         if (&*++BI == II)
9794           return EraseInstFromFunction(CI);
9795       }
9796     }
9797     
9798     // Scan down this block to see if there is another stack restore in the
9799     // same block without an intervening call/alloca.
9800     BasicBlock::iterator BI = II;
9801     TerminatorInst *TI = II->getParent()->getTerminator();
9802     bool CannotRemove = false;
9803     for (++BI; &*BI != TI; ++BI) {
9804       if (isa<AllocaInst>(BI)) {
9805         CannotRemove = true;
9806         break;
9807       }
9808       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9809         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9810           // If there is a stackrestore below this one, remove this one.
9811           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9812             return EraseInstFromFunction(CI);
9813           // Otherwise, ignore the intrinsic.
9814         } else {
9815           // If we found a non-intrinsic call, we can't remove the stack
9816           // restore.
9817           CannotRemove = true;
9818           break;
9819         }
9820       }
9821     }
9822     
9823     // If the stack restore is in a return/unwind block and if there are no
9824     // allocas or calls between the restore and the return, nuke the restore.
9825     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9826       return EraseInstFromFunction(CI);
9827     break;
9828   }
9829   }
9830
9831   return visitCallSite(II);
9832 }
9833
9834 // InvokeInst simplification
9835 //
9836 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9837   return visitCallSite(&II);
9838 }
9839
9840 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9841 /// passed through the varargs area, we can eliminate the use of the cast.
9842 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9843                                          const CastInst * const CI,
9844                                          const TargetData * const TD,
9845                                          const int ix) {
9846   if (!CI->isLosslessCast())
9847     return false;
9848
9849   // The size of ByVal arguments is derived from the type, so we
9850   // can't change to a type with a different size.  If the size were
9851   // passed explicitly we could avoid this check.
9852   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9853     return true;
9854
9855   const Type* SrcTy = 
9856             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9857   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9858   if (!SrcTy->isSized() || !DstTy->isSized())
9859     return false;
9860   if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
9861     return false;
9862   return true;
9863 }
9864
9865 // visitCallSite - Improvements for call and invoke instructions.
9866 //
9867 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9868   bool Changed = false;
9869
9870   // If the callee is a constexpr cast of a function, attempt to move the cast
9871   // to the arguments of the call/invoke.
9872   if (transformConstExprCastCall(CS)) return 0;
9873
9874   Value *Callee = CS.getCalledValue();
9875
9876   if (Function *CalleeF = dyn_cast<Function>(Callee))
9877     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9878       Instruction *OldCall = CS.getInstruction();
9879       // If the call and callee calling conventions don't match, this call must
9880       // be unreachable, as the call is undefined.
9881       new StoreInst(ConstantInt::getTrue(*Context),
9882                 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), 
9883                                   OldCall);
9884       if (!OldCall->use_empty())
9885         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9886       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
9887         return EraseInstFromFunction(*OldCall);
9888       return 0;
9889     }
9890
9891   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9892     // This instruction is not reachable, just remove it.  We insert a store to
9893     // undef so that we know that this code is not reachable, despite the fact
9894     // that we can't modify the CFG here.
9895     new StoreInst(ConstantInt::getTrue(*Context),
9896                UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
9897                   CS.getInstruction());
9898
9899     if (!CS.getInstruction()->use_empty())
9900       CS.getInstruction()->
9901         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9902
9903     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9904       // Don't break the CFG, insert a dummy cond branch.
9905       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9906                          ConstantInt::getTrue(*Context), II);
9907     }
9908     return EraseInstFromFunction(*CS.getInstruction());
9909   }
9910
9911   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9912     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9913       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9914         return transformCallThroughTrampoline(CS);
9915
9916   const PointerType *PTy = cast<PointerType>(Callee->getType());
9917   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9918   if (FTy->isVarArg()) {
9919     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9920     // See if we can optimize any arguments passed through the varargs area of
9921     // the call.
9922     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9923            E = CS.arg_end(); I != E; ++I, ++ix) {
9924       CastInst *CI = dyn_cast<CastInst>(*I);
9925       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9926         *I = CI->getOperand(0);
9927         Changed = true;
9928       }
9929     }
9930   }
9931
9932   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9933     // Inline asm calls cannot throw - mark them 'nounwind'.
9934     CS.setDoesNotThrow();
9935     Changed = true;
9936   }
9937
9938   return Changed ? CS.getInstruction() : 0;
9939 }
9940
9941 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9942 // attempt to move the cast to the arguments of the call/invoke.
9943 //
9944 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9945   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9946   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9947   if (CE->getOpcode() != Instruction::BitCast || 
9948       !isa<Function>(CE->getOperand(0)))
9949     return false;
9950   Function *Callee = cast<Function>(CE->getOperand(0));
9951   Instruction *Caller = CS.getInstruction();
9952   const AttrListPtr &CallerPAL = CS.getAttributes();
9953
9954   // Okay, this is a cast from a function to a different type.  Unless doing so
9955   // would cause a type conversion of one of our arguments, change this call to
9956   // be a direct call with arguments casted to the appropriate types.
9957   //
9958   const FunctionType *FT = Callee->getFunctionType();
9959   const Type *OldRetTy = Caller->getType();
9960   const Type *NewRetTy = FT->getReturnType();
9961
9962   if (isa<StructType>(NewRetTy))
9963     return false; // TODO: Handle multiple return values.
9964
9965   // Check to see if we are changing the return type...
9966   if (OldRetTy != NewRetTy) {
9967     if (Callee->isDeclaration() &&
9968         // Conversion is ok if changing from one pointer type to another or from
9969         // a pointer to an integer of the same size.
9970         !((isa<PointerType>(OldRetTy) || !TD ||
9971            OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
9972           (isa<PointerType>(NewRetTy) || !TD ||
9973            NewRetTy == TD->getIntPtrType(Caller->getContext()))))
9974       return false;   // Cannot transform this return value.
9975
9976     if (!Caller->use_empty() &&
9977         // void -> non-void is handled specially
9978         NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
9979       return false;   // Cannot transform this return value.
9980
9981     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9982       Attributes RAttrs = CallerPAL.getRetAttributes();
9983       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
9984         return false;   // Attribute not compatible with transformed value.
9985     }
9986
9987     // If the callsite is an invoke instruction, and the return value is used by
9988     // a PHI node in a successor, we cannot change the return type of the call
9989     // because there is no place to put the cast instruction (without breaking
9990     // the critical edge).  Bail out in this case.
9991     if (!Caller->use_empty())
9992       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9993         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9994              UI != E; ++UI)
9995           if (PHINode *PN = dyn_cast<PHINode>(*UI))
9996             if (PN->getParent() == II->getNormalDest() ||
9997                 PN->getParent() == II->getUnwindDest())
9998               return false;
9999   }
10000
10001   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10002   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10003
10004   CallSite::arg_iterator AI = CS.arg_begin();
10005   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10006     const Type *ParamTy = FT->getParamType(i);
10007     const Type *ActTy = (*AI)->getType();
10008
10009     if (!CastInst::isCastable(ActTy, ParamTy))
10010       return false;   // Cannot transform this parameter value.
10011
10012     if (CallerPAL.getParamAttributes(i + 1) 
10013         & Attribute::typeIncompatible(ParamTy))
10014       return false;   // Attribute not compatible with transformed value.
10015
10016     // Converting from one pointer type to another or between a pointer and an
10017     // integer of the same size is safe even if we do not have a body.
10018     bool isConvertible = ActTy == ParamTy ||
10019       (TD && ((isa<PointerType>(ParamTy) ||
10020       ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10021               (isa<PointerType>(ActTy) ||
10022               ActTy == TD->getIntPtrType(Caller->getContext()))));
10023     if (Callee->isDeclaration() && !isConvertible) return false;
10024   }
10025
10026   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10027       Callee->isDeclaration())
10028     return false;   // Do not delete arguments unless we have a function body.
10029
10030   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10031       !CallerPAL.isEmpty())
10032     // In this case we have more arguments than the new function type, but we
10033     // won't be dropping them.  Check that these extra arguments have attributes
10034     // that are compatible with being a vararg call argument.
10035     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10036       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10037         break;
10038       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10039       if (PAttrs & Attribute::VarArgsIncompatible)
10040         return false;
10041     }
10042
10043   // Okay, we decided that this is a safe thing to do: go ahead and start
10044   // inserting cast instructions as necessary...
10045   std::vector<Value*> Args;
10046   Args.reserve(NumActualArgs);
10047   SmallVector<AttributeWithIndex, 8> attrVec;
10048   attrVec.reserve(NumCommonArgs);
10049
10050   // Get any return attributes.
10051   Attributes RAttrs = CallerPAL.getRetAttributes();
10052
10053   // If the return value is not being used, the type may not be compatible
10054   // with the existing attributes.  Wipe out any problematic attributes.
10055   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10056
10057   // Add the new return attributes.
10058   if (RAttrs)
10059     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10060
10061   AI = CS.arg_begin();
10062   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10063     const Type *ParamTy = FT->getParamType(i);
10064     if ((*AI)->getType() == ParamTy) {
10065       Args.push_back(*AI);
10066     } else {
10067       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10068           false, ParamTy, false);
10069       Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
10070     }
10071
10072     // Add any parameter attributes.
10073     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10074       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10075   }
10076
10077   // If the function takes more arguments than the call was taking, add them
10078   // now.
10079   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10080     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10081
10082   // If we are removing arguments to the function, emit an obnoxious warning.
10083   if (FT->getNumParams() < NumActualArgs) {
10084     if (!FT->isVarArg()) {
10085       errs() << "WARNING: While resolving call to function '"
10086              << Callee->getName() << "' arguments were dropped!\n";
10087     } else {
10088       // Add all of the arguments in their promoted form to the arg list.
10089       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10090         const Type *PTy = getPromotedType((*AI)->getType());
10091         if (PTy != (*AI)->getType()) {
10092           // Must promote to pass through va_arg area!
10093           Instruction::CastOps opcode =
10094             CastInst::getCastOpcode(*AI, false, PTy, false);
10095           Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
10096         } else {
10097           Args.push_back(*AI);
10098         }
10099
10100         // Add any parameter attributes.
10101         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10102           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10103       }
10104     }
10105   }
10106
10107   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10108     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10109
10110   if (NewRetTy == Type::getVoidTy(*Context))
10111     Caller->setName("");   // Void type should not have a name.
10112
10113   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10114                                                      attrVec.end());
10115
10116   Instruction *NC;
10117   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10118     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10119                             Args.begin(), Args.end(),
10120                             Caller->getName(), Caller);
10121     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10122     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10123   } else {
10124     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10125                           Caller->getName(), Caller);
10126     CallInst *CI = cast<CallInst>(Caller);
10127     if (CI->isTailCall())
10128       cast<CallInst>(NC)->setTailCall();
10129     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10130     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10131   }
10132
10133   // Insert a cast of the return type as necessary.
10134   Value *NV = NC;
10135   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10136     if (NV->getType() != Type::getVoidTy(*Context)) {
10137       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10138                                                             OldRetTy, false);
10139       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10140
10141       // If this is an invoke instruction, we should insert it after the first
10142       // non-phi, instruction in the normal successor block.
10143       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10144         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10145         InsertNewInstBefore(NC, *I);
10146       } else {
10147         // Otherwise, it's a call, just insert cast right after the call instr
10148         InsertNewInstBefore(NC, *Caller);
10149       }
10150       Worklist.AddUsersToWorkList(*Caller);
10151     } else {
10152       NV = UndefValue::get(Caller->getType());
10153     }
10154   }
10155
10156   
10157   if (!Caller->use_empty())
10158     Caller->replaceAllUsesWith(NV);
10159   
10160   EraseInstFromFunction(*Caller);
10161   return true;
10162 }
10163
10164 // transformCallThroughTrampoline - Turn a call to a function created by the
10165 // init_trampoline intrinsic into a direct call to the underlying function.
10166 //
10167 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10168   Value *Callee = CS.getCalledValue();
10169   const PointerType *PTy = cast<PointerType>(Callee->getType());
10170   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10171   const AttrListPtr &Attrs = CS.getAttributes();
10172
10173   // If the call already has the 'nest' attribute somewhere then give up -
10174   // otherwise 'nest' would occur twice after splicing in the chain.
10175   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10176     return 0;
10177
10178   IntrinsicInst *Tramp =
10179     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10180
10181   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10182   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10183   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10184
10185   const AttrListPtr &NestAttrs = NestF->getAttributes();
10186   if (!NestAttrs.isEmpty()) {
10187     unsigned NestIdx = 1;
10188     const Type *NestTy = 0;
10189     Attributes NestAttr = Attribute::None;
10190
10191     // Look for a parameter marked with the 'nest' attribute.
10192     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10193          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10194       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10195         // Record the parameter type and any other attributes.
10196         NestTy = *I;
10197         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10198         break;
10199       }
10200
10201     if (NestTy) {
10202       Instruction *Caller = CS.getInstruction();
10203       std::vector<Value*> NewArgs;
10204       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10205
10206       SmallVector<AttributeWithIndex, 8> NewAttrs;
10207       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10208
10209       // Insert the nest argument into the call argument list, which may
10210       // mean appending it.  Likewise for attributes.
10211
10212       // Add any result attributes.
10213       if (Attributes Attr = Attrs.getRetAttributes())
10214         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10215
10216       {
10217         unsigned Idx = 1;
10218         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10219         do {
10220           if (Idx == NestIdx) {
10221             // Add the chain argument and attributes.
10222             Value *NestVal = Tramp->getOperand(3);
10223             if (NestVal->getType() != NestTy)
10224               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10225             NewArgs.push_back(NestVal);
10226             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10227           }
10228
10229           if (I == E)
10230             break;
10231
10232           // Add the original argument and attributes.
10233           NewArgs.push_back(*I);
10234           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10235             NewAttrs.push_back
10236               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10237
10238           ++Idx, ++I;
10239         } while (1);
10240       }
10241
10242       // Add any function attributes.
10243       if (Attributes Attr = Attrs.getFnAttributes())
10244         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10245
10246       // The trampoline may have been bitcast to a bogus type (FTy).
10247       // Handle this by synthesizing a new function type, equal to FTy
10248       // with the chain parameter inserted.
10249
10250       std::vector<const Type*> NewTypes;
10251       NewTypes.reserve(FTy->getNumParams()+1);
10252
10253       // Insert the chain's type into the list of parameter types, which may
10254       // mean appending it.
10255       {
10256         unsigned Idx = 1;
10257         FunctionType::param_iterator I = FTy->param_begin(),
10258           E = FTy->param_end();
10259
10260         do {
10261           if (Idx == NestIdx)
10262             // Add the chain's type.
10263             NewTypes.push_back(NestTy);
10264
10265           if (I == E)
10266             break;
10267
10268           // Add the original type.
10269           NewTypes.push_back(*I);
10270
10271           ++Idx, ++I;
10272         } while (1);
10273       }
10274
10275       // Replace the trampoline call with a direct call.  Let the generic
10276       // code sort out any function type mismatches.
10277       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 
10278                                                 FTy->isVarArg());
10279       Constant *NewCallee =
10280         NestF->getType() == PointerType::getUnqual(NewFTy) ?
10281         NestF : ConstantExpr::getBitCast(NestF, 
10282                                          PointerType::getUnqual(NewFTy));
10283       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10284                                                    NewAttrs.end());
10285
10286       Instruction *NewCaller;
10287       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10288         NewCaller = InvokeInst::Create(NewCallee,
10289                                        II->getNormalDest(), II->getUnwindDest(),
10290                                        NewArgs.begin(), NewArgs.end(),
10291                                        Caller->getName(), Caller);
10292         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10293         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10294       } else {
10295         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10296                                      Caller->getName(), Caller);
10297         if (cast<CallInst>(Caller)->isTailCall())
10298           cast<CallInst>(NewCaller)->setTailCall();
10299         cast<CallInst>(NewCaller)->
10300           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10301         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10302       }
10303       if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
10304         Caller->replaceAllUsesWith(NewCaller);
10305       Caller->eraseFromParent();
10306       Worklist.Remove(Caller);
10307       return 0;
10308     }
10309   }
10310
10311   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10312   // parameter, there is no need to adjust the argument list.  Let the generic
10313   // code sort out any function type mismatches.
10314   Constant *NewCallee =
10315     NestF->getType() == PTy ? NestF : 
10316                               ConstantExpr::getBitCast(NestF, PTy);
10317   CS.setCalledFunction(NewCallee);
10318   return CS.getInstruction();
10319 }
10320
10321 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10322 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10323 /// and a single binop.
10324 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10325   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10326   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10327   unsigned Opc = FirstInst->getOpcode();
10328   Value *LHSVal = FirstInst->getOperand(0);
10329   Value *RHSVal = FirstInst->getOperand(1);
10330     
10331   const Type *LHSType = LHSVal->getType();
10332   const Type *RHSType = RHSVal->getType();
10333   
10334   // Scan to see if all operands are the same opcode, all have one use, and all
10335   // kill their operands (i.e. the operands have one use).
10336   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10337     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10338     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10339         // Verify type of the LHS matches so we don't fold cmp's of different
10340         // types or GEP's with different index types.
10341         I->getOperand(0)->getType() != LHSType ||
10342         I->getOperand(1)->getType() != RHSType)
10343       return 0;
10344
10345     // If they are CmpInst instructions, check their predicates
10346     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10347       if (cast<CmpInst>(I)->getPredicate() !=
10348           cast<CmpInst>(FirstInst)->getPredicate())
10349         return 0;
10350     
10351     // Keep track of which operand needs a phi node.
10352     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10353     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10354   }
10355   
10356   // Otherwise, this is safe to transform!
10357   
10358   Value *InLHS = FirstInst->getOperand(0);
10359   Value *InRHS = FirstInst->getOperand(1);
10360   PHINode *NewLHS = 0, *NewRHS = 0;
10361   if (LHSVal == 0) {
10362     NewLHS = PHINode::Create(LHSType,
10363                              FirstInst->getOperand(0)->getName() + ".pn");
10364     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10365     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10366     InsertNewInstBefore(NewLHS, PN);
10367     LHSVal = NewLHS;
10368   }
10369   
10370   if (RHSVal == 0) {
10371     NewRHS = PHINode::Create(RHSType,
10372                              FirstInst->getOperand(1)->getName() + ".pn");
10373     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10374     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10375     InsertNewInstBefore(NewRHS, PN);
10376     RHSVal = NewRHS;
10377   }
10378   
10379   // Add all operands to the new PHIs.
10380   if (NewLHS || NewRHS) {
10381     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10382       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10383       if (NewLHS) {
10384         Value *NewInLHS = InInst->getOperand(0);
10385         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10386       }
10387       if (NewRHS) {
10388         Value *NewInRHS = InInst->getOperand(1);
10389         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10390       }
10391     }
10392   }
10393     
10394   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10395     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10396   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10397   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10398                          LHSVal, RHSVal);
10399 }
10400
10401 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10402   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10403   
10404   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10405                                         FirstInst->op_end());
10406   // This is true if all GEP bases are allocas and if all indices into them are
10407   // constants.
10408   bool AllBasePointersAreAllocas = true;
10409   
10410   // Scan to see if all operands are the same opcode, all have one use, and all
10411   // kill their operands (i.e. the operands have one use).
10412   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10413     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10414     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10415       GEP->getNumOperands() != FirstInst->getNumOperands())
10416       return 0;
10417
10418     // Keep track of whether or not all GEPs are of alloca pointers.
10419     if (AllBasePointersAreAllocas &&
10420         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10421          !GEP->hasAllConstantIndices()))
10422       AllBasePointersAreAllocas = false;
10423     
10424     // Compare the operand lists.
10425     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10426       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10427         continue;
10428       
10429       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10430       // if one of the PHIs has a constant for the index.  The index may be
10431       // substantially cheaper to compute for the constants, so making it a
10432       // variable index could pessimize the path.  This also handles the case
10433       // for struct indices, which must always be constant.
10434       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10435           isa<ConstantInt>(GEP->getOperand(op)))
10436         return 0;
10437       
10438       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10439         return 0;
10440       FixedOperands[op] = 0;  // Needs a PHI.
10441     }
10442   }
10443   
10444   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10445   // bother doing this transformation.  At best, this will just save a bit of
10446   // offset calculation, but all the predecessors will have to materialize the
10447   // stack address into a register anyway.  We'd actually rather *clone* the
10448   // load up into the predecessors so that we have a load of a gep of an alloca,
10449   // which can usually all be folded into the load.
10450   if (AllBasePointersAreAllocas)
10451     return 0;
10452   
10453   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10454   // that is variable.
10455   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10456   
10457   bool HasAnyPHIs = false;
10458   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10459     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10460     Value *FirstOp = FirstInst->getOperand(i);
10461     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10462                                      FirstOp->getName()+".pn");
10463     InsertNewInstBefore(NewPN, PN);
10464     
10465     NewPN->reserveOperandSpace(e);
10466     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10467     OperandPhis[i] = NewPN;
10468     FixedOperands[i] = NewPN;
10469     HasAnyPHIs = true;
10470   }
10471
10472   
10473   // Add all operands to the new PHIs.
10474   if (HasAnyPHIs) {
10475     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10476       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10477       BasicBlock *InBB = PN.getIncomingBlock(i);
10478       
10479       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10480         if (PHINode *OpPhi = OperandPhis[op])
10481           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10482     }
10483   }
10484   
10485   Value *Base = FixedOperands[0];
10486   GetElementPtrInst *GEP =
10487     GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10488                               FixedOperands.end());
10489   if (cast<GEPOperator>(FirstInst)->isInBounds())
10490     cast<GEPOperator>(GEP)->setIsInBounds(true);
10491   return GEP;
10492 }
10493
10494
10495 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10496 /// sink the load out of the block that defines it.  This means that it must be
10497 /// obvious the value of the load is not changed from the point of the load to
10498 /// the end of the block it is in.
10499 ///
10500 /// Finally, it is safe, but not profitable, to sink a load targetting a
10501 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10502 /// to a register.
10503 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10504   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10505   
10506   for (++BBI; BBI != E; ++BBI)
10507     if (BBI->mayWriteToMemory())
10508       return false;
10509   
10510   // Check for non-address taken alloca.  If not address-taken already, it isn't
10511   // profitable to do this xform.
10512   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10513     bool isAddressTaken = false;
10514     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10515          UI != E; ++UI) {
10516       if (isa<LoadInst>(UI)) continue;
10517       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10518         // If storing TO the alloca, then the address isn't taken.
10519         if (SI->getOperand(1) == AI) continue;
10520       }
10521       isAddressTaken = true;
10522       break;
10523     }
10524     
10525     if (!isAddressTaken && AI->isStaticAlloca())
10526       return false;
10527   }
10528   
10529   // If this load is a load from a GEP with a constant offset from an alloca,
10530   // then we don't want to sink it.  In its present form, it will be
10531   // load [constant stack offset].  Sinking it will cause us to have to
10532   // materialize the stack addresses in each predecessor in a register only to
10533   // do a shared load from register in the successor.
10534   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10535     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10536       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10537         return false;
10538   
10539   return true;
10540 }
10541
10542
10543 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10544 // operator and they all are only used by the PHI, PHI together their
10545 // inputs, and do the operation once, to the result of the PHI.
10546 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10547   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10548
10549   // Scan the instruction, looking for input operations that can be folded away.
10550   // If all input operands to the phi are the same instruction (e.g. a cast from
10551   // the same type or "+42") we can pull the operation through the PHI, reducing
10552   // code size and simplifying code.
10553   Constant *ConstantOp = 0;
10554   const Type *CastSrcTy = 0;
10555   bool isVolatile = false;
10556   if (isa<CastInst>(FirstInst)) {
10557     CastSrcTy = FirstInst->getOperand(0)->getType();
10558   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10559     // Can fold binop, compare or shift here if the RHS is a constant, 
10560     // otherwise call FoldPHIArgBinOpIntoPHI.
10561     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10562     if (ConstantOp == 0)
10563       return FoldPHIArgBinOpIntoPHI(PN);
10564   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10565     isVolatile = LI->isVolatile();
10566     // We can't sink the load if the loaded value could be modified between the
10567     // load and the PHI.
10568     if (LI->getParent() != PN.getIncomingBlock(0) ||
10569         !isSafeAndProfitableToSinkLoad(LI))
10570       return 0;
10571     
10572     // If the PHI is of volatile loads and the load block has multiple
10573     // successors, sinking it would remove a load of the volatile value from
10574     // the path through the other successor.
10575     if (isVolatile &&
10576         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10577       return 0;
10578     
10579   } else if (isa<GetElementPtrInst>(FirstInst)) {
10580     return FoldPHIArgGEPIntoPHI(PN);
10581   } else {
10582     return 0;  // Cannot fold this operation.
10583   }
10584
10585   // Check to see if all arguments are the same operation.
10586   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10587     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10588     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10589     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10590       return 0;
10591     if (CastSrcTy) {
10592       if (I->getOperand(0)->getType() != CastSrcTy)
10593         return 0;  // Cast operation must match.
10594     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10595       // We can't sink the load if the loaded value could be modified between 
10596       // the load and the PHI.
10597       if (LI->isVolatile() != isVolatile ||
10598           LI->getParent() != PN.getIncomingBlock(i) ||
10599           !isSafeAndProfitableToSinkLoad(LI))
10600         return 0;
10601       
10602       // If the PHI is of volatile loads and the load block has multiple
10603       // successors, sinking it would remove a load of the volatile value from
10604       // the path through the other successor.
10605       if (isVolatile &&
10606           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10607         return 0;
10608       
10609     } else if (I->getOperand(1) != ConstantOp) {
10610       return 0;
10611     }
10612   }
10613
10614   // Okay, they are all the same operation.  Create a new PHI node of the
10615   // correct type, and PHI together all of the LHS's of the instructions.
10616   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10617                                    PN.getName()+".in");
10618   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10619
10620   Value *InVal = FirstInst->getOperand(0);
10621   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10622
10623   // Add all operands to the new PHI.
10624   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10625     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10626     if (NewInVal != InVal)
10627       InVal = 0;
10628     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10629   }
10630
10631   Value *PhiVal;
10632   if (InVal) {
10633     // The new PHI unions all of the same values together.  This is really
10634     // common, so we handle it intelligently here for compile-time speed.
10635     PhiVal = InVal;
10636     delete NewPN;
10637   } else {
10638     InsertNewInstBefore(NewPN, PN);
10639     PhiVal = NewPN;
10640   }
10641
10642   // Insert and return the new operation.
10643   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10644     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10645   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10646     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10647   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10648     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10649                            PhiVal, ConstantOp);
10650   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10651   
10652   // If this was a volatile load that we are merging, make sure to loop through
10653   // and mark all the input loads as non-volatile.  If we don't do this, we will
10654   // insert a new volatile load and the old ones will not be deletable.
10655   if (isVolatile)
10656     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10657       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10658   
10659   return new LoadInst(PhiVal, "", isVolatile);
10660 }
10661
10662 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10663 /// that is dead.
10664 static bool DeadPHICycle(PHINode *PN,
10665                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10666   if (PN->use_empty()) return true;
10667   if (!PN->hasOneUse()) return false;
10668
10669   // Remember this node, and if we find the cycle, return.
10670   if (!PotentiallyDeadPHIs.insert(PN))
10671     return true;
10672   
10673   // Don't scan crazily complex things.
10674   if (PotentiallyDeadPHIs.size() == 16)
10675     return false;
10676
10677   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10678     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10679
10680   return false;
10681 }
10682
10683 /// PHIsEqualValue - Return true if this phi node is always equal to
10684 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10685 ///   z = some value; x = phi (y, z); y = phi (x, z)
10686 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10687                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10688   // See if we already saw this PHI node.
10689   if (!ValueEqualPHIs.insert(PN))
10690     return true;
10691   
10692   // Don't scan crazily complex things.
10693   if (ValueEqualPHIs.size() == 16)
10694     return false;
10695  
10696   // Scan the operands to see if they are either phi nodes or are equal to
10697   // the value.
10698   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10699     Value *Op = PN->getIncomingValue(i);
10700     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10701       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10702         return false;
10703     } else if (Op != NonPhiInVal)
10704       return false;
10705   }
10706   
10707   return true;
10708 }
10709
10710
10711 // PHINode simplification
10712 //
10713 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10714   // If LCSSA is around, don't mess with Phi nodes
10715   if (MustPreserveLCSSA) return 0;
10716   
10717   if (Value *V = PN.hasConstantValue())
10718     return ReplaceInstUsesWith(PN, V);
10719
10720   // If all PHI operands are the same operation, pull them through the PHI,
10721   // reducing code size.
10722   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10723       isa<Instruction>(PN.getIncomingValue(1)) &&
10724       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10725       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10726       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10727       // than themselves more than once.
10728       PN.getIncomingValue(0)->hasOneUse())
10729     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10730       return Result;
10731
10732   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10733   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10734   // PHI)... break the cycle.
10735   if (PN.hasOneUse()) {
10736     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10737     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10738       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10739       PotentiallyDeadPHIs.insert(&PN);
10740       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10741         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10742     }
10743    
10744     // If this phi has a single use, and if that use just computes a value for
10745     // the next iteration of a loop, delete the phi.  This occurs with unused
10746     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10747     // common case here is good because the only other things that catch this
10748     // are induction variable analysis (sometimes) and ADCE, which is only run
10749     // late.
10750     if (PHIUser->hasOneUse() &&
10751         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10752         PHIUser->use_back() == &PN) {
10753       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10754     }
10755   }
10756
10757   // We sometimes end up with phi cycles that non-obviously end up being the
10758   // same value, for example:
10759   //   z = some value; x = phi (y, z); y = phi (x, z)
10760   // where the phi nodes don't necessarily need to be in the same block.  Do a
10761   // quick check to see if the PHI node only contains a single non-phi value, if
10762   // so, scan to see if the phi cycle is actually equal to that value.
10763   {
10764     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10765     // Scan for the first non-phi operand.
10766     while (InValNo != NumOperandVals && 
10767            isa<PHINode>(PN.getIncomingValue(InValNo)))
10768       ++InValNo;
10769
10770     if (InValNo != NumOperandVals) {
10771       Value *NonPhiInVal = PN.getOperand(InValNo);
10772       
10773       // Scan the rest of the operands to see if there are any conflicts, if so
10774       // there is no need to recursively scan other phis.
10775       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10776         Value *OpVal = PN.getIncomingValue(InValNo);
10777         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10778           break;
10779       }
10780       
10781       // If we scanned over all operands, then we have one unique value plus
10782       // phi values.  Scan PHI nodes to see if they all merge in each other or
10783       // the value.
10784       if (InValNo == NumOperandVals) {
10785         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10786         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10787           return ReplaceInstUsesWith(PN, NonPhiInVal);
10788       }
10789     }
10790   }
10791   return 0;
10792 }
10793
10794 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10795   Value *PtrOp = GEP.getOperand(0);
10796   // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
10797   if (GEP.getNumOperands() == 1)
10798     return ReplaceInstUsesWith(GEP, PtrOp);
10799
10800   if (isa<UndefValue>(GEP.getOperand(0)))
10801     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10802
10803   bool HasZeroPointerIndex = false;
10804   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10805     HasZeroPointerIndex = C->isNullValue();
10806
10807   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10808     return ReplaceInstUsesWith(GEP, PtrOp);
10809
10810   // Eliminate unneeded casts for indices.
10811   if (TD) {
10812     bool MadeChange = false;
10813     unsigned PtrSize = TD->getPointerSizeInBits();
10814     
10815     gep_type_iterator GTI = gep_type_begin(GEP);
10816     for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10817          I != E; ++I, ++GTI) {
10818       if (!isa<SequentialType>(*GTI)) continue;
10819       
10820       // If we are using a wider index than needed for this platform, shrink it
10821       // to what we need.  If narrower, sign-extend it to what we need.  This
10822       // explicit cast can make subsequent optimizations more obvious.
10823       unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
10824       if (OpBits == PtrSize)
10825         continue;
10826       
10827       *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
10828       MadeChange = true;
10829     }
10830     if (MadeChange) return &GEP;
10831   }
10832
10833   // Combine Indices - If the source pointer to this getelementptr instruction
10834   // is a getelementptr instruction, combine the indices of the two
10835   // getelementptr instructions into a single instruction.
10836   //
10837   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
10838     // Note that if our source is a gep chain itself that we wait for that
10839     // chain to be resolved before we perform this transformation.  This
10840     // avoids us creating a TON of code in some cases.
10841     //
10842     if (GetElementPtrInst *SrcGEP =
10843           dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10844       if (SrcGEP->getNumOperands() == 2)
10845         return 0;   // Wait until our source is folded to completion.
10846
10847     SmallVector<Value*, 8> Indices;
10848
10849     // Find out whether the last index in the source GEP is a sequential idx.
10850     bool EndsWithSequential = false;
10851     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10852          I != E; ++I)
10853       EndsWithSequential = !isa<StructType>(*I);
10854
10855     // Can we combine the two pointer arithmetics offsets?
10856     if (EndsWithSequential) {
10857       // Replace: gep (gep %P, long B), long A, ...
10858       // With:    T = long A+B; gep %P, T, ...
10859       //
10860       Value *Sum;
10861       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10862       Value *GO1 = GEP.getOperand(1);
10863       if (SO1 == Constant::getNullValue(SO1->getType())) {
10864         Sum = GO1;
10865       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10866         Sum = SO1;
10867       } else {
10868         // If they aren't the same type, then the input hasn't been processed
10869         // by the loop above yet (which canonicalizes sequential index types to
10870         // intptr_t).  Just avoid transforming this until the input has been
10871         // normalized.
10872         if (SO1->getType() != GO1->getType())
10873           return 0;
10874         Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10875       }
10876
10877       // Update the GEP in place if possible.
10878       if (Src->getNumOperands() == 2) {
10879         GEP.setOperand(0, Src->getOperand(0));
10880         GEP.setOperand(1, Sum);
10881         return &GEP;
10882       }
10883       Indices.append(Src->op_begin()+1, Src->op_end()-1);
10884       Indices.push_back(Sum);
10885       Indices.append(GEP.op_begin()+2, GEP.op_end());
10886     } else if (isa<Constant>(*GEP.idx_begin()) &&
10887                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10888                Src->getNumOperands() != 1) {
10889       // Otherwise we can do the fold if the first index of the GEP is a zero
10890       Indices.append(Src->op_begin()+1, Src->op_end());
10891       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
10892     }
10893
10894     if (!Indices.empty()) {
10895       GetElementPtrInst *NewGEP =
10896         GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
10897                                   Indices.end(), GEP.getName());
10898       if (cast<GEPOperator>(&GEP)->isInBounds() && Src->isInBounds())
10899         cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10900       return NewGEP;
10901     }
10902   }
10903   
10904   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
10905   if (Value *X = getBitCastOperand(PtrOp)) {
10906     assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
10907
10908     // If the input bitcast is actually "bitcast(bitcast(x))", then we don't 
10909     // want to change the gep until the bitcasts are eliminated.
10910     if (getBitCastOperand(X)) {
10911       Worklist.AddValue(PtrOp);
10912       return 0;
10913     }
10914     
10915     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10916     // into     : GEP [10 x i8]* X, i32 0, ...
10917     //
10918     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
10919     //           into     : GEP i8* X, ...
10920     // 
10921     // This occurs when the program declares an array extern like "int X[];"
10922     if (HasZeroPointerIndex) {
10923       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10924       const PointerType *XTy = cast<PointerType>(X->getType());
10925       if (const ArrayType *CATy =
10926           dyn_cast<ArrayType>(CPTy->getElementType())) {
10927         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
10928         if (CATy->getElementType() == XTy->getElementType()) {
10929           // -> GEP i8* X, ...
10930           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
10931           GetElementPtrInst *NewGEP =
10932             GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
10933                                       GEP.getName());
10934           if (cast<GEPOperator>(&GEP)->isInBounds())
10935             cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10936           return NewGEP;
10937         }
10938         
10939         if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
10940           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
10941           if (CATy->getElementType() == XATy->getElementType()) {
10942             // -> GEP [10 x i8]* X, i32 0, ...
10943             // At this point, we know that the cast source type is a pointer
10944             // to an array of the same type as the destination pointer
10945             // array.  Because the array type is never stepped over (there
10946             // is a leading zero) we can fold the cast into this GEP.
10947             GEP.setOperand(0, X);
10948             return &GEP;
10949           }
10950         }
10951       }
10952     } else if (GEP.getNumOperands() == 2) {
10953       // Transform things like:
10954       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10955       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10956       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10957       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10958       if (TD && isa<ArrayType>(SrcElTy) &&
10959           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10960           TD->getTypeAllocSize(ResElTy)) {
10961         Value *Idx[2];
10962         Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
10963         Idx[1] = GEP.getOperand(1);
10964         Value *NewGEP =
10965           Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
10966         if (cast<GEPOperator>(&GEP)->isInBounds())
10967           cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10968         // V and GEP are both pointer types --> BitCast
10969         return new BitCastInst(NewGEP, GEP.getType());
10970       }
10971       
10972       // Transform things like:
10973       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10974       //   (where tmp = 8*tmp2) into:
10975       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10976       
10977       if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
10978         uint64_t ArrayEltSize =
10979             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
10980         
10981         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
10982         // allow either a mul, shift, or constant here.
10983         Value *NewIdx = 0;
10984         ConstantInt *Scale = 0;
10985         if (ArrayEltSize == 1) {
10986           NewIdx = GEP.getOperand(1);
10987           Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
10988         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10989           NewIdx = ConstantInt::get(CI->getType(), 1);
10990           Scale = CI;
10991         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10992           if (Inst->getOpcode() == Instruction::Shl &&
10993               isa<ConstantInt>(Inst->getOperand(1))) {
10994             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10995             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10996             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
10997                                      1ULL << ShAmtVal);
10998             NewIdx = Inst->getOperand(0);
10999           } else if (Inst->getOpcode() == Instruction::Mul &&
11000                      isa<ConstantInt>(Inst->getOperand(1))) {
11001             Scale = cast<ConstantInt>(Inst->getOperand(1));
11002             NewIdx = Inst->getOperand(0);
11003           }
11004         }
11005         
11006         // If the index will be to exactly the right offset with the scale taken
11007         // out, perform the transformation. Note, we don't know whether Scale is
11008         // signed or not. We'll use unsigned version of division/modulo
11009         // operation after making sure Scale doesn't have the sign bit set.
11010         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11011             Scale->getZExtValue() % ArrayEltSize == 0) {
11012           Scale = ConstantInt::get(Scale->getType(),
11013                                    Scale->getZExtValue() / ArrayEltSize);
11014           if (Scale->getZExtValue() != 1) {
11015             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11016                                                        false /*ZExt*/);
11017             NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
11018           }
11019
11020           // Insert the new GEP instruction.
11021           Value *Idx[2];
11022           Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11023           Idx[1] = NewIdx;
11024           Value *NewGEP = Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11025           if (cast<GEPOperator>(&GEP)->isInBounds())
11026             cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11027           // The NewGEP must be pointer typed, so must the old one -> BitCast
11028           return new BitCastInst(NewGEP, GEP.getType());
11029         }
11030       }
11031     }
11032   }
11033   
11034   /// See if we can simplify:
11035   ///   X = bitcast A* to B*
11036   ///   Y = gep X, <...constant indices...>
11037   /// into a gep of the original struct.  This is important for SROA and alias
11038   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11039   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11040     if (TD &&
11041         !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11042       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11043       // a constant back from EmitGEPOffset.
11044       ConstantInt *OffsetV =
11045                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11046       int64_t Offset = OffsetV->getSExtValue();
11047       
11048       // If this GEP instruction doesn't move the pointer, just replace the GEP
11049       // with a bitcast of the real input to the dest type.
11050       if (Offset == 0) {
11051         // If the bitcast is of an allocation, and the allocation will be
11052         // converted to match the type of the cast, don't touch this.
11053         if (isa<AllocationInst>(BCI->getOperand(0))) {
11054           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11055           if (Instruction *I = visitBitCast(*BCI)) {
11056             if (I != BCI) {
11057               I->takeName(BCI);
11058               BCI->getParent()->getInstList().insert(BCI, I);
11059               ReplaceInstUsesWith(*BCI, I);
11060             }
11061             return &GEP;
11062           }
11063         }
11064         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11065       }
11066       
11067       // Otherwise, if the offset is non-zero, we need to find out if there is a
11068       // field at Offset in 'A's type.  If so, we can pull the cast through the
11069       // GEP.
11070       SmallVector<Value*, 8> NewIndices;
11071       const Type *InTy =
11072         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11073       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11074         Value *NGEP = Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11075                                          NewIndices.end());
11076         if (cast<GEPOperator>(&GEP)->isInBounds())
11077           cast<GEPOperator>(NGEP)->setIsInBounds(true);
11078         
11079         if (NGEP->getType() == GEP.getType())
11080           return ReplaceInstUsesWith(GEP, NGEP);
11081         NGEP->takeName(&GEP);
11082         return new BitCastInst(NGEP, GEP.getType());
11083       }
11084     }
11085   }    
11086     
11087   return 0;
11088 }
11089
11090 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11091   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11092   if (AI.isArrayAllocation()) {  // Check C != 1
11093     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11094       const Type *NewTy = 
11095         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11096       AllocationInst *New = 0;
11097
11098       // Create and insert the replacement instruction...
11099       if (isa<MallocInst>(AI))
11100         New = Builder->CreateMalloc(NewTy, 0, AI.getName());
11101       else {
11102         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11103         New = Builder->CreateAlloca(NewTy, 0, AI.getName());
11104       }
11105       New->setAlignment(AI.getAlignment());
11106
11107       // Scan to the end of the allocation instructions, to skip over a block of
11108       // allocas if possible...also skip interleaved debug info
11109       //
11110       BasicBlock::iterator It = New;
11111       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11112
11113       // Now that I is pointing to the first non-allocation-inst in the block,
11114       // insert our getelementptr instruction...
11115       //
11116       Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
11117       Value *Idx[2];
11118       Idx[0] = NullIdx;
11119       Idx[1] = NullIdx;
11120       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11121                                            New->getName()+".sub", It);
11122       cast<GEPOperator>(V)->setIsInBounds(true);
11123
11124       // Now make everything use the getelementptr instead of the original
11125       // allocation.
11126       return ReplaceInstUsesWith(AI, V);
11127     } else if (isa<UndefValue>(AI.getArraySize())) {
11128       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11129     }
11130   }
11131
11132   if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11133     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11134     // Note that we only do this for alloca's, because malloc should allocate
11135     // and return a unique pointer, even for a zero byte allocation.
11136     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11137       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11138
11139     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11140     if (AI.getAlignment() == 0)
11141       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11142   }
11143
11144   return 0;
11145 }
11146
11147 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11148   Value *Op = FI.getOperand(0);
11149
11150   // free undef -> unreachable.
11151   if (isa<UndefValue>(Op)) {
11152     // Insert a new store to null because we cannot modify the CFG here.
11153     new StoreInst(ConstantInt::getTrue(*Context),
11154            UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
11155     return EraseInstFromFunction(FI);
11156   }
11157   
11158   // If we have 'free null' delete the instruction.  This can happen in stl code
11159   // when lots of inlining happens.
11160   if (isa<ConstantPointerNull>(Op))
11161     return EraseInstFromFunction(FI);
11162   
11163   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11164   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11165     FI.setOperand(0, CI->getOperand(0));
11166     return &FI;
11167   }
11168   
11169   // Change free (gep X, 0,0,0,0) into free(X)
11170   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11171     if (GEPI->hasAllZeroIndices()) {
11172       Worklist.Add(GEPI);
11173       FI.setOperand(0, GEPI->getOperand(0));
11174       return &FI;
11175     }
11176   }
11177   
11178   // Change free(malloc) into nothing, if the malloc has a single use.
11179   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11180     if (MI->hasOneUse()) {
11181       EraseInstFromFunction(FI);
11182       return EraseInstFromFunction(*MI);
11183     }
11184
11185   return 0;
11186 }
11187
11188
11189 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11190 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11191                                         const TargetData *TD) {
11192   User *CI = cast<User>(LI.getOperand(0));
11193   Value *CastOp = CI->getOperand(0);
11194   LLVMContext *Context = IC.getContext();
11195
11196   if (TD) {
11197     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11198       // Instead of loading constant c string, use corresponding integer value
11199       // directly if string length is small enough.
11200       std::string Str;
11201       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11202         unsigned len = Str.length();
11203         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11204         unsigned numBits = Ty->getPrimitiveSizeInBits();
11205         // Replace LI with immediate integer store.
11206         if ((numBits >> 3) == len + 1) {
11207           APInt StrVal(numBits, 0);
11208           APInt SingleChar(numBits, 0);
11209           if (TD->isLittleEndian()) {
11210             for (signed i = len-1; i >= 0; i--) {
11211               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11212               StrVal = (StrVal << 8) | SingleChar;
11213             }
11214           } else {
11215             for (unsigned i = 0; i < len; i++) {
11216               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11217               StrVal = (StrVal << 8) | SingleChar;
11218             }
11219             // Append NULL at the end.
11220             SingleChar = 0;
11221             StrVal = (StrVal << 8) | SingleChar;
11222           }
11223           Value *NL = ConstantInt::get(*Context, StrVal);
11224           return IC.ReplaceInstUsesWith(LI, NL);
11225         }
11226       }
11227     }
11228   }
11229
11230   const PointerType *DestTy = cast<PointerType>(CI->getType());
11231   const Type *DestPTy = DestTy->getElementType();
11232   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11233
11234     // If the address spaces don't match, don't eliminate the cast.
11235     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11236       return 0;
11237
11238     const Type *SrcPTy = SrcTy->getElementType();
11239
11240     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11241          isa<VectorType>(DestPTy)) {
11242       // If the source is an array, the code below will not succeed.  Check to
11243       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11244       // constants.
11245       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11246         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11247           if (ASrcTy->getNumElements() != 0) {
11248             Value *Idxs[2];
11249             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
11250             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11251             SrcTy = cast<PointerType>(CastOp->getType());
11252             SrcPTy = SrcTy->getElementType();
11253           }
11254
11255       if (IC.getTargetData() &&
11256           (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11257             isa<VectorType>(SrcPTy)) &&
11258           // Do not allow turning this into a load of an integer, which is then
11259           // casted to a pointer, this pessimizes pointer analysis a lot.
11260           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11261           IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11262                IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11263
11264         // Okay, we are casting from one integer or pointer type to another of
11265         // the same size.  Instead of casting the pointer before the load, cast
11266         // the result of the loaded value.
11267         Value *NewLoad = 
11268           IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
11269         // Now cast the result of the load.
11270         return new BitCastInst(NewLoad, LI.getType());
11271       }
11272     }
11273   }
11274   return 0;
11275 }
11276
11277 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11278   Value *Op = LI.getOperand(0);
11279
11280   // Attempt to improve the alignment.
11281   if (TD) {
11282     unsigned KnownAlign =
11283       GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11284     if (KnownAlign >
11285         (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11286                                   LI.getAlignment()))
11287       LI.setAlignment(KnownAlign);
11288   }
11289
11290   // load (cast X) --> cast (load X) iff safe.
11291   if (isa<CastInst>(Op))
11292     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11293       return Res;
11294
11295   // None of the following transforms are legal for volatile loads.
11296   if (LI.isVolatile()) return 0;
11297   
11298   // Do really simple store-to-load forwarding and load CSE, to catch cases
11299   // where there are several consequtive memory accesses to the same location,
11300   // separated by a few arithmetic operations.
11301   BasicBlock::iterator BBI = &LI;
11302   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11303     return ReplaceInstUsesWith(LI, AvailableVal);
11304
11305   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11306     const Value *GEPI0 = GEPI->getOperand(0);
11307     // TODO: Consider a target hook for valid address spaces for this xform.
11308     if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
11309       // Insert a new store to null instruction before the load to indicate
11310       // that this code is not reachable.  We do this instead of inserting
11311       // an unreachable instruction directly because we cannot modify the
11312       // CFG.
11313       new StoreInst(UndefValue::get(LI.getType()),
11314                     Constant::getNullValue(Op->getType()), &LI);
11315       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11316     }
11317   } 
11318
11319   if (Constant *C = dyn_cast<Constant>(Op)) {
11320     // load null/undef -> undef
11321     // TODO: Consider a target hook for valid address spaces for this xform.
11322     if (isa<UndefValue>(C) ||
11323         (C->isNullValue() && LI.getPointerAddressSpace() == 0)) {
11324       // Insert a new store to null instruction before the load to indicate that
11325       // this code is not reachable.  We do this instead of inserting an
11326       // unreachable instruction directly because we cannot modify the CFG.
11327       new StoreInst(UndefValue::get(LI.getType()),
11328                     Constant::getNullValue(Op->getType()), &LI);
11329       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11330     }
11331
11332     // Instcombine load (constant global) into the value loaded.
11333     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11334       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11335         return ReplaceInstUsesWith(LI, GV->getInitializer());
11336
11337     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11338     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11339       if (CE->getOpcode() == Instruction::GetElementPtr) {
11340         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11341           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11342             if (Constant *V = 
11343                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE, 
11344                                                       *Context))
11345               return ReplaceInstUsesWith(LI, V);
11346         if (CE->getOperand(0)->isNullValue()) {
11347           // Insert a new store to null instruction before the load to indicate
11348           // that this code is not reachable.  We do this instead of inserting
11349           // an unreachable instruction directly because we cannot modify the
11350           // CFG.
11351           new StoreInst(UndefValue::get(LI.getType()),
11352                         Constant::getNullValue(Op->getType()), &LI);
11353           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11354         }
11355
11356       } else if (CE->isCast()) {
11357         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11358           return Res;
11359       }
11360     }
11361   }
11362     
11363   // If this load comes from anywhere in a constant global, and if the global
11364   // is all undef or zero, we know what it loads.
11365   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11366     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11367       if (GV->getInitializer()->isNullValue())
11368         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11369       else if (isa<UndefValue>(GV->getInitializer()))
11370         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11371     }
11372   }
11373
11374   if (Op->hasOneUse()) {
11375     // Change select and PHI nodes to select values instead of addresses: this
11376     // helps alias analysis out a lot, allows many others simplifications, and
11377     // exposes redundancy in the code.
11378     //
11379     // Note that we cannot do the transformation unless we know that the
11380     // introduced loads cannot trap!  Something like this is valid as long as
11381     // the condition is always false: load (select bool %C, int* null, int* %G),
11382     // but it would not be valid if we transformed it to load from null
11383     // unconditionally.
11384     //
11385     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11386       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11387       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11388           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11389         Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11390                                         SI->getOperand(1)->getName()+".val");
11391         Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11392                                         SI->getOperand(2)->getName()+".val");
11393         return SelectInst::Create(SI->getCondition(), V1, V2);
11394       }
11395
11396       // load (select (cond, null, P)) -> load P
11397       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11398         if (C->isNullValue()) {
11399           LI.setOperand(0, SI->getOperand(2));
11400           return &LI;
11401         }
11402
11403       // load (select (cond, P, null)) -> load P
11404       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11405         if (C->isNullValue()) {
11406           LI.setOperand(0, SI->getOperand(1));
11407           return &LI;
11408         }
11409     }
11410   }
11411   return 0;
11412 }
11413
11414 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11415 /// when possible.  This makes it generally easy to do alias analysis and/or
11416 /// SROA/mem2reg of the memory object.
11417 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11418   User *CI = cast<User>(SI.getOperand(1));
11419   Value *CastOp = CI->getOperand(0);
11420
11421   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11422   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11423   if (SrcTy == 0) return 0;
11424   
11425   const Type *SrcPTy = SrcTy->getElementType();
11426
11427   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11428     return 0;
11429   
11430   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11431   /// to its first element.  This allows us to handle things like:
11432   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11433   /// on 32-bit hosts.
11434   SmallVector<Value*, 4> NewGEPIndices;
11435   
11436   // If the source is an array, the code below will not succeed.  Check to
11437   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11438   // constants.
11439   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11440     // Index through pointer.
11441     Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
11442     NewGEPIndices.push_back(Zero);
11443     
11444     while (1) {
11445       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11446         if (!STy->getNumElements()) /* Struct can be empty {} */
11447           break;
11448         NewGEPIndices.push_back(Zero);
11449         SrcPTy = STy->getElementType(0);
11450       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11451         NewGEPIndices.push_back(Zero);
11452         SrcPTy = ATy->getElementType();
11453       } else {
11454         break;
11455       }
11456     }
11457     
11458     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11459   }
11460
11461   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11462     return 0;
11463   
11464   // If the pointers point into different address spaces or if they point to
11465   // values with different sizes, we can't do the transformation.
11466   if (!IC.getTargetData() ||
11467       SrcTy->getAddressSpace() != 
11468         cast<PointerType>(CI->getType())->getAddressSpace() ||
11469       IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11470       IC.getTargetData()->getTypeSizeInBits(DestPTy))
11471     return 0;
11472
11473   // Okay, we are casting from one integer or pointer type to another of
11474   // the same size.  Instead of casting the pointer before 
11475   // the store, cast the value to be stored.
11476   Value *NewCast;
11477   Value *SIOp0 = SI.getOperand(0);
11478   Instruction::CastOps opcode = Instruction::BitCast;
11479   const Type* CastSrcTy = SIOp0->getType();
11480   const Type* CastDstTy = SrcPTy;
11481   if (isa<PointerType>(CastDstTy)) {
11482     if (CastSrcTy->isInteger())
11483       opcode = Instruction::IntToPtr;
11484   } else if (isa<IntegerType>(CastDstTy)) {
11485     if (isa<PointerType>(SIOp0->getType()))
11486       opcode = Instruction::PtrToInt;
11487   }
11488   
11489   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11490   // emit a GEP to index into its first field.
11491   if (!NewGEPIndices.empty()) {
11492     CastOp = IC.Builder->CreateGEP(CastOp, NewGEPIndices.begin(),
11493                                    NewGEPIndices.end());
11494     cast<GEPOperator>(CastOp)->setIsInBounds(true);
11495   }
11496   
11497   NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11498                                    SIOp0->getName()+".c");
11499   return new StoreInst(NewCast, CastOp);
11500 }
11501
11502 /// equivalentAddressValues - Test if A and B will obviously have the same
11503 /// value. This includes recognizing that %t0 and %t1 will have the same
11504 /// value in code like this:
11505 ///   %t0 = getelementptr \@a, 0, 3
11506 ///   store i32 0, i32* %t0
11507 ///   %t1 = getelementptr \@a, 0, 3
11508 ///   %t2 = load i32* %t1
11509 ///
11510 static bool equivalentAddressValues(Value *A, Value *B) {
11511   // Test if the values are trivially equivalent.
11512   if (A == B) return true;
11513   
11514   // Test if the values come form identical arithmetic instructions.
11515   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11516   // its only used to compare two uses within the same basic block, which
11517   // means that they'll always either have the same value or one of them
11518   // will have an undefined value.
11519   if (isa<BinaryOperator>(A) ||
11520       isa<CastInst>(A) ||
11521       isa<PHINode>(A) ||
11522       isa<GetElementPtrInst>(A))
11523     if (Instruction *BI = dyn_cast<Instruction>(B))
11524       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
11525         return true;
11526   
11527   // Otherwise they may not be equivalent.
11528   return false;
11529 }
11530
11531 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11532 // return the llvm.dbg.declare.
11533 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11534   if (!V->hasNUses(2))
11535     return 0;
11536   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11537        UI != E; ++UI) {
11538     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11539       return DI;
11540     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11541       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11542         return DI;
11543       }
11544   }
11545   return 0;
11546 }
11547
11548 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11549   Value *Val = SI.getOperand(0);
11550   Value *Ptr = SI.getOperand(1);
11551
11552   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11553     EraseInstFromFunction(SI);
11554     ++NumCombined;
11555     return 0;
11556   }
11557   
11558   // If the RHS is an alloca with a single use, zapify the store, making the
11559   // alloca dead.
11560   // If the RHS is an alloca with a two uses, the other one being a 
11561   // llvm.dbg.declare, zapify the store and the declare, making the
11562   // alloca dead.  We must do this to prevent declare's from affecting
11563   // codegen.
11564   if (!SI.isVolatile()) {
11565     if (Ptr->hasOneUse()) {
11566       if (isa<AllocaInst>(Ptr)) {
11567         EraseInstFromFunction(SI);
11568         ++NumCombined;
11569         return 0;
11570       }
11571       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11572         if (isa<AllocaInst>(GEP->getOperand(0))) {
11573           if (GEP->getOperand(0)->hasOneUse()) {
11574             EraseInstFromFunction(SI);
11575             ++NumCombined;
11576             return 0;
11577           }
11578           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11579             EraseInstFromFunction(*DI);
11580             EraseInstFromFunction(SI);
11581             ++NumCombined;
11582             return 0;
11583           }
11584         }
11585       }
11586     }
11587     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11588       EraseInstFromFunction(*DI);
11589       EraseInstFromFunction(SI);
11590       ++NumCombined;
11591       return 0;
11592     }
11593   }
11594
11595   // Attempt to improve the alignment.
11596   if (TD) {
11597     unsigned KnownAlign =
11598       GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11599     if (KnownAlign >
11600         (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11601                                   SI.getAlignment()))
11602       SI.setAlignment(KnownAlign);
11603   }
11604
11605   // Do really simple DSE, to catch cases where there are several consecutive
11606   // stores to the same location, separated by a few arithmetic operations. This
11607   // situation often occurs with bitfield accesses.
11608   BasicBlock::iterator BBI = &SI;
11609   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11610        --ScanInsts) {
11611     --BBI;
11612     // Don't count debug info directives, lest they affect codegen,
11613     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11614     // It is necessary for correctness to skip those that feed into a
11615     // llvm.dbg.declare, as these are not present when debugging is off.
11616     if (isa<DbgInfoIntrinsic>(BBI) ||
11617         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11618       ScanInsts++;
11619       continue;
11620     }    
11621     
11622     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11623       // Prev store isn't volatile, and stores to the same location?
11624       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11625                                                           SI.getOperand(1))) {
11626         ++NumDeadStore;
11627         ++BBI;
11628         EraseInstFromFunction(*PrevSI);
11629         continue;
11630       }
11631       break;
11632     }
11633     
11634     // If this is a load, we have to stop.  However, if the loaded value is from
11635     // the pointer we're loading and is producing the pointer we're storing,
11636     // then *this* store is dead (X = load P; store X -> P).
11637     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11638       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11639           !SI.isVolatile()) {
11640         EraseInstFromFunction(SI);
11641         ++NumCombined;
11642         return 0;
11643       }
11644       // Otherwise, this is a load from some other location.  Stores before it
11645       // may not be dead.
11646       break;
11647     }
11648     
11649     // Don't skip over loads or things that can modify memory.
11650     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11651       break;
11652   }
11653   
11654   
11655   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11656
11657   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11658   if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
11659     if (!isa<UndefValue>(Val)) {
11660       SI.setOperand(0, UndefValue::get(Val->getType()));
11661       if (Instruction *U = dyn_cast<Instruction>(Val))
11662         Worklist.Add(U);  // Dropped a use.
11663       ++NumCombined;
11664     }
11665     return 0;  // Do not modify these!
11666   }
11667
11668   // store undef, Ptr -> noop
11669   if (isa<UndefValue>(Val)) {
11670     EraseInstFromFunction(SI);
11671     ++NumCombined;
11672     return 0;
11673   }
11674
11675   // If the pointer destination is a cast, see if we can fold the cast into the
11676   // source instead.
11677   if (isa<CastInst>(Ptr))
11678     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11679       return Res;
11680   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11681     if (CE->isCast())
11682       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11683         return Res;
11684
11685   
11686   // If this store is the last instruction in the basic block (possibly
11687   // excepting debug info instructions and the pointer bitcasts that feed
11688   // into them), and if the block ends with an unconditional branch, try
11689   // to move it to the successor block.
11690   BBI = &SI; 
11691   do {
11692     ++BBI;
11693   } while (isa<DbgInfoIntrinsic>(BBI) ||
11694            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11695   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11696     if (BI->isUnconditional())
11697       if (SimplifyStoreAtEndOfBlock(SI))
11698         return 0;  // xform done!
11699   
11700   return 0;
11701 }
11702
11703 /// SimplifyStoreAtEndOfBlock - Turn things like:
11704 ///   if () { *P = v1; } else { *P = v2 }
11705 /// into a phi node with a store in the successor.
11706 ///
11707 /// Simplify things like:
11708 ///   *P = v1; if () { *P = v2; }
11709 /// into a phi node with a store in the successor.
11710 ///
11711 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11712   BasicBlock *StoreBB = SI.getParent();
11713   
11714   // Check to see if the successor block has exactly two incoming edges.  If
11715   // so, see if the other predecessor contains a store to the same location.
11716   // if so, insert a PHI node (if needed) and move the stores down.
11717   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11718   
11719   // Determine whether Dest has exactly two predecessors and, if so, compute
11720   // the other predecessor.
11721   pred_iterator PI = pred_begin(DestBB);
11722   BasicBlock *OtherBB = 0;
11723   if (*PI != StoreBB)
11724     OtherBB = *PI;
11725   ++PI;
11726   if (PI == pred_end(DestBB))
11727     return false;
11728   
11729   if (*PI != StoreBB) {
11730     if (OtherBB)
11731       return false;
11732     OtherBB = *PI;
11733   }
11734   if (++PI != pred_end(DestBB))
11735     return false;
11736
11737   // Bail out if all the relevant blocks aren't distinct (this can happen,
11738   // for example, if SI is in an infinite loop)
11739   if (StoreBB == DestBB || OtherBB == DestBB)
11740     return false;
11741
11742   // Verify that the other block ends in a branch and is not otherwise empty.
11743   BasicBlock::iterator BBI = OtherBB->getTerminator();
11744   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11745   if (!OtherBr || BBI == OtherBB->begin())
11746     return false;
11747   
11748   // If the other block ends in an unconditional branch, check for the 'if then
11749   // else' case.  there is an instruction before the branch.
11750   StoreInst *OtherStore = 0;
11751   if (OtherBr->isUnconditional()) {
11752     --BBI;
11753     // Skip over debugging info.
11754     while (isa<DbgInfoIntrinsic>(BBI) ||
11755            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11756       if (BBI==OtherBB->begin())
11757         return false;
11758       --BBI;
11759     }
11760     // If this isn't a store, or isn't a store to the same location, bail out.
11761     OtherStore = dyn_cast<StoreInst>(BBI);
11762     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11763       return false;
11764   } else {
11765     // Otherwise, the other block ended with a conditional branch. If one of the
11766     // destinations is StoreBB, then we have the if/then case.
11767     if (OtherBr->getSuccessor(0) != StoreBB && 
11768         OtherBr->getSuccessor(1) != StoreBB)
11769       return false;
11770     
11771     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11772     // if/then triangle.  See if there is a store to the same ptr as SI that
11773     // lives in OtherBB.
11774     for (;; --BBI) {
11775       // Check to see if we find the matching store.
11776       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11777         if (OtherStore->getOperand(1) != SI.getOperand(1))
11778           return false;
11779         break;
11780       }
11781       // If we find something that may be using or overwriting the stored
11782       // value, or if we run out of instructions, we can't do the xform.
11783       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11784           BBI == OtherBB->begin())
11785         return false;
11786     }
11787     
11788     // In order to eliminate the store in OtherBr, we have to
11789     // make sure nothing reads or overwrites the stored value in
11790     // StoreBB.
11791     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11792       // FIXME: This should really be AA driven.
11793       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11794         return false;
11795     }
11796   }
11797   
11798   // Insert a PHI node now if we need it.
11799   Value *MergedVal = OtherStore->getOperand(0);
11800   if (MergedVal != SI.getOperand(0)) {
11801     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11802     PN->reserveOperandSpace(2);
11803     PN->addIncoming(SI.getOperand(0), SI.getParent());
11804     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11805     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11806   }
11807   
11808   // Advance to a place where it is safe to insert the new store and
11809   // insert it.
11810   BBI = DestBB->getFirstNonPHI();
11811   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11812                                     OtherStore->isVolatile()), *BBI);
11813   
11814   // Nuke the old stores.
11815   EraseInstFromFunction(SI);
11816   EraseInstFromFunction(*OtherStore);
11817   ++NumCombined;
11818   return true;
11819 }
11820
11821
11822 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11823   // Change br (not X), label True, label False to: br X, label False, True
11824   Value *X = 0;
11825   BasicBlock *TrueDest;
11826   BasicBlock *FalseDest;
11827   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11828       !isa<Constant>(X)) {
11829     // Swap Destinations and condition...
11830     BI.setCondition(X);
11831     BI.setSuccessor(0, FalseDest);
11832     BI.setSuccessor(1, TrueDest);
11833     return &BI;
11834   }
11835
11836   // Cannonicalize fcmp_one -> fcmp_oeq
11837   FCmpInst::Predicate FPred; Value *Y;
11838   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11839                              TrueDest, FalseDest)) &&
11840       BI.getCondition()->hasOneUse())
11841     if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11842         FPred == FCmpInst::FCMP_OGE) {
11843       FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11844       Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11845       
11846       // Swap Destinations and condition.
11847       BI.setSuccessor(0, FalseDest);
11848       BI.setSuccessor(1, TrueDest);
11849       Worklist.Add(Cond);
11850       return &BI;
11851     }
11852
11853   // Cannonicalize icmp_ne -> icmp_eq
11854   ICmpInst::Predicate IPred;
11855   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11856                       TrueDest, FalseDest)) &&
11857       BI.getCondition()->hasOneUse())
11858     if (IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
11859         IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11860         IPred == ICmpInst::ICMP_SGE) {
11861       ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11862       Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11863       // Swap Destinations and condition.
11864       BI.setSuccessor(0, FalseDest);
11865       BI.setSuccessor(1, TrueDest);
11866       Worklist.Add(Cond);
11867       return &BI;
11868     }
11869
11870   return 0;
11871 }
11872
11873 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11874   Value *Cond = SI.getCondition();
11875   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11876     if (I->getOpcode() == Instruction::Add)
11877       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11878         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11879         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11880           SI.setOperand(i,
11881                    ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11882                                                 AddRHS));
11883         SI.setOperand(0, I->getOperand(0));
11884         Worklist.Add(I);
11885         return &SI;
11886       }
11887   }
11888   return 0;
11889 }
11890
11891 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
11892   Value *Agg = EV.getAggregateOperand();
11893
11894   if (!EV.hasIndices())
11895     return ReplaceInstUsesWith(EV, Agg);
11896
11897   if (Constant *C = dyn_cast<Constant>(Agg)) {
11898     if (isa<UndefValue>(C))
11899       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11900       
11901     if (isa<ConstantAggregateZero>(C))
11902       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11903
11904     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11905       // Extract the element indexed by the first index out of the constant
11906       Value *V = C->getOperand(*EV.idx_begin());
11907       if (EV.getNumIndices() > 1)
11908         // Extract the remaining indices out of the constant indexed by the
11909         // first index
11910         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11911       else
11912         return ReplaceInstUsesWith(EV, V);
11913     }
11914     return 0; // Can't handle other constants
11915   } 
11916   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11917     // We're extracting from an insertvalue instruction, compare the indices
11918     const unsigned *exti, *exte, *insi, *inse;
11919     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11920          exte = EV.idx_end(), inse = IV->idx_end();
11921          exti != exte && insi != inse;
11922          ++exti, ++insi) {
11923       if (*insi != *exti)
11924         // The insert and extract both reference distinctly different elements.
11925         // This means the extract is not influenced by the insert, and we can
11926         // replace the aggregate operand of the extract with the aggregate
11927         // operand of the insert. i.e., replace
11928         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11929         // %E = extractvalue { i32, { i32 } } %I, 0
11930         // with
11931         // %E = extractvalue { i32, { i32 } } %A, 0
11932         return ExtractValueInst::Create(IV->getAggregateOperand(),
11933                                         EV.idx_begin(), EV.idx_end());
11934     }
11935     if (exti == exte && insi == inse)
11936       // Both iterators are at the end: Index lists are identical. Replace
11937       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11938       // %C = extractvalue { i32, { i32 } } %B, 1, 0
11939       // with "i32 42"
11940       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11941     if (exti == exte) {
11942       // The extract list is a prefix of the insert list. i.e. replace
11943       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11944       // %E = extractvalue { i32, { i32 } } %I, 1
11945       // with
11946       // %X = extractvalue { i32, { i32 } } %A, 1
11947       // %E = insertvalue { i32 } %X, i32 42, 0
11948       // by switching the order of the insert and extract (though the
11949       // insertvalue should be left in, since it may have other uses).
11950       Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
11951                                                  EV.idx_begin(), EV.idx_end());
11952       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11953                                      insi, inse);
11954     }
11955     if (insi == inse)
11956       // The insert list is a prefix of the extract list
11957       // We can simply remove the common indices from the extract and make it
11958       // operate on the inserted value instead of the insertvalue result.
11959       // i.e., replace
11960       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11961       // %E = extractvalue { i32, { i32 } } %I, 1, 0
11962       // with
11963       // %E extractvalue { i32 } { i32 42 }, 0
11964       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
11965                                       exti, exte);
11966   }
11967   // Can't simplify extracts from other values. Note that nested extracts are
11968   // already simplified implicitely by the above (extract ( extract (insert) )
11969   // will be translated into extract ( insert ( extract ) ) first and then just
11970   // the value inserted, if appropriate).
11971   return 0;
11972 }
11973
11974 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11975 /// is to leave as a vector operation.
11976 static bool CheapToScalarize(Value *V, bool isConstant) {
11977   if (isa<ConstantAggregateZero>(V)) 
11978     return true;
11979   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11980     if (isConstant) return true;
11981     // If all elts are the same, we can extract.
11982     Constant *Op0 = C->getOperand(0);
11983     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11984       if (C->getOperand(i) != Op0)
11985         return false;
11986     return true;
11987   }
11988   Instruction *I = dyn_cast<Instruction>(V);
11989   if (!I) return false;
11990   
11991   // Insert element gets simplified to the inserted element or is deleted if
11992   // this is constant idx extract element and its a constant idx insertelt.
11993   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11994       isa<ConstantInt>(I->getOperand(2)))
11995     return true;
11996   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11997     return true;
11998   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11999     if (BO->hasOneUse() &&
12000         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12001          CheapToScalarize(BO->getOperand(1), isConstant)))
12002       return true;
12003   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12004     if (CI->hasOneUse() &&
12005         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12006          CheapToScalarize(CI->getOperand(1), isConstant)))
12007       return true;
12008   
12009   return false;
12010 }
12011
12012 /// Read and decode a shufflevector mask.
12013 ///
12014 /// It turns undef elements into values that are larger than the number of
12015 /// elements in the input.
12016 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12017   unsigned NElts = SVI->getType()->getNumElements();
12018   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12019     return std::vector<unsigned>(NElts, 0);
12020   if (isa<UndefValue>(SVI->getOperand(2)))
12021     return std::vector<unsigned>(NElts, 2*NElts);
12022
12023   std::vector<unsigned> Result;
12024   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12025   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12026     if (isa<UndefValue>(*i))
12027       Result.push_back(NElts*2);  // undef -> 8
12028     else
12029       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12030   return Result;
12031 }
12032
12033 /// FindScalarElement - Given a vector and an element number, see if the scalar
12034 /// value is already around as a register, for example if it were inserted then
12035 /// extracted from the vector.
12036 static Value *FindScalarElement(Value *V, unsigned EltNo,
12037                                 LLVMContext *Context) {
12038   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12039   const VectorType *PTy = cast<VectorType>(V->getType());
12040   unsigned Width = PTy->getNumElements();
12041   if (EltNo >= Width)  // Out of range access.
12042     return UndefValue::get(PTy->getElementType());
12043   
12044   if (isa<UndefValue>(V))
12045     return UndefValue::get(PTy->getElementType());
12046   else if (isa<ConstantAggregateZero>(V))
12047     return Constant::getNullValue(PTy->getElementType());
12048   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12049     return CP->getOperand(EltNo);
12050   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12051     // If this is an insert to a variable element, we don't know what it is.
12052     if (!isa<ConstantInt>(III->getOperand(2))) 
12053       return 0;
12054     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12055     
12056     // If this is an insert to the element we are looking for, return the
12057     // inserted value.
12058     if (EltNo == IIElt) 
12059       return III->getOperand(1);
12060     
12061     // Otherwise, the insertelement doesn't modify the value, recurse on its
12062     // vector input.
12063     return FindScalarElement(III->getOperand(0), EltNo, Context);
12064   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12065     unsigned LHSWidth =
12066       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12067     unsigned InEl = getShuffleMask(SVI)[EltNo];
12068     if (InEl < LHSWidth)
12069       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12070     else if (InEl < LHSWidth*2)
12071       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12072     else
12073       return UndefValue::get(PTy->getElementType());
12074   }
12075   
12076   // Otherwise, we don't know.
12077   return 0;
12078 }
12079
12080 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12081   // If vector val is undef, replace extract with scalar undef.
12082   if (isa<UndefValue>(EI.getOperand(0)))
12083     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12084
12085   // If vector val is constant 0, replace extract with scalar 0.
12086   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12087     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12088   
12089   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12090     // If vector val is constant with all elements the same, replace EI with
12091     // that element. When the elements are not identical, we cannot replace yet
12092     // (we do that below, but only when the index is constant).
12093     Constant *op0 = C->getOperand(0);
12094     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12095       if (C->getOperand(i) != op0) {
12096         op0 = 0; 
12097         break;
12098       }
12099     if (op0)
12100       return ReplaceInstUsesWith(EI, op0);
12101   }
12102   
12103   // If extracting a specified index from the vector, see if we can recursively
12104   // find a previously computed scalar that was inserted into the vector.
12105   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12106     unsigned IndexVal = IdxC->getZExtValue();
12107     unsigned VectorWidth = 
12108       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12109       
12110     // If this is extracting an invalid index, turn this into undef, to avoid
12111     // crashing the code below.
12112     if (IndexVal >= VectorWidth)
12113       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12114     
12115     // This instruction only demands the single element from the input vector.
12116     // If the input vector has a single use, simplify it based on this use
12117     // property.
12118     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12119       APInt UndefElts(VectorWidth, 0);
12120       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12121       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12122                                                 DemandedMask, UndefElts)) {
12123         EI.setOperand(0, V);
12124         return &EI;
12125       }
12126     }
12127     
12128     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12129       return ReplaceInstUsesWith(EI, Elt);
12130     
12131     // If the this extractelement is directly using a bitcast from a vector of
12132     // the same number of elements, see if we can find the source element from
12133     // it.  In this case, we will end up needing to bitcast the scalars.
12134     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12135       if (const VectorType *VT = 
12136               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12137         if (VT->getNumElements() == VectorWidth)
12138           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12139                                              IndexVal, Context))
12140             return new BitCastInst(Elt, EI.getType());
12141     }
12142   }
12143   
12144   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12145     if (I->hasOneUse()) {
12146       // Push extractelement into predecessor operation if legal and
12147       // profitable to do so
12148       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12149         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12150         if (CheapToScalarize(BO, isConstantElt)) {
12151           Value *newEI0 =
12152             Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12153                                           EI.getName()+".lhs");
12154           Value *newEI1 =
12155             Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12156                                           EI.getName()+".rhs");
12157           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12158         }
12159       } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
12160         unsigned AS = LI->getPointerAddressSpace();
12161         Value *Ptr = Builder->CreateBitCast(I->getOperand(0),
12162                                             PointerType::get(EI.getType(), AS),
12163                                             I->getOperand(0)->getName());
12164         Value *GEP =
12165           Builder->CreateGEP(Ptr, EI.getOperand(1), I->getName()+".gep");
12166         cast<GEPOperator>(GEP)->setIsInBounds(true);
12167         
12168         LoadInst *Load = Builder->CreateLoad(GEP, "tmp");
12169
12170         // Make sure the Load goes before the load instruction in the source,
12171         // not wherever the extract happens to be.
12172         if (Instruction *P = dyn_cast<Instruction>(Ptr))
12173           P->moveBefore(I);
12174         if (Instruction *G = dyn_cast<Instruction>(GEP))
12175           G->moveBefore(I);
12176         Load->moveBefore(I);
12177         
12178         return ReplaceInstUsesWith(EI, Load);
12179       }
12180     }
12181     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12182       // Extracting the inserted element?
12183       if (IE->getOperand(2) == EI.getOperand(1))
12184         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12185       // If the inserted and extracted elements are constants, they must not
12186       // be the same value, extract from the pre-inserted value instead.
12187       if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
12188         Worklist.AddValue(EI.getOperand(0));
12189         EI.setOperand(0, IE->getOperand(0));
12190         return &EI;
12191       }
12192     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12193       // If this is extracting an element from a shufflevector, figure out where
12194       // it came from and extract from the appropriate input element instead.
12195       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12196         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12197         Value *Src;
12198         unsigned LHSWidth =
12199           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12200
12201         if (SrcIdx < LHSWidth)
12202           Src = SVI->getOperand(0);
12203         else if (SrcIdx < LHSWidth*2) {
12204           SrcIdx -= LHSWidth;
12205           Src = SVI->getOperand(1);
12206         } else {
12207           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12208         }
12209         return ExtractElementInst::Create(Src,
12210                          ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12211                                           false));
12212       }
12213     }
12214     // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12215   }
12216   return 0;
12217 }
12218
12219 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12220 /// elements from either LHS or RHS, return the shuffle mask and true. 
12221 /// Otherwise, return false.
12222 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12223                                          std::vector<Constant*> &Mask,
12224                                          LLVMContext *Context) {
12225   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12226          "Invalid CollectSingleShuffleElements");
12227   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12228
12229   if (isa<UndefValue>(V)) {
12230     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12231     return true;
12232   } else if (V == LHS) {
12233     for (unsigned i = 0; i != NumElts; ++i)
12234       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12235     return true;
12236   } else if (V == RHS) {
12237     for (unsigned i = 0; i != NumElts; ++i)
12238       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
12239     return true;
12240   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12241     // If this is an insert of an extract from some other vector, include it.
12242     Value *VecOp    = IEI->getOperand(0);
12243     Value *ScalarOp = IEI->getOperand(1);
12244     Value *IdxOp    = IEI->getOperand(2);
12245     
12246     if (!isa<ConstantInt>(IdxOp))
12247       return false;
12248     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12249     
12250     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12251       // Okay, we can handle this if the vector we are insertinting into is
12252       // transitively ok.
12253       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12254         // If so, update the mask to reflect the inserted undef.
12255         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
12256         return true;
12257       }      
12258     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12259       if (isa<ConstantInt>(EI->getOperand(1)) &&
12260           EI->getOperand(0)->getType() == V->getType()) {
12261         unsigned ExtractedIdx =
12262           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12263         
12264         // This must be extracting from either LHS or RHS.
12265         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12266           // Okay, we can handle this if the vector we are insertinting into is
12267           // transitively ok.
12268           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12269             // If so, update the mask to reflect the inserted value.
12270             if (EI->getOperand(0) == LHS) {
12271               Mask[InsertedIdx % NumElts] = 
12272                  ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12273             } else {
12274               assert(EI->getOperand(0) == RHS);
12275               Mask[InsertedIdx % NumElts] = 
12276                 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
12277               
12278             }
12279             return true;
12280           }
12281         }
12282       }
12283     }
12284   }
12285   // TODO: Handle shufflevector here!
12286   
12287   return false;
12288 }
12289
12290 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12291 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12292 /// that computes V and the LHS value of the shuffle.
12293 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12294                                      Value *&RHS, LLVMContext *Context) {
12295   assert(isa<VectorType>(V->getType()) && 
12296          (RHS == 0 || V->getType() == RHS->getType()) &&
12297          "Invalid shuffle!");
12298   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12299
12300   if (isa<UndefValue>(V)) {
12301     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12302     return V;
12303   } else if (isa<ConstantAggregateZero>(V)) {
12304     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
12305     return V;
12306   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12307     // If this is an insert of an extract from some other vector, include it.
12308     Value *VecOp    = IEI->getOperand(0);
12309     Value *ScalarOp = IEI->getOperand(1);
12310     Value *IdxOp    = IEI->getOperand(2);
12311     
12312     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12313       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12314           EI->getOperand(0)->getType() == V->getType()) {
12315         unsigned ExtractedIdx =
12316           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12317         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12318         
12319         // Either the extracted from or inserted into vector must be RHSVec,
12320         // otherwise we'd end up with a shuffle of three inputs.
12321         if (EI->getOperand(0) == RHS || RHS == 0) {
12322           RHS = EI->getOperand(0);
12323           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12324           Mask[InsertedIdx % NumElts] = 
12325             ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
12326           return V;
12327         }
12328         
12329         if (VecOp == RHS) {
12330           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12331                                             RHS, Context);
12332           // Everything but the extracted element is replaced with the RHS.
12333           for (unsigned i = 0; i != NumElts; ++i) {
12334             if (i != InsertedIdx)
12335               Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
12336           }
12337           return V;
12338         }
12339         
12340         // If this insertelement is a chain that comes from exactly these two
12341         // vectors, return the vector and the effective shuffle.
12342         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12343                                          Context))
12344           return EI->getOperand(0);
12345         
12346       }
12347     }
12348   }
12349   // TODO: Handle shufflevector here!
12350   
12351   // Otherwise, can't do anything fancy.  Return an identity vector.
12352   for (unsigned i = 0; i != NumElts; ++i)
12353     Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12354   return V;
12355 }
12356
12357 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12358   Value *VecOp    = IE.getOperand(0);
12359   Value *ScalarOp = IE.getOperand(1);
12360   Value *IdxOp    = IE.getOperand(2);
12361   
12362   // Inserting an undef or into an undefined place, remove this.
12363   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12364     ReplaceInstUsesWith(IE, VecOp);
12365   
12366   // If the inserted element was extracted from some other vector, and if the 
12367   // indexes are constant, try to turn this into a shufflevector operation.
12368   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12369     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12370         EI->getOperand(0)->getType() == IE.getType()) {
12371       unsigned NumVectorElts = IE.getType()->getNumElements();
12372       unsigned ExtractedIdx =
12373         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12374       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12375       
12376       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12377         return ReplaceInstUsesWith(IE, VecOp);
12378       
12379       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12380         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12381       
12382       // If we are extracting a value from a vector, then inserting it right
12383       // back into the same place, just use the input vector.
12384       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12385         return ReplaceInstUsesWith(IE, VecOp);      
12386       
12387       // We could theoretically do this for ANY input.  However, doing so could
12388       // turn chains of insertelement instructions into a chain of shufflevector
12389       // instructions, and right now we do not merge shufflevectors.  As such,
12390       // only do this in a situation where it is clear that there is benefit.
12391       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12392         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12393         // the values of VecOp, except then one read from EIOp0.
12394         // Build a new shuffle mask.
12395         std::vector<Constant*> Mask;
12396         if (isa<UndefValue>(VecOp))
12397           Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
12398         else {
12399           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12400           Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
12401                                                        NumVectorElts));
12402         } 
12403         Mask[InsertedIdx] = 
12404                            ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12405         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12406                                      ConstantVector::get(Mask));
12407       }
12408       
12409       // If this insertelement isn't used by some other insertelement, turn it
12410       // (and any insertelements it points to), into one big shuffle.
12411       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12412         std::vector<Constant*> Mask;
12413         Value *RHS = 0;
12414         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12415         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12416         // We now have a shuffle of LHS, RHS, Mask.
12417         return new ShuffleVectorInst(LHS, RHS,
12418                                      ConstantVector::get(Mask));
12419       }
12420     }
12421   }
12422
12423   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12424   APInt UndefElts(VWidth, 0);
12425   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12426   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12427     return &IE;
12428
12429   return 0;
12430 }
12431
12432
12433 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12434   Value *LHS = SVI.getOperand(0);
12435   Value *RHS = SVI.getOperand(1);
12436   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12437
12438   bool MadeChange = false;
12439
12440   // Undefined shuffle mask -> undefined value.
12441   if (isa<UndefValue>(SVI.getOperand(2)))
12442     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12443
12444   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12445
12446   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12447     return 0;
12448
12449   APInt UndefElts(VWidth, 0);
12450   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12451   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12452     LHS = SVI.getOperand(0);
12453     RHS = SVI.getOperand(1);
12454     MadeChange = true;
12455   }
12456   
12457   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12458   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12459   if (LHS == RHS || isa<UndefValue>(LHS)) {
12460     if (isa<UndefValue>(LHS) && LHS == RHS) {
12461       // shuffle(undef,undef,mask) -> undef.
12462       return ReplaceInstUsesWith(SVI, LHS);
12463     }
12464     
12465     // Remap any references to RHS to use LHS.
12466     std::vector<Constant*> Elts;
12467     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12468       if (Mask[i] >= 2*e)
12469         Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12470       else {
12471         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12472             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12473           Mask[i] = 2*e;     // Turn into undef.
12474           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12475         } else {
12476           Mask[i] = Mask[i] % e;  // Force to LHS.
12477           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
12478         }
12479       }
12480     }
12481     SVI.setOperand(0, SVI.getOperand(1));
12482     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12483     SVI.setOperand(2, ConstantVector::get(Elts));
12484     LHS = SVI.getOperand(0);
12485     RHS = SVI.getOperand(1);
12486     MadeChange = true;
12487   }
12488   
12489   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12490   bool isLHSID = true, isRHSID = true;
12491     
12492   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12493     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12494     // Is this an identity shuffle of the LHS value?
12495     isLHSID &= (Mask[i] == i);
12496       
12497     // Is this an identity shuffle of the RHS value?
12498     isRHSID &= (Mask[i]-e == i);
12499   }
12500
12501   // Eliminate identity shuffles.
12502   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12503   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12504   
12505   // If the LHS is a shufflevector itself, see if we can combine it with this
12506   // one without producing an unusual shuffle.  Here we are really conservative:
12507   // we are absolutely afraid of producing a shuffle mask not in the input
12508   // program, because the code gen may not be smart enough to turn a merged
12509   // shuffle into two specific shuffles: it may produce worse code.  As such,
12510   // we only merge two shuffles if the result is one of the two input shuffle
12511   // masks.  In this case, merging the shuffles just removes one instruction,
12512   // which we know is safe.  This is good for things like turning:
12513   // (splat(splat)) -> splat.
12514   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12515     if (isa<UndefValue>(RHS)) {
12516       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12517
12518       std::vector<unsigned> NewMask;
12519       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12520         if (Mask[i] >= 2*e)
12521           NewMask.push_back(2*e);
12522         else
12523           NewMask.push_back(LHSMask[Mask[i]]);
12524       
12525       // If the result mask is equal to the src shuffle or this shuffle mask, do
12526       // the replacement.
12527       if (NewMask == LHSMask || NewMask == Mask) {
12528         unsigned LHSInNElts =
12529           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12530         std::vector<Constant*> Elts;
12531         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12532           if (NewMask[i] >= LHSInNElts*2) {
12533             Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12534           } else {
12535             Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
12536           }
12537         }
12538         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12539                                      LHSSVI->getOperand(1),
12540                                      ConstantVector::get(Elts));
12541       }
12542     }
12543   }
12544
12545   return MadeChange ? &SVI : 0;
12546 }
12547
12548
12549
12550
12551 /// TryToSinkInstruction - Try to move the specified instruction from its
12552 /// current block into the beginning of DestBlock, which can only happen if it's
12553 /// safe to move the instruction past all of the instructions between it and the
12554 /// end of its block.
12555 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12556   assert(I->hasOneUse() && "Invariants didn't hold!");
12557
12558   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12559   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12560     return false;
12561
12562   // Do not sink alloca instructions out of the entry block.
12563   if (isa<AllocaInst>(I) && I->getParent() ==
12564         &DestBlock->getParent()->getEntryBlock())
12565     return false;
12566
12567   // We can only sink load instructions if there is nothing between the load and
12568   // the end of block that could change the value.
12569   if (I->mayReadFromMemory()) {
12570     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12571          Scan != E; ++Scan)
12572       if (Scan->mayWriteToMemory())
12573         return false;
12574   }
12575
12576   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12577
12578   CopyPrecedingStopPoint(I, InsertPos);
12579   I->moveBefore(InsertPos);
12580   ++NumSunkInst;
12581   return true;
12582 }
12583
12584
12585 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12586 /// all reachable code to the worklist.
12587 ///
12588 /// This has a couple of tricks to make the code faster and more powerful.  In
12589 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12590 /// them to the worklist (this significantly speeds up instcombine on code where
12591 /// many instructions are dead or constant).  Additionally, if we find a branch
12592 /// whose condition is a known constant, we only visit the reachable successors.
12593 ///
12594 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12595                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12596                                        InstCombiner &IC,
12597                                        const TargetData *TD) {
12598   SmallVector<BasicBlock*, 256> Worklist;
12599   Worklist.push_back(BB);
12600
12601   while (!Worklist.empty()) {
12602     BB = Worklist.back();
12603     Worklist.pop_back();
12604     
12605     // We have now visited this block!  If we've already been here, ignore it.
12606     if (!Visited.insert(BB)) continue;
12607
12608     DbgInfoIntrinsic *DBI_Prev = NULL;
12609     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12610       Instruction *Inst = BBI++;
12611       
12612       // DCE instruction if trivially dead.
12613       if (isInstructionTriviallyDead(Inst)) {
12614         ++NumDeadInst;
12615         DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
12616         Inst->eraseFromParent();
12617         continue;
12618       }
12619       
12620       // ConstantProp instruction if trivially constant.
12621       if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12622         DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12623                      << *Inst << '\n');
12624         Inst->replaceAllUsesWith(C);
12625         ++NumConstProp;
12626         Inst->eraseFromParent();
12627         continue;
12628       }
12629      
12630       // If there are two consecutive llvm.dbg.stoppoint calls then
12631       // it is likely that the optimizer deleted code in between these
12632       // two intrinsics. 
12633       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12634       if (DBI_Next) {
12635         if (DBI_Prev
12636             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12637             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12638           IC.Worklist.Remove(DBI_Prev);
12639           DBI_Prev->eraseFromParent();
12640         }
12641         DBI_Prev = DBI_Next;
12642       } else {
12643         DBI_Prev = 0;
12644       }
12645
12646       IC.Worklist.Add(Inst);
12647     }
12648
12649     // Recursively visit successors.  If this is a branch or switch on a
12650     // constant, only visit the reachable successor.
12651     TerminatorInst *TI = BB->getTerminator();
12652     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12653       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12654         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12655         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12656         Worklist.push_back(ReachableBB);
12657         continue;
12658       }
12659     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12660       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12661         // See if this is an explicit destination.
12662         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12663           if (SI->getCaseValue(i) == Cond) {
12664             BasicBlock *ReachableBB = SI->getSuccessor(i);
12665             Worklist.push_back(ReachableBB);
12666             continue;
12667           }
12668         
12669         // Otherwise it is the default destination.
12670         Worklist.push_back(SI->getSuccessor(0));
12671         continue;
12672       }
12673     }
12674     
12675     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12676       Worklist.push_back(TI->getSuccessor(i));
12677   }
12678 }
12679
12680 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12681   MadeIRChange = false;
12682   TD = getAnalysisIfAvailable<TargetData>();
12683   
12684   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12685         << F.getNameStr() << "\n");
12686
12687   {
12688     // Do a depth-first traversal of the function, populate the worklist with
12689     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12690     // track of which blocks we visit.
12691     SmallPtrSet<BasicBlock*, 64> Visited;
12692     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12693
12694     // Do a quick scan over the function.  If we find any blocks that are
12695     // unreachable, remove any instructions inside of them.  This prevents
12696     // the instcombine code from having to deal with some bad special cases.
12697     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12698       if (!Visited.count(BB)) {
12699         Instruction *Term = BB->getTerminator();
12700         while (Term != BB->begin()) {   // Remove instrs bottom-up
12701           BasicBlock::iterator I = Term; --I;
12702
12703           DEBUG(errs() << "IC: DCE: " << *I << '\n');
12704           // A debug intrinsic shouldn't force another iteration if we weren't
12705           // going to do one without it.
12706           if (!isa<DbgInfoIntrinsic>(I)) {
12707             ++NumDeadInst;
12708             MadeIRChange = true;
12709           }
12710           if (!I->use_empty())
12711             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12712           I->eraseFromParent();
12713         }
12714       }
12715   }
12716
12717   while (!Worklist.isEmpty()) {
12718     Instruction *I = Worklist.RemoveOne();
12719     if (I == 0) continue;  // skip null values.
12720
12721     // Check to see if we can DCE the instruction.
12722     if (isInstructionTriviallyDead(I)) {
12723       DEBUG(errs() << "IC: DCE: " << *I << '\n');
12724       EraseInstFromFunction(*I);
12725       ++NumDeadInst;
12726       MadeIRChange = true;
12727       continue;
12728     }
12729
12730     // Instruction isn't dead, see if we can constant propagate it.
12731     if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12732       DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
12733
12734       // Add operands to the worklist.
12735       ReplaceInstUsesWith(*I, C);
12736       ++NumConstProp;
12737       EraseInstFromFunction(*I);
12738       MadeIRChange = true;
12739       continue;
12740     }
12741
12742     if (TD) {
12743       // See if we can constant fold its operands.
12744       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12745         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12746           if (Constant *NewC = ConstantFoldConstantExpression(CE,   
12747                                   F.getContext(), TD))
12748             if (NewC != CE) {
12749               i->set(NewC);
12750               MadeIRChange = true;
12751             }
12752     }
12753
12754     // See if we can trivially sink this instruction to a successor basic block.
12755     if (I->hasOneUse()) {
12756       BasicBlock *BB = I->getParent();
12757       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12758       if (UserParent != BB) {
12759         bool UserIsSuccessor = false;
12760         // See if the user is one of our successors.
12761         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12762           if (*SI == UserParent) {
12763             UserIsSuccessor = true;
12764             break;
12765           }
12766
12767         // If the user is one of our immediate successors, and if that successor
12768         // only has us as a predecessors (we'd have to split the critical edge
12769         // otherwise), we can keep going.
12770         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12771             next(pred_begin(UserParent)) == pred_end(UserParent))
12772           // Okay, the CFG is simple enough, try to sink this instruction.
12773           MadeIRChange |= TryToSinkInstruction(I, UserParent);
12774       }
12775     }
12776
12777     // Now that we have an instruction, try combining it to simplify it.
12778     Builder->SetInsertPoint(I->getParent(), I);
12779     
12780 #ifndef NDEBUG
12781     std::string OrigI;
12782 #endif
12783     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
12784     
12785     if (Instruction *Result = visit(*I)) {
12786       ++NumCombined;
12787       // Should we replace the old instruction with a new one?
12788       if (Result != I) {
12789         DEBUG(errs() << "IC: Old = " << *I << '\n'
12790                      << "    New = " << *Result << '\n');
12791
12792         // Everything uses the new instruction now.
12793         I->replaceAllUsesWith(Result);
12794
12795         // Push the new instruction and any users onto the worklist.
12796         Worklist.Add(Result);
12797         Worklist.AddUsersToWorkList(*Result);
12798
12799         // Move the name to the new instruction first.
12800         Result->takeName(I);
12801
12802         // Insert the new instruction into the basic block...
12803         BasicBlock *InstParent = I->getParent();
12804         BasicBlock::iterator InsertPos = I;
12805
12806         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12807           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12808             ++InsertPos;
12809
12810         InstParent->getInstList().insert(InsertPos, Result);
12811
12812         EraseInstFromFunction(*I);
12813       } else {
12814 #ifndef NDEBUG
12815         DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12816                      << "    New = " << *I << '\n');
12817 #endif
12818
12819         // If the instruction was modified, it's possible that it is now dead.
12820         // if so, remove it.
12821         if (isInstructionTriviallyDead(I)) {
12822           EraseInstFromFunction(*I);
12823         } else {
12824           Worklist.Add(I);
12825           Worklist.AddUsersToWorkList(*I);
12826         }
12827       }
12828       MadeIRChange = true;
12829     }
12830   }
12831
12832   Worklist.Zap();
12833   return MadeIRChange;
12834 }
12835
12836
12837 bool InstCombiner::runOnFunction(Function &F) {
12838   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12839   Context = &F.getContext();
12840   
12841   
12842   /// Builder - This is an IRBuilder that automatically inserts new
12843   /// instructions into the worklist when they are created.
12844   IRBuilder<true, ConstantFolder, InstCombineIRInserter> 
12845     TheBuilder(F.getContext(), ConstantFolder(F.getContext()),
12846                InstCombineIRInserter(Worklist));
12847   Builder = &TheBuilder;
12848   
12849   bool EverMadeChange = false;
12850
12851   // Iterate while there is work to do.
12852   unsigned Iteration = 0;
12853   while (DoOneIteration(F, Iteration++))
12854     EverMadeChange = true;
12855   
12856   Builder = 0;
12857   return EverMadeChange;
12858 }
12859
12860 FunctionPass *llvm::createInstructionCombiningPass() {
12861   return new InstCombiner();
12862 }