The bitcast case is not needed here: instcombine turns icmp(bitcast(x), null) ->...
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions.  This pass does not modify the CFG.  This pass is where
12 // algebraic simplification happens.
13 //
14 // This pass combines things like:
15 //    %Y = add i32 %X, 1
16 //    %Z = add i32 %Y, 1
17 // into:
18 //    %Z = add i32 %X, 2
19 //
20 // This is a simple worklist driven algorithm.
21 //
22 // This pass guarantees that the following canonicalizations are performed on
23 // the program:
24 //    1. If a binary operator has a constant operand, it is moved to the RHS
25 //    2. Bitwise operators with constant operands are always grouped so that
26 //       shifts are performed first, then or's, then and's, then xor's.
27 //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All cmp instructions on boolean values are replaced with logical ops
29 //    5. add X, X is represented as (X*2) => (X << 1)
30 //    6. Multiplies with a power-of-two constant argument are transformed into
31 //       shifts.
32 //   ... etc.
33 //
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/LLVMContext.h"
40 #include "llvm/Pass.h"
41 #include "llvm/DerivedTypes.h"
42 #include "llvm/GlobalVariable.h"
43 #include "llvm/Operator.h"
44 #include "llvm/Analysis/ConstantFolding.h"
45 #include "llvm/Analysis/MallocHelper.h"
46 #include "llvm/Analysis/ValueTracking.h"
47 #include "llvm/Target/TargetData.h"
48 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
49 #include "llvm/Transforms/Utils/Local.h"
50 #include "llvm/Support/CallSite.h"
51 #include "llvm/Support/ConstantRange.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include "llvm/Support/GetElementPtrTypeIterator.h"
55 #include "llvm/Support/InstVisitor.h"
56 #include "llvm/Support/IRBuilder.h"
57 #include "llvm/Support/MathExtras.h"
58 #include "llvm/Support/PatternMatch.h"
59 #include "llvm/Support/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       DEBUG(errs() << "IC: ADD: " << *I << '\n');
94       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
95         Worklist.push_back(I);
96     }
97     
98     void AddValue(Value *V) {
99       if (Instruction *I = dyn_cast<Instruction>(V))
100         Add(I);
101     }
102     
103     // Remove - remove I from the worklist if it exists.
104     void Remove(Instruction *I) {
105       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
106       if (It == WorklistMap.end()) return; // Not in worklist.
107       
108       // Don't bother moving everything down, just null out the slot.
109       Worklist[It->second] = 0;
110       
111       WorklistMap.erase(It);
112     }
113     
114     Instruction *RemoveOne() {
115       Instruction *I = Worklist.back();
116       Worklist.pop_back();
117       WorklistMap.erase(I);
118       return I;
119     }
120
121     /// AddUsersToWorkList - When an instruction is simplified, add all users of
122     /// the instruction to the work lists because they might get more simplified
123     /// now.
124     ///
125     void AddUsersToWorkList(Instruction &I) {
126       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
127            UI != UE; ++UI)
128         Add(cast<Instruction>(*UI));
129     }
130     
131     
132     /// Zap - check that the worklist is empty and nuke the backing store for
133     /// the map if it is large.
134     void Zap() {
135       assert(WorklistMap.empty() && "Worklist empty, but map not?");
136       
137       // Do an explicit clear, this shrinks the map if needed.
138       WorklistMap.clear();
139     }
140   };
141 } // end anonymous namespace.
142
143
144 namespace {
145   /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
146   /// just like the normal insertion helper, but also adds any new instructions
147   /// to the instcombine worklist.
148   class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
149     InstCombineWorklist &Worklist;
150   public:
151     InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
152     
153     void InsertHelper(Instruction *I, const Twine &Name,
154                       BasicBlock *BB, BasicBlock::iterator InsertPt) const {
155       IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
156       Worklist.Add(I);
157     }
158   };
159 } // end anonymous namespace
160
161
162 namespace {
163   class InstCombiner : 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 << '\n');
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, cast instruction, or select
388     // which has a PHI node as operand #0, see if we can fold the instruction
389     // into the PHI (which is only possible if all operands to the PHI are
390     // constants).
391     //
392     // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
393     // that would normally be unprofitable because they strongly encourage jump
394     // threading.
395     Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
396
397     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
398     // operator and they all are only used by the PHI, PHI together their
399     // inputs, and do the operation once, to the result of the PHI.
400     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
401     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
402     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
403
404     
405     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
406                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
407     
408     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
409                               bool isSub, Instruction &I);
410     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
411                                  bool isSigned, bool Inside, Instruction &IB);
412     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
413     Instruction *MatchBSwap(BinaryOperator &I);
414     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
415     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
416     Instruction *SimplifyMemSet(MemSetInst *MI);
417
418
419     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
420
421     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
422                                     unsigned CastOpc, int &NumCastsRemoved);
423     unsigned GetOrEnforceKnownAlignment(Value *V,
424                                         unsigned PrefAlign = 0);
425
426   };
427 } // end anonymous namespace
428
429 char InstCombiner::ID = 0;
430 static RegisterPass<InstCombiner>
431 X("instcombine", "Combine redundant instructions");
432
433 // getComplexity:  Assign a complexity or rank value to LLVM Values...
434 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
435 static unsigned getComplexity(Value *V) {
436   if (isa<Instruction>(V)) {
437     if (BinaryOperator::isNeg(V) ||
438         BinaryOperator::isFNeg(V) ||
439         BinaryOperator::isNot(V))
440       return 3;
441     return 4;
442   }
443   if (isa<Argument>(V)) return 3;
444   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
445 }
446
447 // isOnlyUse - Return true if this instruction will be deleted if we stop using
448 // it.
449 static bool isOnlyUse(Value *V) {
450   return V->hasOneUse() || isa<Constant>(V);
451 }
452
453 // getPromotedType - Return the specified type promoted as it would be to pass
454 // though a va_arg area...
455 static const Type *getPromotedType(const Type *Ty) {
456   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
457     if (ITy->getBitWidth() < 32)
458       return Type::getInt32Ty(Ty->getContext());
459   }
460   return Ty;
461 }
462
463 /// getBitCastOperand - If the specified operand is a CastInst, a constant
464 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
465 /// operand value, otherwise return null.
466 static Value *getBitCastOperand(Value *V) {
467   if (Operator *O = dyn_cast<Operator>(V)) {
468     if (O->getOpcode() == Instruction::BitCast)
469       return O->getOperand(0);
470     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
471       if (GEP->hasAllZeroIndices())
472         return GEP->getPointerOperand();
473   }
474   return 0;
475 }
476
477 /// This function is a wrapper around CastInst::isEliminableCastPair. It
478 /// simply extracts arguments and returns what that function returns.
479 static Instruction::CastOps 
480 isEliminableCastPair(
481   const CastInst *CI, ///< The first cast instruction
482   unsigned opcode,       ///< The opcode of the second cast instruction
483   const Type *DstTy,     ///< The target type for the second cast instruction
484   TargetData *TD         ///< The target data for pointer size
485 ) {
486
487   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
488   const Type *MidTy = CI->getType();                  // B from above
489
490   // Get the opcodes of the two Cast instructions
491   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
492   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
493
494   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
495                                                 DstTy,
496                                   TD ? TD->getIntPtrType(CI->getContext()) : 0);
497   
498   // We don't want to form an inttoptr or ptrtoint that converts to an integer
499   // type that differs from the pointer size.
500   if ((Res == Instruction::IntToPtr &&
501           (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
502       (Res == Instruction::PtrToInt &&
503           (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
504     Res = 0;
505   
506   return Instruction::CastOps(Res);
507 }
508
509 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
510 /// in any code being generated.  It does not require codegen if V is simple
511 /// enough or if the cast can be folded into other casts.
512 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
513                               const Type *Ty, TargetData *TD) {
514   if (V->getType() == Ty || isa<Constant>(V)) return false;
515   
516   // If this is another cast that can be eliminated, it isn't codegen either.
517   if (const CastInst *CI = dyn_cast<CastInst>(V))
518     if (isEliminableCastPair(CI, opcode, Ty, TD))
519       return false;
520   return true;
521 }
522
523 // SimplifyCommutative - This performs a few simplifications for commutative
524 // operators:
525 //
526 //  1. Order operands such that they are listed from right (least complex) to
527 //     left (most complex).  This puts constants before unary operators before
528 //     binary operators.
529 //
530 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
531 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
532 //
533 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
534   bool Changed = false;
535   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
536     Changed = !I.swapOperands();
537
538   if (!I.isAssociative()) return Changed;
539   Instruction::BinaryOps Opcode = I.getOpcode();
540   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
541     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
542       if (isa<Constant>(I.getOperand(1))) {
543         Constant *Folded = ConstantExpr::get(I.getOpcode(),
544                                              cast<Constant>(I.getOperand(1)),
545                                              cast<Constant>(Op->getOperand(1)));
546         I.setOperand(0, Op->getOperand(0));
547         I.setOperand(1, Folded);
548         return true;
549       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
550         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
551             isOnlyUse(Op) && isOnlyUse(Op1)) {
552           Constant *C1 = cast<Constant>(Op->getOperand(1));
553           Constant *C2 = cast<Constant>(Op1->getOperand(1));
554
555           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
556           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
557           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
558                                                     Op1->getOperand(0),
559                                                     Op1->getName(), &I);
560           Worklist.Add(New);
561           I.setOperand(0, New);
562           I.setOperand(1, Folded);
563           return true;
564         }
565     }
566   return Changed;
567 }
568
569 /// SimplifyCompare - For a CmpInst this function just orders the operands
570 /// so that theyare listed from right (least complex) to left (most complex).
571 /// This puts constants before unary operators before binary operators.
572 bool InstCombiner::SimplifyCompare(CmpInst &I) {
573   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
574     return false;
575   I.swapOperands();
576   // Compare instructions are not associative so there's nothing else we can do.
577   return true;
578 }
579
580 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
581 // if the LHS is a constant zero (which is the 'negate' form).
582 //
583 static inline Value *dyn_castNegVal(Value *V) {
584   if (BinaryOperator::isNeg(V))
585     return BinaryOperator::getNegArgument(V);
586
587   // Constants can be considered to be negated values if they can be folded.
588   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
589     return ConstantExpr::getNeg(C);
590
591   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
592     if (C->getType()->getElementType()->isInteger())
593       return ConstantExpr::getNeg(C);
594
595   return 0;
596 }
597
598 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
599 // instruction if the LHS is a constant negative zero (which is the 'negate'
600 // form).
601 //
602 static inline Value *dyn_castFNegVal(Value *V) {
603   if (BinaryOperator::isFNeg(V))
604     return BinaryOperator::getFNegArgument(V);
605
606   // Constants can be considered to be negated values if they can be folded.
607   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
608     return ConstantExpr::getFNeg(C);
609
610   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
611     if (C->getType()->getElementType()->isFloatingPoint())
612       return ConstantExpr::getFNeg(C);
613
614   return 0;
615 }
616
617 static inline Value *dyn_castNotVal(Value *V) {
618   if (BinaryOperator::isNot(V))
619     return BinaryOperator::getNotArgument(V);
620
621   // Constants can be considered to be not'ed values...
622   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
623     return ConstantInt::get(C->getType(), ~C->getValue());
624   return 0;
625 }
626
627 // dyn_castFoldableMul - If this value is a multiply that can be folded into
628 // other computations (because it has a constant operand), return the
629 // non-constant operand of the multiply, and set CST to point to the multiplier.
630 // Otherwise, return null.
631 //
632 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
633   if (V->hasOneUse() && V->getType()->isInteger())
634     if (Instruction *I = dyn_cast<Instruction>(V)) {
635       if (I->getOpcode() == Instruction::Mul)
636         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
637           return I->getOperand(0);
638       if (I->getOpcode() == Instruction::Shl)
639         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
640           // The multiplier is really 1 << CST.
641           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
642           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
643           CST = ConstantInt::get(V->getType()->getContext(),
644                                  APInt(BitWidth, 1).shl(CSTVal));
645           return I->getOperand(0);
646         }
647     }
648   return 0;
649 }
650
651 /// AddOne - Add one to a ConstantInt
652 static Constant *AddOne(Constant *C) {
653   return ConstantExpr::getAdd(C, 
654     ConstantInt::get(C->getType(), 1));
655 }
656 /// SubOne - Subtract one from a ConstantInt
657 static Constant *SubOne(ConstantInt *C) {
658   return ConstantExpr::getSub(C, 
659     ConstantInt::get(C->getType(), 1));
660 }
661 /// MultiplyOverflows - True if the multiply can not be expressed in an int
662 /// this size.
663 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
664   uint32_t W = C1->getBitWidth();
665   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
666   if (sign) {
667     LHSExt.sext(W * 2);
668     RHSExt.sext(W * 2);
669   } else {
670     LHSExt.zext(W * 2);
671     RHSExt.zext(W * 2);
672   }
673
674   APInt MulExt = LHSExt * RHSExt;
675
676   if (sign) {
677     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
678     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
679     return MulExt.slt(Min) || MulExt.sgt(Max);
680   } else 
681     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
682 }
683
684
685 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
686 /// specified instruction is a constant integer.  If so, check to see if there
687 /// are any bits set in the constant that are not demanded.  If so, shrink the
688 /// constant and return true.
689 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
690                                    APInt Demanded) {
691   assert(I && "No instruction?");
692   assert(OpNo < I->getNumOperands() && "Operand index too large");
693
694   // If the operand is not a constant integer, nothing to do.
695   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
696   if (!OpC) return false;
697
698   // If there are no bits set that aren't demanded, nothing to do.
699   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
700   if ((~Demanded & OpC->getValue()) == 0)
701     return false;
702
703   // This instruction is producing bits that are not demanded. Shrink the RHS.
704   Demanded &= OpC->getValue();
705   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
706   return true;
707 }
708
709 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
710 // set of known zero and one bits, compute the maximum and minimum values that
711 // could have the specified known zero and known one bits, returning them in
712 // min/max.
713 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
714                                                    const APInt& KnownOne,
715                                                    APInt& Min, APInt& Max) {
716   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
717          KnownZero.getBitWidth() == Min.getBitWidth() &&
718          KnownZero.getBitWidth() == Max.getBitWidth() &&
719          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
720   APInt UnknownBits = ~(KnownZero|KnownOne);
721
722   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
723   // bit if it is unknown.
724   Min = KnownOne;
725   Max = KnownOne|UnknownBits;
726   
727   if (UnknownBits.isNegative()) { // Sign bit is unknown
728     Min.set(Min.getBitWidth()-1);
729     Max.clear(Max.getBitWidth()-1);
730   }
731 }
732
733 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
734 // a set of known zero and one bits, compute the maximum and minimum values that
735 // could have the specified known zero and known one bits, returning them in
736 // min/max.
737 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
738                                                      const APInt &KnownOne,
739                                                      APInt &Min, APInt &Max) {
740   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
741          KnownZero.getBitWidth() == Min.getBitWidth() &&
742          KnownZero.getBitWidth() == Max.getBitWidth() &&
743          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
744   APInt UnknownBits = ~(KnownZero|KnownOne);
745   
746   // The minimum value is when the unknown bits are all zeros.
747   Min = KnownOne;
748   // The maximum value is when the unknown bits are all ones.
749   Max = KnownOne|UnknownBits;
750 }
751
752 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
753 /// SimplifyDemandedBits knows about.  See if the instruction has any
754 /// properties that allow us to simplify its operands.
755 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
756   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
757   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
758   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
759   
760   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
761                                      KnownZero, KnownOne, 0);
762   if (V == 0) return false;
763   if (V == &Inst) return true;
764   ReplaceInstUsesWith(Inst, V);
765   return true;
766 }
767
768 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
769 /// specified instruction operand if possible, updating it in place.  It returns
770 /// true if it made any change and false otherwise.
771 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
772                                         APInt &KnownZero, APInt &KnownOne,
773                                         unsigned Depth) {
774   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
775                                           KnownZero, KnownOne, Depth);
776   if (NewVal == 0) return false;
777   U.set(NewVal);
778   return true;
779 }
780
781
782 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
783 /// value based on the demanded bits.  When this function is called, it is known
784 /// that only the bits set in DemandedMask of the result of V are ever used
785 /// downstream. Consequently, depending on the mask and V, it may be possible
786 /// to replace V with a constant or one of its operands. In such cases, this
787 /// function does the replacement and returns true. In all other cases, it
788 /// returns false after analyzing the expression and setting KnownOne and known
789 /// to be one in the expression.  KnownZero contains all the bits that are known
790 /// to be zero in the expression. These are provided to potentially allow the
791 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
792 /// the expression. KnownOne and KnownZero always follow the invariant that 
793 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
794 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
795 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
796 /// and KnownOne must all be the same.
797 ///
798 /// This returns null if it did not change anything and it permits no
799 /// simplification.  This returns V itself if it did some simplification of V's
800 /// operands based on the information about what bits are demanded. This returns
801 /// some other non-null value if it found out that V is equal to another value
802 /// in the context where the specified bits are demanded, but not for all users.
803 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
804                                              APInt &KnownZero, APInt &KnownOne,
805                                              unsigned Depth) {
806   assert(V != 0 && "Null pointer of Value???");
807   assert(Depth <= 6 && "Limit Search Depth");
808   uint32_t BitWidth = DemandedMask.getBitWidth();
809   const Type *VTy = V->getType();
810   assert((TD || !isa<PointerType>(VTy)) &&
811          "SimplifyDemandedBits needs to know bit widths!");
812   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
813          (!VTy->isIntOrIntVector() ||
814           VTy->getScalarSizeInBits() == BitWidth) &&
815          KnownZero.getBitWidth() == BitWidth &&
816          KnownOne.getBitWidth() == BitWidth &&
817          "Value *V, DemandedMask, KnownZero and KnownOne "
818          "must have same BitWidth");
819   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
820     // We know all of the bits for a constant!
821     KnownOne = CI->getValue() & DemandedMask;
822     KnownZero = ~KnownOne & DemandedMask;
823     return 0;
824   }
825   if (isa<ConstantPointerNull>(V)) {
826     // We know all of the bits for a constant!
827     KnownOne.clear();
828     KnownZero = DemandedMask;
829     return 0;
830   }
831
832   KnownZero.clear();
833   KnownOne.clear();
834   if (DemandedMask == 0) {   // Not demanding any bits from V.
835     if (isa<UndefValue>(V))
836       return 0;
837     return UndefValue::get(VTy);
838   }
839   
840   if (Depth == 6)        // Limit search depth.
841     return 0;
842   
843   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
844   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
845
846   Instruction *I = dyn_cast<Instruction>(V);
847   if (!I) {
848     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
849     return 0;        // Only analyze instructions.
850   }
851
852   // If there are multiple uses of this value and we aren't at the root, then
853   // we can't do any simplifications of the operands, because DemandedMask
854   // only reflects the bits demanded by *one* of the users.
855   if (Depth != 0 && !I->hasOneUse()) {
856     // Despite the fact that we can't simplify this instruction in all User's
857     // context, we can at least compute the knownzero/knownone bits, and we can
858     // do simplifications that apply to *just* the one user if we know that
859     // this instruction has a simpler value in that context.
860     if (I->getOpcode() == Instruction::And) {
861       // If either the LHS or the RHS are Zero, the result is zero.
862       ComputeMaskedBits(I->getOperand(1), DemandedMask,
863                         RHSKnownZero, RHSKnownOne, Depth+1);
864       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
865                         LHSKnownZero, LHSKnownOne, Depth+1);
866       
867       // If all of the demanded bits are known 1 on one side, return the other.
868       // These bits cannot contribute to the result of the 'and' in this
869       // context.
870       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
871           (DemandedMask & ~LHSKnownZero))
872         return I->getOperand(0);
873       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
874           (DemandedMask & ~RHSKnownZero))
875         return I->getOperand(1);
876       
877       // If all of the demanded bits in the inputs are known zeros, return zero.
878       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
879         return Constant::getNullValue(VTy);
880       
881     } else if (I->getOpcode() == Instruction::Or) {
882       // We can simplify (X|Y) -> X or Y in the user's context if we know that
883       // only bits from X or Y are demanded.
884       
885       // If either the LHS or the RHS are One, the result is One.
886       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
887                         RHSKnownZero, RHSKnownOne, Depth+1);
888       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
889                         LHSKnownZero, LHSKnownOne, Depth+1);
890       
891       // If all of the demanded bits are known zero on one side, return the
892       // other.  These bits cannot contribute to the result of the 'or' in this
893       // context.
894       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
895           (DemandedMask & ~LHSKnownOne))
896         return I->getOperand(0);
897       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
898           (DemandedMask & ~RHSKnownOne))
899         return I->getOperand(1);
900       
901       // If all of the potentially set bits on one side are known to be set on
902       // the other side, just use the 'other' side.
903       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
904           (DemandedMask & (~RHSKnownZero)))
905         return I->getOperand(0);
906       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
907           (DemandedMask & (~LHSKnownZero)))
908         return I->getOperand(1);
909     }
910     
911     // Compute the KnownZero/KnownOne bits to simplify things downstream.
912     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
913     return 0;
914   }
915   
916   // If this is the root being simplified, allow it to have multiple uses,
917   // just set the DemandedMask to all bits so that we can try to simplify the
918   // operands.  This allows visitTruncInst (for example) to simplify the
919   // operand of a trunc without duplicating all the logic below.
920   if (Depth == 0 && !V->hasOneUse())
921     DemandedMask = APInt::getAllOnesValue(BitWidth);
922   
923   switch (I->getOpcode()) {
924   default:
925     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
926     break;
927   case Instruction::And:
928     // If either the LHS or the RHS are Zero, the result is zero.
929     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
930                              RHSKnownZero, RHSKnownOne, Depth+1) ||
931         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
932                              LHSKnownZero, LHSKnownOne, Depth+1))
933       return I;
934     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
935     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
936
937     // If all of the demanded bits are known 1 on one side, return the other.
938     // These bits cannot contribute to the result of the 'and'.
939     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
940         (DemandedMask & ~LHSKnownZero))
941       return I->getOperand(0);
942     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
943         (DemandedMask & ~RHSKnownZero))
944       return I->getOperand(1);
945     
946     // If all of the demanded bits in the inputs are known zeros, return zero.
947     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
948       return Constant::getNullValue(VTy);
949       
950     // If the RHS is a constant, see if we can simplify it.
951     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
952       return I;
953       
954     // Output known-1 bits are only known if set in both the LHS & RHS.
955     RHSKnownOne &= LHSKnownOne;
956     // Output known-0 are known to be clear if zero in either the LHS | RHS.
957     RHSKnownZero |= LHSKnownZero;
958     break;
959   case Instruction::Or:
960     // If either the LHS or the RHS are One, the result is One.
961     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
962                              RHSKnownZero, RHSKnownOne, Depth+1) ||
963         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
964                              LHSKnownZero, LHSKnownOne, Depth+1))
965       return I;
966     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
967     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
968     
969     // If all of the demanded bits are known zero on one side, return the other.
970     // These bits cannot contribute to the result of the 'or'.
971     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
972         (DemandedMask & ~LHSKnownOne))
973       return I->getOperand(0);
974     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
975         (DemandedMask & ~RHSKnownOne))
976       return I->getOperand(1);
977
978     // If all of the potentially set bits on one side are known to be set on
979     // the other side, just use the 'other' side.
980     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
981         (DemandedMask & (~RHSKnownZero)))
982       return I->getOperand(0);
983     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
984         (DemandedMask & (~LHSKnownZero)))
985       return I->getOperand(1);
986         
987     // If the RHS is a constant, see if we can simplify it.
988     if (ShrinkDemandedConstant(I, 1, DemandedMask))
989       return I;
990           
991     // Output known-0 bits are only known if clear in both the LHS & RHS.
992     RHSKnownZero &= LHSKnownZero;
993     // Output known-1 are known to be set if set in either the LHS | RHS.
994     RHSKnownOne |= LHSKnownOne;
995     break;
996   case Instruction::Xor: {
997     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
998                              RHSKnownZero, RHSKnownOne, Depth+1) ||
999         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1000                              LHSKnownZero, LHSKnownOne, Depth+1))
1001       return I;
1002     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1003     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1004     
1005     // If all of the demanded bits are known zero on one side, return the other.
1006     // These bits cannot contribute to the result of the 'xor'.
1007     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1008       return I->getOperand(0);
1009     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1010       return I->getOperand(1);
1011     
1012     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1013     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1014                          (RHSKnownOne & LHSKnownOne);
1015     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1016     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1017                         (RHSKnownOne & LHSKnownZero);
1018     
1019     // If all of the demanded bits are known to be zero on one side or the
1020     // other, turn this into an *inclusive* or.
1021     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1022     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1023       Instruction *Or = 
1024         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1025                                  I->getName());
1026       return InsertNewInstBefore(Or, *I);
1027     }
1028     
1029     // If all of the demanded bits on one side are known, and all of the set
1030     // bits on that side are also known to be set on the other side, turn this
1031     // into an AND, as we know the bits will be cleared.
1032     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1033     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1034       // all known
1035       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1036         Constant *AndC = Constant::getIntegerValue(VTy,
1037                                                    ~RHSKnownOne & DemandedMask);
1038         Instruction *And = 
1039           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1040         return InsertNewInstBefore(And, *I);
1041       }
1042     }
1043     
1044     // If the RHS is a constant, see if we can simplify it.
1045     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1046     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1047       return I;
1048     
1049     RHSKnownZero = KnownZeroOut;
1050     RHSKnownOne  = KnownOneOut;
1051     break;
1052   }
1053   case Instruction::Select:
1054     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1055                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1056         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1057                              LHSKnownZero, LHSKnownOne, Depth+1))
1058       return I;
1059     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1060     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1061     
1062     // If the operands are constants, see if we can simplify them.
1063     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1064         ShrinkDemandedConstant(I, 2, DemandedMask))
1065       return I;
1066     
1067     // Only known if known in both the LHS and RHS.
1068     RHSKnownOne &= LHSKnownOne;
1069     RHSKnownZero &= LHSKnownZero;
1070     break;
1071   case Instruction::Trunc: {
1072     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1073     DemandedMask.zext(truncBf);
1074     RHSKnownZero.zext(truncBf);
1075     RHSKnownOne.zext(truncBf);
1076     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1077                              RHSKnownZero, RHSKnownOne, Depth+1))
1078       return I;
1079     DemandedMask.trunc(BitWidth);
1080     RHSKnownZero.trunc(BitWidth);
1081     RHSKnownOne.trunc(BitWidth);
1082     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1083     break;
1084   }
1085   case Instruction::BitCast:
1086     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1087       return false;  // vector->int or fp->int?
1088
1089     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1090       if (const VectorType *SrcVTy =
1091             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1092         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1093           // Don't touch a bitcast between vectors of different element counts.
1094           return false;
1095       } else
1096         // Don't touch a scalar-to-vector bitcast.
1097         return false;
1098     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1099       // Don't touch a vector-to-scalar bitcast.
1100       return false;
1101
1102     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1103                              RHSKnownZero, RHSKnownOne, Depth+1))
1104       return I;
1105     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1106     break;
1107   case Instruction::ZExt: {
1108     // Compute the bits in the result that are not present in the input.
1109     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1110     
1111     DemandedMask.trunc(SrcBitWidth);
1112     RHSKnownZero.trunc(SrcBitWidth);
1113     RHSKnownOne.trunc(SrcBitWidth);
1114     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1115                              RHSKnownZero, RHSKnownOne, Depth+1))
1116       return I;
1117     DemandedMask.zext(BitWidth);
1118     RHSKnownZero.zext(BitWidth);
1119     RHSKnownOne.zext(BitWidth);
1120     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1121     // The top bits are known to be zero.
1122     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1123     break;
1124   }
1125   case Instruction::SExt: {
1126     // Compute the bits in the result that are not present in the input.
1127     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1128     
1129     APInt InputDemandedBits = DemandedMask & 
1130                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1131
1132     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1133     // If any of the sign extended bits are demanded, we know that the sign
1134     // bit is demanded.
1135     if ((NewBits & DemandedMask) != 0)
1136       InputDemandedBits.set(SrcBitWidth-1);
1137       
1138     InputDemandedBits.trunc(SrcBitWidth);
1139     RHSKnownZero.trunc(SrcBitWidth);
1140     RHSKnownOne.trunc(SrcBitWidth);
1141     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1142                              RHSKnownZero, RHSKnownOne, Depth+1))
1143       return I;
1144     InputDemandedBits.zext(BitWidth);
1145     RHSKnownZero.zext(BitWidth);
1146     RHSKnownOne.zext(BitWidth);
1147     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1148       
1149     // If the sign bit of the input is known set or clear, then we know the
1150     // top bits of the result.
1151
1152     // If the input sign bit is known zero, or if the NewBits are not demanded
1153     // convert this into a zero extension.
1154     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1155       // Convert to ZExt cast
1156       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1157       return InsertNewInstBefore(NewCast, *I);
1158     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1159       RHSKnownOne |= NewBits;
1160     }
1161     break;
1162   }
1163   case Instruction::Add: {
1164     // Figure out what the input bits are.  If the top bits of the and result
1165     // are not demanded, then the add doesn't demand them from its input
1166     // either.
1167     unsigned NLZ = DemandedMask.countLeadingZeros();
1168       
1169     // If there is a constant on the RHS, there are a variety of xformations
1170     // we can do.
1171     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1172       // If null, this should be simplified elsewhere.  Some of the xforms here
1173       // won't work if the RHS is zero.
1174       if (RHS->isZero())
1175         break;
1176       
1177       // If the top bit of the output is demanded, demand everything from the
1178       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1179       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1180
1181       // Find information about known zero/one bits in the input.
1182       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1183                                LHSKnownZero, LHSKnownOne, Depth+1))
1184         return I;
1185
1186       // If the RHS of the add has bits set that can't affect the input, reduce
1187       // the constant.
1188       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1189         return I;
1190       
1191       // Avoid excess work.
1192       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1193         break;
1194       
1195       // Turn it into OR if input bits are zero.
1196       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1197         Instruction *Or =
1198           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1199                                    I->getName());
1200         return InsertNewInstBefore(Or, *I);
1201       }
1202       
1203       // We can say something about the output known-zero and known-one bits,
1204       // depending on potential carries from the input constant and the
1205       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1206       // bits set and the RHS constant is 0x01001, then we know we have a known
1207       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1208       
1209       // To compute this, we first compute the potential carry bits.  These are
1210       // the bits which may be modified.  I'm not aware of a better way to do
1211       // this scan.
1212       const APInt &RHSVal = RHS->getValue();
1213       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1214       
1215       // Now that we know which bits have carries, compute the known-1/0 sets.
1216       
1217       // Bits are known one if they are known zero in one operand and one in the
1218       // other, and there is no input carry.
1219       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1220                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1221       
1222       // Bits are known zero if they are known zero in both operands and there
1223       // is no input carry.
1224       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1225     } else {
1226       // If the high-bits of this ADD are not demanded, then it does not demand
1227       // the high bits of its LHS or RHS.
1228       if (DemandedMask[BitWidth-1] == 0) {
1229         // Right fill the mask of bits for this ADD to demand the most
1230         // significant bit and all those below it.
1231         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1232         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1233                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1234             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1235                                  LHSKnownZero, LHSKnownOne, Depth+1))
1236           return I;
1237       }
1238     }
1239     break;
1240   }
1241   case Instruction::Sub:
1242     // If the high-bits of this SUB are not demanded, then it does not demand
1243     // the high bits of its LHS or RHS.
1244     if (DemandedMask[BitWidth-1] == 0) {
1245       // Right fill the mask of bits for this SUB to demand the most
1246       // significant bit and all those below it.
1247       uint32_t NLZ = DemandedMask.countLeadingZeros();
1248       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1249       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1250                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1251           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1252                                LHSKnownZero, LHSKnownOne, Depth+1))
1253         return I;
1254     }
1255     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1256     // the known zeros and ones.
1257     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1258     break;
1259   case Instruction::Shl:
1260     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1261       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1262       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1263       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1264                                RHSKnownZero, RHSKnownOne, Depth+1))
1265         return I;
1266       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1267       RHSKnownZero <<= ShiftAmt;
1268       RHSKnownOne  <<= ShiftAmt;
1269       // low bits known zero.
1270       if (ShiftAmt)
1271         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1272     }
1273     break;
1274   case Instruction::LShr:
1275     // For a logical shift right
1276     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1277       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1278       
1279       // Unsigned shift right.
1280       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1281       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1282                                RHSKnownZero, RHSKnownOne, Depth+1))
1283         return I;
1284       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1285       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1286       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1287       if (ShiftAmt) {
1288         // Compute the new bits that are at the top now.
1289         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1290         RHSKnownZero |= HighBits;  // high bits known zero.
1291       }
1292     }
1293     break;
1294   case Instruction::AShr:
1295     // If this is an arithmetic shift right and only the low-bit is set, we can
1296     // always convert this into a logical shr, even if the shift amount is
1297     // variable.  The low bit of the shift cannot be an input sign bit unless
1298     // the shift amount is >= the size of the datatype, which is undefined.
1299     if (DemandedMask == 1) {
1300       // Perform the logical shift right.
1301       Instruction *NewVal = BinaryOperator::CreateLShr(
1302                         I->getOperand(0), I->getOperand(1), I->getName());
1303       return InsertNewInstBefore(NewVal, *I);
1304     }    
1305
1306     // If the sign bit is the only bit demanded by this ashr, then there is no
1307     // need to do it, the shift doesn't change the high bit.
1308     if (DemandedMask.isSignBit())
1309       return I->getOperand(0);
1310     
1311     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1312       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1313       
1314       // Signed shift right.
1315       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1316       // If any of the "high bits" are demanded, we should set the sign bit as
1317       // demanded.
1318       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1319         DemandedMaskIn.set(BitWidth-1);
1320       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1321                                RHSKnownZero, RHSKnownOne, Depth+1))
1322         return I;
1323       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1324       // Compute the new bits that are at the top now.
1325       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1326       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1327       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1328         
1329       // Handle the sign bits.
1330       APInt SignBit(APInt::getSignBit(BitWidth));
1331       // Adjust to where it is now in the mask.
1332       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1333         
1334       // If the input sign bit is known to be zero, or if none of the top bits
1335       // are demanded, turn this into an unsigned shift right.
1336       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1337           (HighBits & ~DemandedMask) == HighBits) {
1338         // Perform the logical shift right.
1339         Instruction *NewVal = BinaryOperator::CreateLShr(
1340                           I->getOperand(0), SA, I->getName());
1341         return InsertNewInstBefore(NewVal, *I);
1342       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1343         RHSKnownOne |= HighBits;
1344       }
1345     }
1346     break;
1347   case Instruction::SRem:
1348     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1349       APInt RA = Rem->getValue().abs();
1350       if (RA.isPowerOf2()) {
1351         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1352           return I->getOperand(0);
1353
1354         APInt LowBits = RA - 1;
1355         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1356         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1357                                  LHSKnownZero, LHSKnownOne, Depth+1))
1358           return I;
1359
1360         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1361           LHSKnownZero |= ~LowBits;
1362
1363         KnownZero |= LHSKnownZero & DemandedMask;
1364
1365         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1366       }
1367     }
1368     break;
1369   case Instruction::URem: {
1370     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1371     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1372     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1373                              KnownZero2, KnownOne2, Depth+1) ||
1374         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1375                              KnownZero2, KnownOne2, Depth+1))
1376       return I;
1377
1378     unsigned Leaders = KnownZero2.countLeadingOnes();
1379     Leaders = std::max(Leaders,
1380                        KnownZero2.countLeadingOnes());
1381     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1382     break;
1383   }
1384   case Instruction::Call:
1385     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1386       switch (II->getIntrinsicID()) {
1387       default: break;
1388       case Intrinsic::bswap: {
1389         // If the only bits demanded come from one byte of the bswap result,
1390         // just shift the input byte into position to eliminate the bswap.
1391         unsigned NLZ = DemandedMask.countLeadingZeros();
1392         unsigned NTZ = DemandedMask.countTrailingZeros();
1393           
1394         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1395         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1396         // have 14 leading zeros, round to 8.
1397         NLZ &= ~7;
1398         NTZ &= ~7;
1399         // If we need exactly one byte, we can do this transformation.
1400         if (BitWidth-NLZ-NTZ == 8) {
1401           unsigned ResultBit = NTZ;
1402           unsigned InputBit = BitWidth-NTZ-8;
1403           
1404           // Replace this with either a left or right shift to get the byte into
1405           // the right place.
1406           Instruction *NewVal;
1407           if (InputBit > ResultBit)
1408             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1409                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1410           else
1411             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1412                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1413           NewVal->takeName(I);
1414           return InsertNewInstBefore(NewVal, *I);
1415         }
1416           
1417         // TODO: Could compute known zero/one bits based on the input.
1418         break;
1419       }
1420       }
1421     }
1422     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1423     break;
1424   }
1425   
1426   // If the client is only demanding bits that we know, return the known
1427   // constant.
1428   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1429     return Constant::getIntegerValue(VTy, RHSKnownOne);
1430   return false;
1431 }
1432
1433
1434 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1435 /// any number of elements. DemandedElts contains the set of elements that are
1436 /// actually used by the caller.  This method analyzes which elements of the
1437 /// operand are undef and returns that information in UndefElts.
1438 ///
1439 /// If the information about demanded elements can be used to simplify the
1440 /// operation, the operation is simplified, then the resultant value is
1441 /// returned.  This returns null if no change was made.
1442 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1443                                                 APInt& UndefElts,
1444                                                 unsigned Depth) {
1445   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1446   APInt EltMask(APInt::getAllOnesValue(VWidth));
1447   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1448
1449   if (isa<UndefValue>(V)) {
1450     // If the entire vector is undefined, just return this info.
1451     UndefElts = EltMask;
1452     return 0;
1453   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1454     UndefElts = EltMask;
1455     return UndefValue::get(V->getType());
1456   }
1457
1458   UndefElts = 0;
1459   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1460     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1461     Constant *Undef = UndefValue::get(EltTy);
1462
1463     std::vector<Constant*> Elts;
1464     for (unsigned i = 0; i != VWidth; ++i)
1465       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1466         Elts.push_back(Undef);
1467         UndefElts.set(i);
1468       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1469         Elts.push_back(Undef);
1470         UndefElts.set(i);
1471       } else {                               // Otherwise, defined.
1472         Elts.push_back(CP->getOperand(i));
1473       }
1474
1475     // If we changed the constant, return it.
1476     Constant *NewCP = ConstantVector::get(Elts);
1477     return NewCP != CP ? NewCP : 0;
1478   } else if (isa<ConstantAggregateZero>(V)) {
1479     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1480     // set to undef.
1481     
1482     // Check if this is identity. If so, return 0 since we are not simplifying
1483     // anything.
1484     if (DemandedElts == ((1ULL << VWidth) -1))
1485       return 0;
1486     
1487     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1488     Constant *Zero = Constant::getNullValue(EltTy);
1489     Constant *Undef = UndefValue::get(EltTy);
1490     std::vector<Constant*> Elts;
1491     for (unsigned i = 0; i != VWidth; ++i) {
1492       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1493       Elts.push_back(Elt);
1494     }
1495     UndefElts = DemandedElts ^ EltMask;
1496     return ConstantVector::get(Elts);
1497   }
1498   
1499   // Limit search depth.
1500   if (Depth == 10)
1501     return 0;
1502
1503   // If multiple users are using the root value, procede with
1504   // simplification conservatively assuming that all elements
1505   // are needed.
1506   if (!V->hasOneUse()) {
1507     // Quit if we find multiple users of a non-root value though.
1508     // They'll be handled when it's their turn to be visited by
1509     // the main instcombine process.
1510     if (Depth != 0)
1511       // TODO: Just compute the UndefElts information recursively.
1512       return 0;
1513
1514     // Conservatively assume that all elements are needed.
1515     DemandedElts = EltMask;
1516   }
1517   
1518   Instruction *I = dyn_cast<Instruction>(V);
1519   if (!I) return 0;        // Only analyze instructions.
1520   
1521   bool MadeChange = false;
1522   APInt UndefElts2(VWidth, 0);
1523   Value *TmpV;
1524   switch (I->getOpcode()) {
1525   default: break;
1526     
1527   case Instruction::InsertElement: {
1528     // If this is a variable index, we don't know which element it overwrites.
1529     // demand exactly the same input as we produce.
1530     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1531     if (Idx == 0) {
1532       // Note that we can't propagate undef elt info, because we don't know
1533       // which elt is getting updated.
1534       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1535                                         UndefElts2, Depth+1);
1536       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1537       break;
1538     }
1539     
1540     // If this is inserting an element that isn't demanded, remove this
1541     // insertelement.
1542     unsigned IdxNo = Idx->getZExtValue();
1543     if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1544       Worklist.Add(I);
1545       return I->getOperand(0);
1546     }
1547     
1548     // Otherwise, the element inserted overwrites whatever was there, so the
1549     // input demanded set is simpler than the output set.
1550     APInt DemandedElts2 = DemandedElts;
1551     DemandedElts2.clear(IdxNo);
1552     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1553                                       UndefElts, Depth+1);
1554     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1555
1556     // The inserted element is defined.
1557     UndefElts.clear(IdxNo);
1558     break;
1559   }
1560   case Instruction::ShuffleVector: {
1561     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1562     uint64_t LHSVWidth =
1563       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1564     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1565     for (unsigned i = 0; i < VWidth; i++) {
1566       if (DemandedElts[i]) {
1567         unsigned MaskVal = Shuffle->getMaskValue(i);
1568         if (MaskVal != -1u) {
1569           assert(MaskVal < LHSVWidth * 2 &&
1570                  "shufflevector mask index out of range!");
1571           if (MaskVal < LHSVWidth)
1572             LeftDemanded.set(MaskVal);
1573           else
1574             RightDemanded.set(MaskVal - LHSVWidth);
1575         }
1576       }
1577     }
1578
1579     APInt UndefElts4(LHSVWidth, 0);
1580     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1581                                       UndefElts4, Depth+1);
1582     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1583
1584     APInt UndefElts3(LHSVWidth, 0);
1585     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1586                                       UndefElts3, Depth+1);
1587     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1588
1589     bool NewUndefElts = false;
1590     for (unsigned i = 0; i < VWidth; i++) {
1591       unsigned MaskVal = Shuffle->getMaskValue(i);
1592       if (MaskVal == -1u) {
1593         UndefElts.set(i);
1594       } else if (MaskVal < LHSVWidth) {
1595         if (UndefElts4[MaskVal]) {
1596           NewUndefElts = true;
1597           UndefElts.set(i);
1598         }
1599       } else {
1600         if (UndefElts3[MaskVal - LHSVWidth]) {
1601           NewUndefElts = true;
1602           UndefElts.set(i);
1603         }
1604       }
1605     }
1606
1607     if (NewUndefElts) {
1608       // Add additional discovered undefs.
1609       std::vector<Constant*> Elts;
1610       for (unsigned i = 0; i < VWidth; ++i) {
1611         if (UndefElts[i])
1612           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
1613         else
1614           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
1615                                           Shuffle->getMaskValue(i)));
1616       }
1617       I->setOperand(2, ConstantVector::get(Elts));
1618       MadeChange = true;
1619     }
1620     break;
1621   }
1622   case Instruction::BitCast: {
1623     // Vector->vector casts only.
1624     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1625     if (!VTy) break;
1626     unsigned InVWidth = VTy->getNumElements();
1627     APInt InputDemandedElts(InVWidth, 0);
1628     unsigned Ratio;
1629
1630     if (VWidth == InVWidth) {
1631       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1632       // elements as are demanded of us.
1633       Ratio = 1;
1634       InputDemandedElts = DemandedElts;
1635     } else if (VWidth > InVWidth) {
1636       // Untested so far.
1637       break;
1638       
1639       // If there are more elements in the result than there are in the source,
1640       // then an input element is live if any of the corresponding output
1641       // elements are live.
1642       Ratio = VWidth/InVWidth;
1643       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1644         if (DemandedElts[OutIdx])
1645           InputDemandedElts.set(OutIdx/Ratio);
1646       }
1647     } else {
1648       // Untested so far.
1649       break;
1650       
1651       // If there are more elements in the source than there are in the result,
1652       // then an input element is live if the corresponding output element is
1653       // live.
1654       Ratio = InVWidth/VWidth;
1655       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1656         if (DemandedElts[InIdx/Ratio])
1657           InputDemandedElts.set(InIdx);
1658     }
1659     
1660     // div/rem demand all inputs, because they don't want divide by zero.
1661     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1662                                       UndefElts2, Depth+1);
1663     if (TmpV) {
1664       I->setOperand(0, TmpV);
1665       MadeChange = true;
1666     }
1667     
1668     UndefElts = UndefElts2;
1669     if (VWidth > InVWidth) {
1670       llvm_unreachable("Unimp");
1671       // If there are more elements in the result than there are in the source,
1672       // then an output element is undef if the corresponding input element is
1673       // undef.
1674       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1675         if (UndefElts2[OutIdx/Ratio])
1676           UndefElts.set(OutIdx);
1677     } else if (VWidth < InVWidth) {
1678       llvm_unreachable("Unimp");
1679       // If there are more elements in the source than there are in the result,
1680       // then a result element is undef if all of the corresponding input
1681       // elements are undef.
1682       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1683       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1684         if (!UndefElts2[InIdx])            // Not undef?
1685           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1686     }
1687     break;
1688   }
1689   case Instruction::And:
1690   case Instruction::Or:
1691   case Instruction::Xor:
1692   case Instruction::Add:
1693   case Instruction::Sub:
1694   case Instruction::Mul:
1695     // div/rem demand all inputs, because they don't want divide by zero.
1696     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1697                                       UndefElts, Depth+1);
1698     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1699     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1700                                       UndefElts2, Depth+1);
1701     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1702       
1703     // Output elements are undefined if both are undefined.  Consider things
1704     // like undef&0.  The result is known zero, not undef.
1705     UndefElts &= UndefElts2;
1706     break;
1707     
1708   case Instruction::Call: {
1709     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1710     if (!II) break;
1711     switch (II->getIntrinsicID()) {
1712     default: break;
1713       
1714     // Binary vector operations that work column-wise.  A dest element is a
1715     // function of the corresponding input elements from the two inputs.
1716     case Intrinsic::x86_sse_sub_ss:
1717     case Intrinsic::x86_sse_mul_ss:
1718     case Intrinsic::x86_sse_min_ss:
1719     case Intrinsic::x86_sse_max_ss:
1720     case Intrinsic::x86_sse2_sub_sd:
1721     case Intrinsic::x86_sse2_mul_sd:
1722     case Intrinsic::x86_sse2_min_sd:
1723     case Intrinsic::x86_sse2_max_sd:
1724       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1725                                         UndefElts, Depth+1);
1726       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1727       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1728                                         UndefElts2, Depth+1);
1729       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1730
1731       // If only the low elt is demanded and this is a scalarizable intrinsic,
1732       // scalarize it now.
1733       if (DemandedElts == 1) {
1734         switch (II->getIntrinsicID()) {
1735         default: break;
1736         case Intrinsic::x86_sse_sub_ss:
1737         case Intrinsic::x86_sse_mul_ss:
1738         case Intrinsic::x86_sse2_sub_sd:
1739         case Intrinsic::x86_sse2_mul_sd:
1740           // TODO: Lower MIN/MAX/ABS/etc
1741           Value *LHS = II->getOperand(1);
1742           Value *RHS = II->getOperand(2);
1743           // Extract the element as scalars.
1744           LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS, 
1745             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1746           RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1747             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1748           
1749           switch (II->getIntrinsicID()) {
1750           default: llvm_unreachable("Case stmts out of sync!");
1751           case Intrinsic::x86_sse_sub_ss:
1752           case Intrinsic::x86_sse2_sub_sd:
1753             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1754                                                         II->getName()), *II);
1755             break;
1756           case Intrinsic::x86_sse_mul_ss:
1757           case Intrinsic::x86_sse2_mul_sd:
1758             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1759                                                          II->getName()), *II);
1760             break;
1761           }
1762           
1763           Instruction *New =
1764             InsertElementInst::Create(
1765               UndefValue::get(II->getType()), TmpV,
1766               ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
1767           InsertNewInstBefore(New, *II);
1768           return New;
1769         }            
1770       }
1771         
1772       // Output elements are undefined if both are undefined.  Consider things
1773       // like undef&0.  The result is known zero, not undef.
1774       UndefElts &= UndefElts2;
1775       break;
1776     }
1777     break;
1778   }
1779   }
1780   return MadeChange ? I : 0;
1781 }
1782
1783
1784 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1785 /// function is designed to check a chain of associative operators for a
1786 /// potential to apply a certain optimization.  Since the optimization may be
1787 /// applicable if the expression was reassociated, this checks the chain, then
1788 /// reassociates the expression as necessary to expose the optimization
1789 /// opportunity.  This makes use of a special Functor, which must define
1790 /// 'shouldApply' and 'apply' methods.
1791 ///
1792 template<typename Functor>
1793 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1794   unsigned Opcode = Root.getOpcode();
1795   Value *LHS = Root.getOperand(0);
1796
1797   // Quick check, see if the immediate LHS matches...
1798   if (F.shouldApply(LHS))
1799     return F.apply(Root);
1800
1801   // Otherwise, if the LHS is not of the same opcode as the root, return.
1802   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1803   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1804     // Should we apply this transform to the RHS?
1805     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1806
1807     // If not to the RHS, check to see if we should apply to the LHS...
1808     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1809       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1810       ShouldApply = true;
1811     }
1812
1813     // If the functor wants to apply the optimization to the RHS of LHSI,
1814     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1815     if (ShouldApply) {
1816       // Now all of the instructions are in the current basic block, go ahead
1817       // and perform the reassociation.
1818       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1819
1820       // First move the selected RHS to the LHS of the root...
1821       Root.setOperand(0, LHSI->getOperand(1));
1822
1823       // Make what used to be the LHS of the root be the user of the root...
1824       Value *ExtraOperand = TmpLHSI->getOperand(1);
1825       if (&Root == TmpLHSI) {
1826         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1827         return 0;
1828       }
1829       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1830       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1831       BasicBlock::iterator ARI = &Root; ++ARI;
1832       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1833       ARI = Root;
1834
1835       // Now propagate the ExtraOperand down the chain of instructions until we
1836       // get to LHSI.
1837       while (TmpLHSI != LHSI) {
1838         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1839         // Move the instruction to immediately before the chain we are
1840         // constructing to avoid breaking dominance properties.
1841         NextLHSI->moveBefore(ARI);
1842         ARI = NextLHSI;
1843
1844         Value *NextOp = NextLHSI->getOperand(1);
1845         NextLHSI->setOperand(1, ExtraOperand);
1846         TmpLHSI = NextLHSI;
1847         ExtraOperand = NextOp;
1848       }
1849
1850       // Now that the instructions are reassociated, have the functor perform
1851       // the transformation...
1852       return F.apply(Root);
1853     }
1854
1855     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1856   }
1857   return 0;
1858 }
1859
1860 namespace {
1861
1862 // AddRHS - Implements: X + X --> X << 1
1863 struct AddRHS {
1864   Value *RHS;
1865   explicit AddRHS(Value *rhs) : RHS(rhs) {}
1866   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1867   Instruction *apply(BinaryOperator &Add) const {
1868     return BinaryOperator::CreateShl(Add.getOperand(0),
1869                                      ConstantInt::get(Add.getType(), 1));
1870   }
1871 };
1872
1873 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1874 //                 iff C1&C2 == 0
1875 struct AddMaskingAnd {
1876   Constant *C2;
1877   explicit AddMaskingAnd(Constant *c) : C2(c) {}
1878   bool shouldApply(Value *LHS) const {
1879     ConstantInt *C1;
1880     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1881            ConstantExpr::getAnd(C1, C2)->isNullValue();
1882   }
1883   Instruction *apply(BinaryOperator &Add) const {
1884     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1885   }
1886 };
1887
1888 }
1889
1890 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1891                                              InstCombiner *IC) {
1892   if (CastInst *CI = dyn_cast<CastInst>(&I))
1893     return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
1894
1895   // Figure out if the constant is the left or the right argument.
1896   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1897   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1898
1899   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1900     if (ConstIsRHS)
1901       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1902     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1903   }
1904
1905   Value *Op0 = SO, *Op1 = ConstOperand;
1906   if (!ConstIsRHS)
1907     std::swap(Op0, Op1);
1908   
1909   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1910     return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1911                                     SO->getName()+".op");
1912   if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1913     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1914                                    SO->getName()+".cmp");
1915   if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1916     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1917                                    SO->getName()+".cmp");
1918   llvm_unreachable("Unknown binary instruction type!");
1919 }
1920
1921 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1922 // constant as the other operand, try to fold the binary operator into the
1923 // select arguments.  This also works for Cast instructions, which obviously do
1924 // not have a second operand.
1925 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1926                                      InstCombiner *IC) {
1927   // Don't modify shared select instructions
1928   if (!SI->hasOneUse()) return 0;
1929   Value *TV = SI->getOperand(1);
1930   Value *FV = SI->getOperand(2);
1931
1932   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1933     // Bool selects with constant operands can be folded to logical ops.
1934     if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
1935
1936     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1937     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1938
1939     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1940                               SelectFalseVal);
1941   }
1942   return 0;
1943 }
1944
1945
1946 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
1947 /// has a PHI node as operand #0, see if we can fold the instruction into the
1948 /// PHI (which is only possible if all operands to the PHI are constants).
1949 ///
1950 /// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
1951 /// that would normally be unprofitable because they strongly encourage jump
1952 /// threading.
1953 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
1954                                          bool AllowAggressive) {
1955   AllowAggressive = false;
1956   PHINode *PN = cast<PHINode>(I.getOperand(0));
1957   unsigned NumPHIValues = PN->getNumIncomingValues();
1958   if (NumPHIValues == 0 ||
1959       // We normally only transform phis with a single use, unless we're trying
1960       // hard to make jump threading happen.
1961       (!PN->hasOneUse() && !AllowAggressive))
1962     return 0;
1963   
1964   
1965   // Check to see if all of the operands of the PHI are simple constants
1966   // (constantint/constantfp/undef).  If there is one non-constant value,
1967   // remember the BB it is in.  If there is more than one or if *it* is a PHI,
1968   // bail out.  We don't do arbitrary constant expressions here because moving
1969   // their computation can be expensive without a cost model.
1970   BasicBlock *NonConstBB = 0;
1971   for (unsigned i = 0; i != NumPHIValues; ++i)
1972     if (!isa<Constant>(PN->getIncomingValue(i)) ||
1973         isa<ConstantExpr>(PN->getIncomingValue(i))) {
1974       if (NonConstBB) return 0;  // More than one non-const value.
1975       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1976       NonConstBB = PN->getIncomingBlock(i);
1977       
1978       // If the incoming non-constant value is in I's block, we have an infinite
1979       // loop.
1980       if (NonConstBB == I.getParent())
1981         return 0;
1982     }
1983   
1984   // If there is exactly one non-constant value, we can insert a copy of the
1985   // operation in that block.  However, if this is a critical edge, we would be
1986   // inserting the computation one some other paths (e.g. inside a loop).  Only
1987   // do this if the pred block is unconditionally branching into the phi block.
1988   if (NonConstBB != 0 && !AllowAggressive) {
1989     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1990     if (!BI || !BI->isUnconditional()) return 0;
1991   }
1992
1993   // Okay, we can do the transformation: create the new PHI node.
1994   PHINode *NewPN = PHINode::Create(I.getType(), "");
1995   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1996   InsertNewInstBefore(NewPN, *PN);
1997   NewPN->takeName(PN);
1998
1999   // Next, add all of the operands to the PHI.
2000   if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2001     // We only currently try to fold the condition of a select when it is a phi,
2002     // not the true/false values.
2003     Value *TrueV = SI->getTrueValue();
2004     Value *FalseV = SI->getFalseValue();
2005     for (unsigned i = 0; i != NumPHIValues; ++i) {
2006       BasicBlock *ThisBB = PN->getIncomingBlock(i);
2007       Value *TrueVInPred = TrueV->DoPHITranslation(I.getParent(), ThisBB);
2008       Value *FalseVInPred = FalseV->DoPHITranslation(I.getParent(), ThisBB);
2009       Value *InV = 0;
2010       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2011         InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
2012       } else {
2013         assert(PN->getIncomingBlock(i) == NonConstBB);
2014         InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2015                                  FalseVInPred,
2016                                  "phitmp", NonConstBB->getTerminator());
2017         Worklist.Add(cast<Instruction>(InV));
2018       }
2019       NewPN->addIncoming(InV, ThisBB);
2020     }
2021   } else if (I.getNumOperands() == 2) {
2022     Constant *C = cast<Constant>(I.getOperand(1));
2023     for (unsigned i = 0; i != NumPHIValues; ++i) {
2024       Value *InV = 0;
2025       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2026         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2027           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2028         else
2029           InV = ConstantExpr::get(I.getOpcode(), InC, C);
2030       } else {
2031         assert(PN->getIncomingBlock(i) == NonConstBB);
2032         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2033           InV = BinaryOperator::Create(BO->getOpcode(),
2034                                        PN->getIncomingValue(i), C, "phitmp",
2035                                        NonConstBB->getTerminator());
2036         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2037           InV = CmpInst::Create(CI->getOpcode(),
2038                                 CI->getPredicate(),
2039                                 PN->getIncomingValue(i), C, "phitmp",
2040                                 NonConstBB->getTerminator());
2041         else
2042           llvm_unreachable("Unknown binop!");
2043         
2044         Worklist.Add(cast<Instruction>(InV));
2045       }
2046       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2047     }
2048   } else { 
2049     CastInst *CI = cast<CastInst>(&I);
2050     const Type *RetTy = CI->getType();
2051     for (unsigned i = 0; i != NumPHIValues; ++i) {
2052       Value *InV;
2053       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2054         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2055       } else {
2056         assert(PN->getIncomingBlock(i) == NonConstBB);
2057         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2058                                I.getType(), "phitmp", 
2059                                NonConstBB->getTerminator());
2060         Worklist.Add(cast<Instruction>(InV));
2061       }
2062       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2063     }
2064   }
2065   return ReplaceInstUsesWith(I, NewPN);
2066 }
2067
2068
2069 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2070 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2071 /// This basically requires proving that the add in the original type would not
2072 /// overflow to change the sign bit or have a carry out.
2073 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2074   // There are different heuristics we can use for this.  Here are some simple
2075   // ones.
2076   
2077   // Add has the property that adding any two 2's complement numbers can only 
2078   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2079   // have at least two sign bits, we know that the addition of the two values will
2080   // sign extend fine.
2081   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2082     return true;
2083   
2084   
2085   // If one of the operands only has one non-zero bit, and if the other operand
2086   // has a known-zero bit in a more significant place than it (not including the
2087   // sign bit) the ripple may go up to and fill the zero, but won't change the
2088   // sign.  For example, (X & ~4) + 1.
2089   
2090   // TODO: Implement.
2091   
2092   return false;
2093 }
2094
2095
2096 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2097   bool Changed = SimplifyCommutative(I);
2098   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2099
2100   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2101     // X + undef -> undef
2102     if (isa<UndefValue>(RHS))
2103       return ReplaceInstUsesWith(I, RHS);
2104
2105     // X + 0 --> X
2106     if (RHSC->isNullValue())
2107       return ReplaceInstUsesWith(I, LHS);
2108
2109     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2110       // X + (signbit) --> X ^ signbit
2111       const APInt& Val = CI->getValue();
2112       uint32_t BitWidth = Val.getBitWidth();
2113       if (Val == APInt::getSignBit(BitWidth))
2114         return BinaryOperator::CreateXor(LHS, RHS);
2115       
2116       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2117       // (X & 254)+1 -> (X&254)|1
2118       if (SimplifyDemandedInstructionBits(I))
2119         return &I;
2120
2121       // zext(bool) + C -> bool ? C + 1 : C
2122       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2123         if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2124           return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2125     }
2126
2127     if (isa<PHINode>(LHS))
2128       if (Instruction *NV = FoldOpIntoPhi(I))
2129         return NV;
2130     
2131     ConstantInt *XorRHS = 0;
2132     Value *XorLHS = 0;
2133     if (isa<ConstantInt>(RHSC) &&
2134         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2135       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2136       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2137       
2138       uint32_t Size = TySizeBits / 2;
2139       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2140       APInt CFF80Val(-C0080Val);
2141       do {
2142         if (TySizeBits > Size) {
2143           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2144           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2145           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2146               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2147             // This is a sign extend if the top bits are known zero.
2148             if (!MaskedValueIsZero(XorLHS, 
2149                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2150               Size = 0;  // Not a sign ext, but can't be any others either.
2151             break;
2152           }
2153         }
2154         Size >>= 1;
2155         C0080Val = APIntOps::lshr(C0080Val, Size);
2156         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2157       } while (Size >= 1);
2158       
2159       // FIXME: This shouldn't be necessary. When the backends can handle types
2160       // with funny bit widths then this switch statement should be removed. It
2161       // is just here to get the size of the "middle" type back up to something
2162       // that the back ends can handle.
2163       const Type *MiddleType = 0;
2164       switch (Size) {
2165         default: break;
2166         case 32: MiddleType = Type::getInt32Ty(*Context); break;
2167         case 16: MiddleType = Type::getInt16Ty(*Context); break;
2168         case  8: MiddleType = Type::getInt8Ty(*Context); break;
2169       }
2170       if (MiddleType) {
2171         Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
2172         return new SExtInst(NewTrunc, I.getType(), I.getName());
2173       }
2174     }
2175   }
2176
2177   if (I.getType() == Type::getInt1Ty(*Context))
2178     return BinaryOperator::CreateXor(LHS, RHS);
2179
2180   // X + X --> X << 1
2181   if (I.getType()->isInteger()) {
2182     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2183       return Result;
2184
2185     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2186       if (RHSI->getOpcode() == Instruction::Sub)
2187         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2188           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2189     }
2190     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2191       if (LHSI->getOpcode() == Instruction::Sub)
2192         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2193           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2194     }
2195   }
2196
2197   // -A + B  -->  B - A
2198   // -A + -B  -->  -(A + B)
2199   if (Value *LHSV = dyn_castNegVal(LHS)) {
2200     if (LHS->getType()->isIntOrIntVector()) {
2201       if (Value *RHSV = dyn_castNegVal(RHS)) {
2202         Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
2203         return BinaryOperator::CreateNeg(NewAdd);
2204       }
2205     }
2206     
2207     return BinaryOperator::CreateSub(RHS, LHSV);
2208   }
2209
2210   // A + -B  -->  A - B
2211   if (!isa<Constant>(RHS))
2212     if (Value *V = dyn_castNegVal(RHS))
2213       return BinaryOperator::CreateSub(LHS, V);
2214
2215
2216   ConstantInt *C2;
2217   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2218     if (X == RHS)   // X*C + X --> X * (C+1)
2219       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2220
2221     // X*C1 + X*C2 --> X * (C1+C2)
2222     ConstantInt *C1;
2223     if (X == dyn_castFoldableMul(RHS, C1))
2224       return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2225   }
2226
2227   // X + X*C --> X * (C+1)
2228   if (dyn_castFoldableMul(RHS, C2) == LHS)
2229     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2230
2231   // X + ~X --> -1   since   ~X = -X-1
2232   if (dyn_castNotVal(LHS) == RHS ||
2233       dyn_castNotVal(RHS) == LHS)
2234     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2235   
2236
2237   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2238   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2239     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2240       return R;
2241   
2242   // A+B --> A|B iff A and B have no bits set in common.
2243   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2244     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2245     APInt LHSKnownOne(IT->getBitWidth(), 0);
2246     APInt LHSKnownZero(IT->getBitWidth(), 0);
2247     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2248     if (LHSKnownZero != 0) {
2249       APInt RHSKnownOne(IT->getBitWidth(), 0);
2250       APInt RHSKnownZero(IT->getBitWidth(), 0);
2251       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2252       
2253       // No bits in common -> bitwise or.
2254       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2255         return BinaryOperator::CreateOr(LHS, RHS);
2256     }
2257   }
2258
2259   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2260   if (I.getType()->isIntOrIntVector()) {
2261     Value *W, *X, *Y, *Z;
2262     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2263         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2264       if (W != Y) {
2265         if (W == Z) {
2266           std::swap(Y, Z);
2267         } else if (Y == X) {
2268           std::swap(W, X);
2269         } else if (X == Z) {
2270           std::swap(Y, Z);
2271           std::swap(W, X);
2272         }
2273       }
2274
2275       if (W == Y) {
2276         Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
2277         return BinaryOperator::CreateMul(W, NewAdd);
2278       }
2279     }
2280   }
2281
2282   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2283     Value *X = 0;
2284     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2285       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2286
2287     // (X & FF00) + xx00  -> (X+xx00) & FF00
2288     if (LHS->hasOneUse() &&
2289         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2290       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2291       if (Anded == CRHS) {
2292         // See if all bits from the first bit set in the Add RHS up are included
2293         // in the mask.  First, get the rightmost bit.
2294         const APInt& AddRHSV = CRHS->getValue();
2295
2296         // Form a mask of all bits from the lowest bit added through the top.
2297         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2298
2299         // See if the and mask includes all of these bits.
2300         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2301
2302         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2303           // Okay, the xform is safe.  Insert the new add pronto.
2304           Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
2305           return BinaryOperator::CreateAnd(NewAdd, C2);
2306         }
2307       }
2308     }
2309
2310     // Try to fold constant add into select arguments.
2311     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2312       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2313         return R;
2314   }
2315
2316   // add (select X 0 (sub n A)) A  -->  select X A n
2317   {
2318     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2319     Value *A = RHS;
2320     if (!SI) {
2321       SI = dyn_cast<SelectInst>(RHS);
2322       A = LHS;
2323     }
2324     if (SI && SI->hasOneUse()) {
2325       Value *TV = SI->getTrueValue();
2326       Value *FV = SI->getFalseValue();
2327       Value *N;
2328
2329       // Can we fold the add into the argument of the select?
2330       // We check both true and false select arguments for a matching subtract.
2331       if (match(FV, m_Zero()) &&
2332           match(TV, m_Sub(m_Value(N), m_Specific(A))))
2333         // Fold the add into the true select value.
2334         return SelectInst::Create(SI->getCondition(), N, A);
2335       if (match(TV, m_Zero()) &&
2336           match(FV, m_Sub(m_Value(N), m_Specific(A))))
2337         // Fold the add into the false select value.
2338         return SelectInst::Create(SI->getCondition(), A, N);
2339     }
2340   }
2341
2342   // Check for (add (sext x), y), see if we can merge this into an
2343   // integer add followed by a sext.
2344   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2345     // (add (sext x), cst) --> (sext (add x, cst'))
2346     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2347       Constant *CI = 
2348         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2349       if (LHSConv->hasOneUse() &&
2350           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2351           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2352         // Insert the new, smaller add.
2353         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0), 
2354                                            CI, "addconv");
2355         return new SExtInst(NewAdd, I.getType());
2356       }
2357     }
2358     
2359     // (add (sext x), (sext y)) --> (sext (add int x, y))
2360     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2361       // Only do this if x/y have the same type, if at last one of them has a
2362       // single use (so we don't increase the number of sexts), and if the
2363       // integer add will not overflow.
2364       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2365           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2366           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2367                                    RHSConv->getOperand(0))) {
2368         // Insert the new integer add.
2369         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0), 
2370                                            RHSConv->getOperand(0), "addconv");
2371         return new SExtInst(NewAdd, I.getType());
2372       }
2373     }
2374   }
2375
2376   return Changed ? &I : 0;
2377 }
2378
2379 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2380   bool Changed = SimplifyCommutative(I);
2381   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2382
2383   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2384     // X + 0 --> X
2385     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2386       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2387                               (I.getType())->getValueAPF()))
2388         return ReplaceInstUsesWith(I, LHS);
2389     }
2390
2391     if (isa<PHINode>(LHS))
2392       if (Instruction *NV = FoldOpIntoPhi(I))
2393         return NV;
2394   }
2395
2396   // -A + B  -->  B - A
2397   // -A + -B  -->  -(A + B)
2398   if (Value *LHSV = dyn_castFNegVal(LHS))
2399     return BinaryOperator::CreateFSub(RHS, LHSV);
2400
2401   // A + -B  -->  A - B
2402   if (!isa<Constant>(RHS))
2403     if (Value *V = dyn_castFNegVal(RHS))
2404       return BinaryOperator::CreateFSub(LHS, V);
2405
2406   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2407   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2408     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2409       return ReplaceInstUsesWith(I, LHS);
2410
2411   // Check for (add double (sitofp x), y), see if we can merge this into an
2412   // integer add followed by a promotion.
2413   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2414     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2415     // ... if the constant fits in the integer value.  This is useful for things
2416     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2417     // requires a constant pool load, and generally allows the add to be better
2418     // instcombined.
2419     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2420       Constant *CI = 
2421       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2422       if (LHSConv->hasOneUse() &&
2423           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2424           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2425         // Insert the new integer add.
2426         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2427                                            CI, "addconv");
2428         return new SIToFPInst(NewAdd, I.getType());
2429       }
2430     }
2431     
2432     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2433     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2434       // Only do this if x/y have the same type, if at last one of them has a
2435       // single use (so we don't increase the number of int->fp conversions),
2436       // and if the integer add will not overflow.
2437       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2438           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2439           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2440                                    RHSConv->getOperand(0))) {
2441         // Insert the new integer add.
2442         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0), 
2443                                            RHSConv->getOperand(0), "addconv");
2444         return new SIToFPInst(NewAdd, I.getType());
2445       }
2446     }
2447   }
2448   
2449   return Changed ? &I : 0;
2450 }
2451
2452 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2453   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2454
2455   if (Op0 == Op1)                        // sub X, X  -> 0
2456     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2457
2458   // If this is a 'B = x-(-A)', change to B = x+A...
2459   if (Value *V = dyn_castNegVal(Op1))
2460     return BinaryOperator::CreateAdd(Op0, V);
2461
2462   if (isa<UndefValue>(Op0))
2463     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2464   if (isa<UndefValue>(Op1))
2465     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2466
2467   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2468     // Replace (-1 - A) with (~A)...
2469     if (C->isAllOnesValue())
2470       return BinaryOperator::CreateNot(Op1);
2471
2472     // C - ~X == X + (1+C)
2473     Value *X = 0;
2474     if (match(Op1, m_Not(m_Value(X))))
2475       return BinaryOperator::CreateAdd(X, AddOne(C));
2476
2477     // -(X >>u 31) -> (X >>s 31)
2478     // -(X >>s 31) -> (X >>u 31)
2479     if (C->isZero()) {
2480       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2481         if (SI->getOpcode() == Instruction::LShr) {
2482           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2483             // Check to see if we are shifting out everything but the sign bit.
2484             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2485                 SI->getType()->getPrimitiveSizeInBits()-1) {
2486               // Ok, the transformation is safe.  Insert AShr.
2487               return BinaryOperator::Create(Instruction::AShr, 
2488                                           SI->getOperand(0), CU, SI->getName());
2489             }
2490           }
2491         }
2492         else if (SI->getOpcode() == Instruction::AShr) {
2493           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2494             // Check to see if we are shifting out everything but the sign bit.
2495             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2496                 SI->getType()->getPrimitiveSizeInBits()-1) {
2497               // Ok, the transformation is safe.  Insert LShr. 
2498               return BinaryOperator::CreateLShr(
2499                                           SI->getOperand(0), CU, SI->getName());
2500             }
2501           }
2502         }
2503       }
2504     }
2505
2506     // Try to fold constant sub into select arguments.
2507     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2508       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2509         return R;
2510
2511     // C - zext(bool) -> bool ? C - 1 : C
2512     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2513       if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2514         return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2515   }
2516
2517   if (I.getType() == Type::getInt1Ty(*Context))
2518     return BinaryOperator::CreateXor(Op0, Op1);
2519
2520   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2521     if (Op1I->getOpcode() == Instruction::Add) {
2522       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2523         return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2524                                          I.getName());
2525       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2526         return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2527                                          I.getName());
2528       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2529         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2530           // C1-(X+C2) --> (C1-C2)-X
2531           return BinaryOperator::CreateSub(
2532             ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2533       }
2534     }
2535
2536     if (Op1I->hasOneUse()) {
2537       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2538       // is not used by anyone else...
2539       //
2540       if (Op1I->getOpcode() == Instruction::Sub) {
2541         // Swap the two operands of the subexpr...
2542         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2543         Op1I->setOperand(0, IIOp1);
2544         Op1I->setOperand(1, IIOp0);
2545
2546         // Create the new top level add instruction...
2547         return BinaryOperator::CreateAdd(Op0, Op1);
2548       }
2549
2550       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2551       //
2552       if (Op1I->getOpcode() == Instruction::And &&
2553           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2554         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2555
2556         Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
2557         return BinaryOperator::CreateAnd(Op0, NewNot);
2558       }
2559
2560       // 0 - (X sdiv C)  -> (X sdiv -C)
2561       if (Op1I->getOpcode() == Instruction::SDiv)
2562         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2563           if (CSI->isZero())
2564             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2565               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2566                                           ConstantExpr::getNeg(DivRHS));
2567
2568       // X - X*C --> X * (1-C)
2569       ConstantInt *C2 = 0;
2570       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2571         Constant *CP1 = 
2572           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2573                                              C2);
2574         return BinaryOperator::CreateMul(Op0, CP1);
2575       }
2576     }
2577   }
2578
2579   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2580     if (Op0I->getOpcode() == Instruction::Add) {
2581       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2582         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2583       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2584         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2585     } else if (Op0I->getOpcode() == Instruction::Sub) {
2586       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2587         return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2588                                          I.getName());
2589     }
2590   }
2591
2592   ConstantInt *C1;
2593   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2594     if (X == Op1)  // X*C - X --> X * (C-1)
2595       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2596
2597     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2598     if (X == dyn_castFoldableMul(Op1, C2))
2599       return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2600   }
2601   return 0;
2602 }
2603
2604 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2605   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2606
2607   // If this is a 'B = x-(-A)', change to B = x+A...
2608   if (Value *V = dyn_castFNegVal(Op1))
2609     return BinaryOperator::CreateFAdd(Op0, V);
2610
2611   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2612     if (Op1I->getOpcode() == Instruction::FAdd) {
2613       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2614         return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
2615                                           I.getName());
2616       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2617         return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
2618                                           I.getName());
2619     }
2620   }
2621
2622   return 0;
2623 }
2624
2625 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2626 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2627 /// TrueIfSigned if the result of the comparison is true when the input value is
2628 /// signed.
2629 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2630                            bool &TrueIfSigned) {
2631   switch (pred) {
2632   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2633     TrueIfSigned = true;
2634     return RHS->isZero();
2635   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2636     TrueIfSigned = true;
2637     return RHS->isAllOnesValue();
2638   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2639     TrueIfSigned = false;
2640     return RHS->isAllOnesValue();
2641   case ICmpInst::ICMP_UGT:
2642     // True if LHS u> RHS and RHS == high-bit-mask - 1
2643     TrueIfSigned = true;
2644     return RHS->getValue() ==
2645       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2646   case ICmpInst::ICMP_UGE: 
2647     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2648     TrueIfSigned = true;
2649     return RHS->getValue().isSignBit();
2650   default:
2651     return false;
2652   }
2653 }
2654
2655 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2656   bool Changed = SimplifyCommutative(I);
2657   Value *Op0 = I.getOperand(0);
2658
2659   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2660     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2661
2662   // Simplify mul instructions with a constant RHS...
2663   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2664     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2665
2666       // ((X << C1)*C2) == (X * (C2 << C1))
2667       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2668         if (SI->getOpcode() == Instruction::Shl)
2669           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2670             return BinaryOperator::CreateMul(SI->getOperand(0),
2671                                         ConstantExpr::getShl(CI, ShOp));
2672
2673       if (CI->isZero())
2674         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2675       if (CI->equalsInt(1))                  // X * 1  == X
2676         return ReplaceInstUsesWith(I, Op0);
2677       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2678         return BinaryOperator::CreateNeg(Op0, I.getName());
2679
2680       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2681       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2682         return BinaryOperator::CreateShl(Op0,
2683                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2684       }
2685     } else if (isa<VectorType>(Op1->getType())) {
2686       if (Op1->isNullValue())
2687         return ReplaceInstUsesWith(I, Op1);
2688
2689       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2690         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2691           return BinaryOperator::CreateNeg(Op0, I.getName());
2692
2693         // As above, vector X*splat(1.0) -> X in all defined cases.
2694         if (Constant *Splat = Op1V->getSplatValue()) {
2695           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2696             if (CI->equalsInt(1))
2697               return ReplaceInstUsesWith(I, Op0);
2698         }
2699       }
2700     }
2701     
2702     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2703       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2704           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2705         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2706         Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1, "tmp");
2707         Value *C1C2 = Builder->CreateMul(Op1, Op0I->getOperand(1));
2708         return BinaryOperator::CreateAdd(Add, C1C2);
2709         
2710       }
2711
2712     // Try to fold constant mul into select arguments.
2713     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2714       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2715         return R;
2716
2717     if (isa<PHINode>(Op0))
2718       if (Instruction *NV = FoldOpIntoPhi(I))
2719         return NV;
2720   }
2721
2722   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2723     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2724       return BinaryOperator::CreateMul(Op0v, Op1v);
2725
2726   // (X / Y) *  Y = X - (X % Y)
2727   // (X / Y) * -Y = (X % Y) - X
2728   {
2729     Value *Op1 = I.getOperand(1);
2730     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2731     if (!BO ||
2732         (BO->getOpcode() != Instruction::UDiv && 
2733          BO->getOpcode() != Instruction::SDiv)) {
2734       Op1 = Op0;
2735       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2736     }
2737     Value *Neg = dyn_castNegVal(Op1);
2738     if (BO && BO->hasOneUse() &&
2739         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2740         (BO->getOpcode() == Instruction::UDiv ||
2741          BO->getOpcode() == Instruction::SDiv)) {
2742       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2743
2744       // If the division is exact, X % Y is zero.
2745       if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2746         if (SDiv->isExact()) {
2747           if (Op1BO == Op1)
2748             return ReplaceInstUsesWith(I, Op0BO);
2749           else
2750             return BinaryOperator::CreateNeg(Op0BO);
2751         }
2752
2753       Value *Rem;
2754       if (BO->getOpcode() == Instruction::UDiv)
2755         Rem = Builder->CreateURem(Op0BO, Op1BO);
2756       else
2757         Rem = Builder->CreateSRem(Op0BO, Op1BO);
2758       Rem->takeName(BO);
2759
2760       if (Op1BO == Op1)
2761         return BinaryOperator::CreateSub(Op0BO, Rem);
2762       return BinaryOperator::CreateSub(Rem, Op0BO);
2763     }
2764   }
2765
2766   if (I.getType() == Type::getInt1Ty(*Context))
2767     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2768
2769   // If one of the operands of the multiply is a cast from a boolean value, then
2770   // we know the bool is either zero or one, so this is a 'masking' multiply.
2771   // See if we can simplify things based on how the boolean was originally
2772   // formed.
2773   CastInst *BoolCast = 0;
2774   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2775     if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2776       BoolCast = CI;
2777   if (!BoolCast)
2778     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2779       if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2780         BoolCast = CI;
2781   if (BoolCast) {
2782     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2783       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2784       const Type *SCOpTy = SCIOp0->getType();
2785       bool TIS = false;
2786       
2787       // If the icmp is true iff the sign bit of X is set, then convert this
2788       // multiply into a shift/and combination.
2789       if (isa<ConstantInt>(SCIOp1) &&
2790           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2791           TIS) {
2792         // Shift the X value right to turn it into "all signbits".
2793         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2794                                           SCOpTy->getPrimitiveSizeInBits()-1);
2795         Value *V = Builder->CreateAShr(SCIOp0, Amt,
2796                                     BoolCast->getOperand(0)->getName()+".mask");
2797
2798         // If the multiply type is not the same as the source type, sign extend
2799         // or truncate to the multiply type.
2800         if (I.getType() != V->getType())
2801           V = Builder->CreateIntCast(V, I.getType(), true);
2802
2803         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2804         return BinaryOperator::CreateAnd(V, OtherOp);
2805       }
2806     }
2807   }
2808
2809   return Changed ? &I : 0;
2810 }
2811
2812 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2813   bool Changed = SimplifyCommutative(I);
2814   Value *Op0 = I.getOperand(0);
2815
2816   // Simplify mul instructions with a constant RHS...
2817   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2818     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2819       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2820       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2821       if (Op1F->isExactlyValue(1.0))
2822         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2823     } else if (isa<VectorType>(Op1->getType())) {
2824       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2825         // As above, vector X*splat(1.0) -> X in all defined cases.
2826         if (Constant *Splat = Op1V->getSplatValue()) {
2827           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2828             if (F->isExactlyValue(1.0))
2829               return ReplaceInstUsesWith(I, Op0);
2830         }
2831       }
2832     }
2833
2834     // Try to fold constant mul into select arguments.
2835     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2836       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2837         return R;
2838
2839     if (isa<PHINode>(Op0))
2840       if (Instruction *NV = FoldOpIntoPhi(I))
2841         return NV;
2842   }
2843
2844   if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
2845     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
2846       return BinaryOperator::CreateFMul(Op0v, Op1v);
2847
2848   return Changed ? &I : 0;
2849 }
2850
2851 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2852 /// instruction.
2853 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2854   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2855   
2856   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2857   int NonNullOperand = -1;
2858   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2859     if (ST->isNullValue())
2860       NonNullOperand = 2;
2861   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2862   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2863     if (ST->isNullValue())
2864       NonNullOperand = 1;
2865   
2866   if (NonNullOperand == -1)
2867     return false;
2868   
2869   Value *SelectCond = SI->getOperand(0);
2870   
2871   // Change the div/rem to use 'Y' instead of the select.
2872   I.setOperand(1, SI->getOperand(NonNullOperand));
2873   
2874   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2875   // problem.  However, the select, or the condition of the select may have
2876   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2877   // propagate the known value for the select into other uses of it, and
2878   // propagate a known value of the condition into its other users.
2879   
2880   // If the select and condition only have a single use, don't bother with this,
2881   // early exit.
2882   if (SI->use_empty() && SelectCond->hasOneUse())
2883     return true;
2884   
2885   // Scan the current block backward, looking for other uses of SI.
2886   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2887   
2888   while (BBI != BBFront) {
2889     --BBI;
2890     // If we found a call to a function, we can't assume it will return, so
2891     // information from below it cannot be propagated above it.
2892     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2893       break;
2894     
2895     // Replace uses of the select or its condition with the known values.
2896     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2897          I != E; ++I) {
2898       if (*I == SI) {
2899         *I = SI->getOperand(NonNullOperand);
2900         Worklist.Add(BBI);
2901       } else if (*I == SelectCond) {
2902         *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2903                                    ConstantInt::getFalse(*Context);
2904         Worklist.Add(BBI);
2905       }
2906     }
2907     
2908     // If we past the instruction, quit looking for it.
2909     if (&*BBI == SI)
2910       SI = 0;
2911     if (&*BBI == SelectCond)
2912       SelectCond = 0;
2913     
2914     // If we ran out of things to eliminate, break out of the loop.
2915     if (SelectCond == 0 && SI == 0)
2916       break;
2917     
2918   }
2919   return true;
2920 }
2921
2922
2923 /// This function implements the transforms on div instructions that work
2924 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2925 /// used by the visitors to those instructions.
2926 /// @brief Transforms common to all three div instructions
2927 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2928   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2929
2930   // undef / X -> 0        for integer.
2931   // undef / X -> undef    for FP (the undef could be a snan).
2932   if (isa<UndefValue>(Op0)) {
2933     if (Op0->getType()->isFPOrFPVector())
2934       return ReplaceInstUsesWith(I, Op0);
2935     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2936   }
2937
2938   // X / undef -> undef
2939   if (isa<UndefValue>(Op1))
2940     return ReplaceInstUsesWith(I, Op1);
2941
2942   return 0;
2943 }
2944
2945 /// This function implements the transforms common to both integer division
2946 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2947 /// division instructions.
2948 /// @brief Common integer divide transforms
2949 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2950   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2951
2952   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2953   if (Op0 == Op1) {
2954     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2955       Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
2956       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2957       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2958     }
2959
2960     Constant *CI = ConstantInt::get(I.getType(), 1);
2961     return ReplaceInstUsesWith(I, CI);
2962   }
2963   
2964   if (Instruction *Common = commonDivTransforms(I))
2965     return Common;
2966   
2967   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2968   // This does not apply for fdiv.
2969   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2970     return &I;
2971
2972   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2973     // div X, 1 == X
2974     if (RHS->equalsInt(1))
2975       return ReplaceInstUsesWith(I, Op0);
2976
2977     // (X / C1) / C2  -> X / (C1*C2)
2978     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2979       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2980         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2981           if (MultiplyOverflows(RHS, LHSRHS,
2982                                 I.getOpcode()==Instruction::SDiv))
2983             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2984           else 
2985             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2986                                       ConstantExpr::getMul(RHS, LHSRHS));
2987         }
2988
2989     if (!RHS->isZero()) { // avoid X udiv 0
2990       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2991         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2992           return R;
2993       if (isa<PHINode>(Op0))
2994         if (Instruction *NV = FoldOpIntoPhi(I))
2995           return NV;
2996     }
2997   }
2998
2999   // 0 / X == 0, we don't need to preserve faults!
3000   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3001     if (LHS->equalsInt(0))
3002       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3003
3004   // It can't be division by zero, hence it must be division by one.
3005   if (I.getType() == Type::getInt1Ty(*Context))
3006     return ReplaceInstUsesWith(I, Op0);
3007
3008   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3009     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3010       // div X, 1 == X
3011       if (X->isOne())
3012         return ReplaceInstUsesWith(I, Op0);
3013   }
3014
3015   return 0;
3016 }
3017
3018 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3019   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3020
3021   // Handle the integer div common cases
3022   if (Instruction *Common = commonIDivTransforms(I))
3023     return Common;
3024
3025   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3026     // X udiv C^2 -> X >> C
3027     // Check to see if this is an unsigned division with an exact power of 2,
3028     // if so, convert to a right shift.
3029     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3030       return BinaryOperator::CreateLShr(Op0, 
3031             ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3032
3033     // X udiv C, where C >= signbit
3034     if (C->getValue().isNegative()) {
3035       Value *IC = Builder->CreateICmpULT( Op0, C);
3036       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3037                                 ConstantInt::get(I.getType(), 1));
3038     }
3039   }
3040
3041   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3042   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3043     if (RHSI->getOpcode() == Instruction::Shl &&
3044         isa<ConstantInt>(RHSI->getOperand(0))) {
3045       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3046       if (C1.isPowerOf2()) {
3047         Value *N = RHSI->getOperand(1);
3048         const Type *NTy = N->getType();
3049         if (uint32_t C2 = C1.logBase2())
3050           N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
3051         return BinaryOperator::CreateLShr(Op0, N);
3052       }
3053     }
3054   }
3055   
3056   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3057   // where C1&C2 are powers of two.
3058   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3059     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3060       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3061         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3062         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3063           // Compute the shift amounts
3064           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3065           // Construct the "on true" case of the select
3066           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3067           Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
3068   
3069           // Construct the "on false" case of the select
3070           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3071           Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
3072
3073           // construct the select instruction and return it.
3074           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3075         }
3076       }
3077   return 0;
3078 }
3079
3080 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3081   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3082
3083   // Handle the integer div common cases
3084   if (Instruction *Common = commonIDivTransforms(I))
3085     return Common;
3086
3087   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3088     // sdiv X, -1 == -X
3089     if (RHS->isAllOnesValue())
3090       return BinaryOperator::CreateNeg(Op0);
3091
3092     // sdiv X, C  -->  ashr X, log2(C)
3093     if (cast<SDivOperator>(&I)->isExact() &&
3094         RHS->getValue().isNonNegative() &&
3095         RHS->getValue().isPowerOf2()) {
3096       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3097                                             RHS->getValue().exactLogBase2());
3098       return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3099     }
3100
3101     // -X/C  -->  X/-C  provided the negation doesn't overflow.
3102     if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3103       if (isa<Constant>(Sub->getOperand(0)) &&
3104           cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3105           Sub->hasNoSignedWrap())
3106         return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3107                                           ConstantExpr::getNeg(RHS));
3108   }
3109
3110   // If the sign bits of both operands are zero (i.e. we can prove they are
3111   // unsigned inputs), turn this into a udiv.
3112   if (I.getType()->isInteger()) {
3113     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3114     if (MaskedValueIsZero(Op0, Mask)) {
3115       if (MaskedValueIsZero(Op1, Mask)) {
3116         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3117         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3118       }
3119       ConstantInt *ShiftedInt;
3120       if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3121           ShiftedInt->getValue().isPowerOf2()) {
3122         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3123         // Safe because the only negative value (1 << Y) can take on is
3124         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3125         // the sign bit set.
3126         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3127       }
3128     }
3129   }
3130   
3131   return 0;
3132 }
3133
3134 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3135   return commonDivTransforms(I);
3136 }
3137
3138 /// This function implements the transforms on rem instructions that work
3139 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3140 /// is used by the visitors to those instructions.
3141 /// @brief Transforms common to all three rem instructions
3142 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3143   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3144
3145   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3146     if (I.getType()->isFPOrFPVector())
3147       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3148     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3149   }
3150   if (isa<UndefValue>(Op1))
3151     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3152
3153   // Handle cases involving: rem X, (select Cond, Y, Z)
3154   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3155     return &I;
3156
3157   return 0;
3158 }
3159
3160 /// This function implements the transforms common to both integer remainder
3161 /// instructions (urem and srem). It is called by the visitors to those integer
3162 /// remainder instructions.
3163 /// @brief Common integer remainder transforms
3164 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3165   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3166
3167   if (Instruction *common = commonRemTransforms(I))
3168     return common;
3169
3170   // 0 % X == 0 for integer, we don't need to preserve faults!
3171   if (Constant *LHS = dyn_cast<Constant>(Op0))
3172     if (LHS->isNullValue())
3173       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3174
3175   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3176     // X % 0 == undef, we don't need to preserve faults!
3177     if (RHS->equalsInt(0))
3178       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3179     
3180     if (RHS->equalsInt(1))  // X % 1 == 0
3181       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3182
3183     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3184       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3185         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3186           return R;
3187       } else if (isa<PHINode>(Op0I)) {
3188         if (Instruction *NV = FoldOpIntoPhi(I))
3189           return NV;
3190       }
3191
3192       // See if we can fold away this rem instruction.
3193       if (SimplifyDemandedInstructionBits(I))
3194         return &I;
3195     }
3196   }
3197
3198   return 0;
3199 }
3200
3201 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3202   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3203
3204   if (Instruction *common = commonIRemTransforms(I))
3205     return common;
3206   
3207   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3208     // X urem C^2 -> X and C
3209     // Check to see if this is an unsigned remainder with an exact power of 2,
3210     // if so, convert to a bitwise and.
3211     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3212       if (C->getValue().isPowerOf2())
3213         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3214   }
3215
3216   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3217     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3218     if (RHSI->getOpcode() == Instruction::Shl &&
3219         isa<ConstantInt>(RHSI->getOperand(0))) {
3220       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3221         Constant *N1 = Constant::getAllOnesValue(I.getType());
3222         Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
3223         return BinaryOperator::CreateAnd(Op0, Add);
3224       }
3225     }
3226   }
3227
3228   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3229   // where C1&C2 are powers of two.
3230   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3231     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3232       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3233         // STO == 0 and SFO == 0 handled above.
3234         if ((STO->getValue().isPowerOf2()) && 
3235             (SFO->getValue().isPowerOf2())) {
3236           Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3237                                               SI->getName()+".t");
3238           Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3239                                                SI->getName()+".f");
3240           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3241         }
3242       }
3243   }
3244   
3245   return 0;
3246 }
3247
3248 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3249   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3250
3251   // Handle the integer rem common cases
3252   if (Instruction *Common = commonIRemTransforms(I))
3253     return Common;
3254   
3255   if (Value *RHSNeg = dyn_castNegVal(Op1))
3256     if (!isa<Constant>(RHSNeg) ||
3257         (isa<ConstantInt>(RHSNeg) &&
3258          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3259       // X % -Y -> X % Y
3260       Worklist.AddValue(I.getOperand(1));
3261       I.setOperand(1, RHSNeg);
3262       return &I;
3263     }
3264
3265   // If the sign bits of both operands are zero (i.e. we can prove they are
3266   // unsigned inputs), turn this into a urem.
3267   if (I.getType()->isInteger()) {
3268     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3269     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3270       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3271       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3272     }
3273   }
3274
3275   // If it's a constant vector, flip any negative values positive.
3276   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3277     unsigned VWidth = RHSV->getNumOperands();
3278
3279     bool hasNegative = false;
3280     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3281       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3282         if (RHS->getValue().isNegative())
3283           hasNegative = true;
3284
3285     if (hasNegative) {
3286       std::vector<Constant *> Elts(VWidth);
3287       for (unsigned i = 0; i != VWidth; ++i) {
3288         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3289           if (RHS->getValue().isNegative())
3290             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3291           else
3292             Elts[i] = RHS;
3293         }
3294       }
3295
3296       Constant *NewRHSV = ConstantVector::get(Elts);
3297       if (NewRHSV != RHSV) {
3298         Worklist.AddValue(I.getOperand(1));
3299         I.setOperand(1, NewRHSV);
3300         return &I;
3301       }
3302     }
3303   }
3304
3305   return 0;
3306 }
3307
3308 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3309   return commonRemTransforms(I);
3310 }
3311
3312 // isOneBitSet - Return true if there is exactly one bit set in the specified
3313 // constant.
3314 static bool isOneBitSet(const ConstantInt *CI) {
3315   return CI->getValue().isPowerOf2();
3316 }
3317
3318 // isHighOnes - Return true if the constant is of the form 1+0+.
3319 // This is the same as lowones(~X).
3320 static bool isHighOnes(const ConstantInt *CI) {
3321   return (~CI->getValue() + 1).isPowerOf2();
3322 }
3323
3324 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3325 /// are carefully arranged to allow folding of expressions such as:
3326 ///
3327 ///      (A < B) | (A > B) --> (A != B)
3328 ///
3329 /// Note that this is only valid if the first and second predicates have the
3330 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3331 ///
3332 /// Three bits are used to represent the condition, as follows:
3333 ///   0  A > B
3334 ///   1  A == B
3335 ///   2  A < B
3336 ///
3337 /// <=>  Value  Definition
3338 /// 000     0   Always false
3339 /// 001     1   A >  B
3340 /// 010     2   A == B
3341 /// 011     3   A >= B
3342 /// 100     4   A <  B
3343 /// 101     5   A != B
3344 /// 110     6   A <= B
3345 /// 111     7   Always true
3346 ///  
3347 static unsigned getICmpCode(const ICmpInst *ICI) {
3348   switch (ICI->getPredicate()) {
3349     // False -> 0
3350   case ICmpInst::ICMP_UGT: return 1;  // 001
3351   case ICmpInst::ICMP_SGT: return 1;  // 001
3352   case ICmpInst::ICMP_EQ:  return 2;  // 010
3353   case ICmpInst::ICMP_UGE: return 3;  // 011
3354   case ICmpInst::ICMP_SGE: return 3;  // 011
3355   case ICmpInst::ICMP_ULT: return 4;  // 100
3356   case ICmpInst::ICMP_SLT: return 4;  // 100
3357   case ICmpInst::ICMP_NE:  return 5;  // 101
3358   case ICmpInst::ICMP_ULE: return 6;  // 110
3359   case ICmpInst::ICMP_SLE: return 6;  // 110
3360     // True -> 7
3361   default:
3362     llvm_unreachable("Invalid ICmp predicate!");
3363     return 0;
3364   }
3365 }
3366
3367 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3368 /// predicate into a three bit mask. It also returns whether it is an ordered
3369 /// predicate by reference.
3370 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3371   isOrdered = false;
3372   switch (CC) {
3373   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3374   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3375   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3376   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3377   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3378   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3379   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3380   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3381   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3382   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3383   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3384   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3385   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3386   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3387     // True -> 7
3388   default:
3389     // Not expecting FCMP_FALSE and FCMP_TRUE;
3390     llvm_unreachable("Unexpected FCmp predicate!");
3391     return 0;
3392   }
3393 }
3394
3395 /// getICmpValue - This is the complement of getICmpCode, which turns an
3396 /// opcode and two operands into either a constant true or false, or a brand 
3397 /// new ICmp instruction. The sign is passed in to determine which kind
3398 /// of predicate to use in the new icmp instruction.
3399 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3400                            LLVMContext *Context) {
3401   switch (code) {
3402   default: llvm_unreachable("Illegal ICmp code!");
3403   case  0: return ConstantInt::getFalse(*Context);
3404   case  1: 
3405     if (sign)
3406       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3407     else
3408       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3409   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3410   case  3: 
3411     if (sign)
3412       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3413     else
3414       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3415   case  4: 
3416     if (sign)
3417       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3418     else
3419       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3420   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3421   case  6: 
3422     if (sign)
3423       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3424     else
3425       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3426   case  7: return ConstantInt::getTrue(*Context);
3427   }
3428 }
3429
3430 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3431 /// opcode and two operands into either a FCmp instruction. isordered is passed
3432 /// in to determine which kind of predicate to use in the new fcmp instruction.
3433 static Value *getFCmpValue(bool isordered, unsigned code,
3434                            Value *LHS, Value *RHS, LLVMContext *Context) {
3435   switch (code) {
3436   default: llvm_unreachable("Illegal FCmp code!");
3437   case  0:
3438     if (isordered)
3439       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3440     else
3441       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3442   case  1: 
3443     if (isordered)
3444       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3445     else
3446       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3447   case  2: 
3448     if (isordered)
3449       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3450     else
3451       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3452   case  3: 
3453     if (isordered)
3454       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3455     else
3456       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3457   case  4: 
3458     if (isordered)
3459       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3460     else
3461       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3462   case  5: 
3463     if (isordered)
3464       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3465     else
3466       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3467   case  6: 
3468     if (isordered)
3469       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3470     else
3471       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3472   case  7: return ConstantInt::getTrue(*Context);
3473   }
3474 }
3475
3476 /// PredicatesFoldable - Return true if both predicates match sign or if at
3477 /// least one of them is an equality comparison (which is signless).
3478 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3479   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3480          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3481          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3482 }
3483
3484 namespace { 
3485 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3486 struct FoldICmpLogical {
3487   InstCombiner &IC;
3488   Value *LHS, *RHS;
3489   ICmpInst::Predicate pred;
3490   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3491     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3492       pred(ICI->getPredicate()) {}
3493   bool shouldApply(Value *V) const {
3494     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3495       if (PredicatesFoldable(pred, ICI->getPredicate()))
3496         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3497                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3498     return false;
3499   }
3500   Instruction *apply(Instruction &Log) const {
3501     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3502     if (ICI->getOperand(0) != LHS) {
3503       assert(ICI->getOperand(1) == LHS);
3504       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3505     }
3506
3507     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3508     unsigned LHSCode = getICmpCode(ICI);
3509     unsigned RHSCode = getICmpCode(RHSICI);
3510     unsigned Code;
3511     switch (Log.getOpcode()) {
3512     case Instruction::And: Code = LHSCode & RHSCode; break;
3513     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3514     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3515     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3516     }
3517
3518     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3519                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3520       
3521     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3522     if (Instruction *I = dyn_cast<Instruction>(RV))
3523       return I;
3524     // Otherwise, it's a constant boolean value...
3525     return IC.ReplaceInstUsesWith(Log, RV);
3526   }
3527 };
3528 } // end anonymous namespace
3529
3530 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3531 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3532 // guaranteed to be a binary operator.
3533 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3534                                     ConstantInt *OpRHS,
3535                                     ConstantInt *AndRHS,
3536                                     BinaryOperator &TheAnd) {
3537   Value *X = Op->getOperand(0);
3538   Constant *Together = 0;
3539   if (!Op->isShift())
3540     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3541
3542   switch (Op->getOpcode()) {
3543   case Instruction::Xor:
3544     if (Op->hasOneUse()) {
3545       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3546       Value *And = Builder->CreateAnd(X, AndRHS);
3547       And->takeName(Op);
3548       return BinaryOperator::CreateXor(And, Together);
3549     }
3550     break;
3551   case Instruction::Or:
3552     if (Together == AndRHS) // (X | C) & C --> C
3553       return ReplaceInstUsesWith(TheAnd, AndRHS);
3554
3555     if (Op->hasOneUse() && Together != OpRHS) {
3556       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3557       Value *Or = Builder->CreateOr(X, Together);
3558       Or->takeName(Op);
3559       return BinaryOperator::CreateAnd(Or, AndRHS);
3560     }
3561     break;
3562   case Instruction::Add:
3563     if (Op->hasOneUse()) {
3564       // Adding a one to a single bit bit-field should be turned into an XOR
3565       // of the bit.  First thing to check is to see if this AND is with a
3566       // single bit constant.
3567       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3568
3569       // If there is only one bit set...
3570       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3571         // Ok, at this point, we know that we are masking the result of the
3572         // ADD down to exactly one bit.  If the constant we are adding has
3573         // no bits set below this bit, then we can eliminate the ADD.
3574         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3575
3576         // Check to see if any bits below the one bit set in AndRHSV are set.
3577         if ((AddRHS & (AndRHSV-1)) == 0) {
3578           // If not, the only thing that can effect the output of the AND is
3579           // the bit specified by AndRHSV.  If that bit is set, the effect of
3580           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3581           // no effect.
3582           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3583             TheAnd.setOperand(0, X);
3584             return &TheAnd;
3585           } else {
3586             // Pull the XOR out of the AND.
3587             Value *NewAnd = Builder->CreateAnd(X, AndRHS);
3588             NewAnd->takeName(Op);
3589             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3590           }
3591         }
3592       }
3593     }
3594     break;
3595
3596   case Instruction::Shl: {
3597     // We know that the AND will not produce any of the bits shifted in, so if
3598     // the anded constant includes them, clear them now!
3599     //
3600     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3601     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3602     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3603     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3604
3605     if (CI->getValue() == ShlMask) { 
3606     // Masking out bits that the shift already masks
3607       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3608     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3609       TheAnd.setOperand(1, CI);
3610       return &TheAnd;
3611     }
3612     break;
3613   }
3614   case Instruction::LShr:
3615   {
3616     // We know that the AND will not produce any of the bits shifted in, so if
3617     // the anded constant includes them, clear them now!  This only applies to
3618     // unsigned shifts, because a signed shr may bring in set bits!
3619     //
3620     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3621     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3622     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3623     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3624
3625     if (CI->getValue() == ShrMask) {   
3626     // Masking out bits that the shift already masks.
3627       return ReplaceInstUsesWith(TheAnd, Op);
3628     } else if (CI != AndRHS) {
3629       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3630       return &TheAnd;
3631     }
3632     break;
3633   }
3634   case Instruction::AShr:
3635     // Signed shr.
3636     // See if this is shifting in some sign extension, then masking it out
3637     // with an and.
3638     if (Op->hasOneUse()) {
3639       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3640       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3641       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3642       Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3643       if (C == AndRHS) {          // Masking out bits shifted in.
3644         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3645         // Make the argument unsigned.
3646         Value *ShVal = Op->getOperand(0);
3647         ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
3648         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3649       }
3650     }
3651     break;
3652   }
3653   return 0;
3654 }
3655
3656
3657 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3658 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3659 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3660 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3661 /// insert new instructions.
3662 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3663                                            bool isSigned, bool Inside, 
3664                                            Instruction &IB) {
3665   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3666             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3667          "Lo is not <= Hi in range emission code!");
3668     
3669   if (Inside) {
3670     if (Lo == Hi)  // Trivially false.
3671       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3672
3673     // V >= Min && V < Hi --> V < Hi
3674     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3675       ICmpInst::Predicate pred = (isSigned ? 
3676         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3677       return new ICmpInst(pred, V, Hi);
3678     }
3679
3680     // Emit V-Lo <u Hi-Lo
3681     Constant *NegLo = ConstantExpr::getNeg(Lo);
3682     Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3683     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3684     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3685   }
3686
3687   if (Lo == Hi)  // Trivially true.
3688     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3689
3690   // V < Min || V >= Hi -> V > Hi-1
3691   Hi = SubOne(cast<ConstantInt>(Hi));
3692   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3693     ICmpInst::Predicate pred = (isSigned ? 
3694         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3695     return new ICmpInst(pred, V, Hi);
3696   }
3697
3698   // Emit V-Lo >u Hi-1-Lo
3699   // Note that Hi has already had one subtracted from it, above.
3700   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3701   Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3702   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3703   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3704 }
3705
3706 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3707 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3708 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3709 // not, since all 1s are not contiguous.
3710 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3711   const APInt& V = Val->getValue();
3712   uint32_t BitWidth = Val->getType()->getBitWidth();
3713   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3714
3715   // look for the first zero bit after the run of ones
3716   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3717   // look for the first non-zero bit
3718   ME = V.getActiveBits(); 
3719   return true;
3720 }
3721
3722 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3723 /// where isSub determines whether the operator is a sub.  If we can fold one of
3724 /// the following xforms:
3725 /// 
3726 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3727 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3728 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3729 ///
3730 /// return (A +/- B).
3731 ///
3732 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3733                                         ConstantInt *Mask, bool isSub,
3734                                         Instruction &I) {
3735   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3736   if (!LHSI || LHSI->getNumOperands() != 2 ||
3737       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3738
3739   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3740
3741   switch (LHSI->getOpcode()) {
3742   default: return 0;
3743   case Instruction::And:
3744     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3745       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3746       if ((Mask->getValue().countLeadingZeros() + 
3747            Mask->getValue().countPopulation()) == 
3748           Mask->getValue().getBitWidth())
3749         break;
3750
3751       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3752       // part, we don't need any explicit masks to take them out of A.  If that
3753       // is all N is, ignore it.
3754       uint32_t MB = 0, ME = 0;
3755       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3756         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3757         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3758         if (MaskedValueIsZero(RHS, Mask))
3759           break;
3760       }
3761     }
3762     return 0;
3763   case Instruction::Or:
3764   case Instruction::Xor:
3765     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3766     if ((Mask->getValue().countLeadingZeros() + 
3767          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3768         && ConstantExpr::getAnd(N, Mask)->isNullValue())
3769       break;
3770     return 0;
3771   }
3772   
3773   if (isSub)
3774     return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3775   return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
3776 }
3777
3778 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3779 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3780                                           ICmpInst *LHS, ICmpInst *RHS) {
3781   Value *Val, *Val2;
3782   ConstantInt *LHSCst, *RHSCst;
3783   ICmpInst::Predicate LHSCC, RHSCC;
3784   
3785   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3786   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3787                          m_ConstantInt(LHSCst))) ||
3788       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3789                          m_ConstantInt(RHSCst))))
3790     return 0;
3791   
3792   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3793   // where C is a power of 2
3794   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3795       LHSCst->getValue().isPowerOf2()) {
3796     Value *NewOr = Builder->CreateOr(Val, Val2);
3797     return new ICmpInst(LHSCC, NewOr, LHSCst);
3798   }
3799   
3800   // From here on, we only handle:
3801   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3802   if (Val != Val2) return 0;
3803   
3804   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3805   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3806       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3807       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3808       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3809     return 0;
3810   
3811   // We can't fold (ugt x, C) & (sgt x, C2).
3812   if (!PredicatesFoldable(LHSCC, RHSCC))
3813     return 0;
3814     
3815   // Ensure that the larger constant is on the RHS.
3816   bool ShouldSwap;
3817   if (ICmpInst::isSignedPredicate(LHSCC) ||
3818       (ICmpInst::isEquality(LHSCC) && 
3819        ICmpInst::isSignedPredicate(RHSCC)))
3820     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3821   else
3822     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3823     
3824   if (ShouldSwap) {
3825     std::swap(LHS, RHS);
3826     std::swap(LHSCst, RHSCst);
3827     std::swap(LHSCC, RHSCC);
3828   }
3829
3830   // At this point, we know we have have two icmp instructions
3831   // comparing a value against two constants and and'ing the result
3832   // together.  Because of the above check, we know that we only have
3833   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3834   // (from the FoldICmpLogical check above), that the two constants 
3835   // are not equal and that the larger constant is on the RHS
3836   assert(LHSCst != RHSCst && "Compares not folded above?");
3837
3838   switch (LHSCC) {
3839   default: llvm_unreachable("Unknown integer condition code!");
3840   case ICmpInst::ICMP_EQ:
3841     switch (RHSCC) {
3842     default: llvm_unreachable("Unknown integer condition code!");
3843     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3844     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3845     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3846       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3847     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3848     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3849     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3850       return ReplaceInstUsesWith(I, LHS);
3851     }
3852   case ICmpInst::ICMP_NE:
3853     switch (RHSCC) {
3854     default: llvm_unreachable("Unknown integer condition code!");
3855     case ICmpInst::ICMP_ULT:
3856       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3857         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3858       break;                        // (X != 13 & X u< 15) -> no change
3859     case ICmpInst::ICMP_SLT:
3860       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3861         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3862       break;                        // (X != 13 & X s< 15) -> no change
3863     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3864     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3865     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3866       return ReplaceInstUsesWith(I, RHS);
3867     case ICmpInst::ICMP_NE:
3868       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3869         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3870         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
3871         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3872                             ConstantInt::get(Add->getType(), 1));
3873       }
3874       break;                        // (X != 13 & X != 15) -> no change
3875     }
3876     break;
3877   case ICmpInst::ICMP_ULT:
3878     switch (RHSCC) {
3879     default: llvm_unreachable("Unknown integer condition code!");
3880     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3881     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3882       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3883     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3884       break;
3885     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3886     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3887       return ReplaceInstUsesWith(I, LHS);
3888     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3889       break;
3890     }
3891     break;
3892   case ICmpInst::ICMP_SLT:
3893     switch (RHSCC) {
3894     default: llvm_unreachable("Unknown integer condition code!");
3895     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3896     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3897       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3898     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3899       break;
3900     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3901     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3902       return ReplaceInstUsesWith(I, LHS);
3903     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3904       break;
3905     }
3906     break;
3907   case ICmpInst::ICMP_UGT:
3908     switch (RHSCC) {
3909     default: llvm_unreachable("Unknown integer condition code!");
3910     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3911     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3912       return ReplaceInstUsesWith(I, RHS);
3913     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3914       break;
3915     case ICmpInst::ICMP_NE:
3916       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3917         return new ICmpInst(LHSCC, Val, RHSCst);
3918       break;                        // (X u> 13 & X != 15) -> no change
3919     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3920       return InsertRangeTest(Val, AddOne(LHSCst),
3921                              RHSCst, false, true, I);
3922     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3923       break;
3924     }
3925     break;
3926   case ICmpInst::ICMP_SGT:
3927     switch (RHSCC) {
3928     default: llvm_unreachable("Unknown integer condition code!");
3929     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3930     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3931       return ReplaceInstUsesWith(I, RHS);
3932     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3933       break;
3934     case ICmpInst::ICMP_NE:
3935       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3936         return new ICmpInst(LHSCC, Val, RHSCst);
3937       break;                        // (X s> 13 & X != 15) -> no change
3938     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3939       return InsertRangeTest(Val, AddOne(LHSCst),
3940                              RHSCst, true, true, I);
3941     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3942       break;
3943     }
3944     break;
3945   }
3946  
3947   return 0;
3948 }
3949
3950 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3951                                           FCmpInst *RHS) {
3952   
3953   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3954       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3955     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3956     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3957       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3958         // If either of the constants are nans, then the whole thing returns
3959         // false.
3960         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3961           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3962         return new FCmpInst(FCmpInst::FCMP_ORD,
3963                             LHS->getOperand(0), RHS->getOperand(0));
3964       }
3965     
3966     // Handle vector zeros.  This occurs because the canonical form of
3967     // "fcmp ord x,x" is "fcmp ord x, 0".
3968     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3969         isa<ConstantAggregateZero>(RHS->getOperand(1)))
3970       return new FCmpInst(FCmpInst::FCMP_ORD,
3971                           LHS->getOperand(0), RHS->getOperand(0));
3972     return 0;
3973   }
3974   
3975   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3976   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3977   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3978   
3979   
3980   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3981     // Swap RHS operands to match LHS.
3982     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3983     std::swap(Op1LHS, Op1RHS);
3984   }
3985   
3986   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3987     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3988     if (Op0CC == Op1CC)
3989       return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
3990     
3991     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
3992       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3993     if (Op0CC == FCmpInst::FCMP_TRUE)
3994       return ReplaceInstUsesWith(I, RHS);
3995     if (Op1CC == FCmpInst::FCMP_TRUE)
3996       return ReplaceInstUsesWith(I, LHS);
3997     
3998     bool Op0Ordered;
3999     bool Op1Ordered;
4000     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4001     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4002     if (Op1Pred == 0) {
4003       std::swap(LHS, RHS);
4004       std::swap(Op0Pred, Op1Pred);
4005       std::swap(Op0Ordered, Op1Ordered);
4006     }
4007     if (Op0Pred == 0) {
4008       // uno && ueq -> uno && (uno || eq) -> ueq
4009       // ord && olt -> ord && (ord && lt) -> olt
4010       if (Op0Ordered == Op1Ordered)
4011         return ReplaceInstUsesWith(I, RHS);
4012       
4013       // uno && oeq -> uno && (ord && eq) -> false
4014       // uno && ord -> false
4015       if (!Op0Ordered)
4016         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4017       // ord && ueq -> ord && (uno || eq) -> oeq
4018       return cast<Instruction>(getFCmpValue(true, Op1Pred,
4019                                             Op0LHS, Op0RHS, Context));
4020     }
4021   }
4022
4023   return 0;
4024 }
4025
4026
4027 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4028   bool Changed = SimplifyCommutative(I);
4029   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4030
4031   if (isa<UndefValue>(Op1))                         // X & undef -> 0
4032     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4033
4034   // and X, X = X
4035   if (Op0 == Op1)
4036     return ReplaceInstUsesWith(I, Op1);
4037
4038   // See if we can simplify any instructions used by the instruction whose sole 
4039   // purpose is to compute bits we don't care about.
4040   if (SimplifyDemandedInstructionBits(I))
4041     return &I;
4042   if (isa<VectorType>(I.getType())) {
4043     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4044       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
4045         return ReplaceInstUsesWith(I, I.getOperand(0));
4046     } else if (isa<ConstantAggregateZero>(Op1)) {
4047       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
4048     }
4049   }
4050
4051   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4052     const APInt& AndRHSMask = AndRHS->getValue();
4053     APInt NotAndRHS(~AndRHSMask);
4054
4055     // Optimize a variety of ((val OP C1) & C2) combinations...
4056     if (isa<BinaryOperator>(Op0)) {
4057       Instruction *Op0I = cast<Instruction>(Op0);
4058       Value *Op0LHS = Op0I->getOperand(0);
4059       Value *Op0RHS = Op0I->getOperand(1);
4060       switch (Op0I->getOpcode()) {
4061       case Instruction::Xor:
4062       case Instruction::Or:
4063         // If the mask is only needed on one incoming arm, push it up.
4064         if (Op0I->hasOneUse()) {
4065           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4066             // Not masking anything out for the LHS, move to RHS.
4067             Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4068                                                Op0RHS->getName()+".masked");
4069             return BinaryOperator::Create(
4070                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4071           }
4072           if (!isa<Constant>(Op0RHS) &&
4073               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4074             // Not masking anything out for the RHS, move to LHS.
4075             Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4076                                                Op0LHS->getName()+".masked");
4077             return BinaryOperator::Create(
4078                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4079           }
4080         }
4081
4082         break;
4083       case Instruction::Add:
4084         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4085         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4086         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4087         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4088           return BinaryOperator::CreateAnd(V, AndRHS);
4089         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4090           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4091         break;
4092
4093       case Instruction::Sub:
4094         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4095         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4096         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4097         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4098           return BinaryOperator::CreateAnd(V, AndRHS);
4099
4100         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4101         // has 1's for all bits that the subtraction with A might affect.
4102         if (Op0I->hasOneUse()) {
4103           uint32_t BitWidth = AndRHSMask.getBitWidth();
4104           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4105           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4106
4107           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4108           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4109               MaskedValueIsZero(Op0LHS, Mask)) {
4110             Value *NewNeg = Builder->CreateNeg(Op0RHS);
4111             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4112           }
4113         }
4114         break;
4115
4116       case Instruction::Shl:
4117       case Instruction::LShr:
4118         // (1 << x) & 1 --> zext(x == 0)
4119         // (1 >> x) & 1 --> zext(x == 0)
4120         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4121           Value *NewICmp =
4122             Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
4123           return new ZExtInst(NewICmp, I.getType());
4124         }
4125         break;
4126       }
4127
4128       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4129         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4130           return Res;
4131     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4132       // If this is an integer truncation or change from signed-to-unsigned, and
4133       // if the source is an and/or with immediate, transform it.  This
4134       // frequently occurs for bitfield accesses.
4135       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4136         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4137             CastOp->getNumOperands() == 2)
4138           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4139             if (CastOp->getOpcode() == Instruction::And) {
4140               // Change: and (cast (and X, C1) to T), C2
4141               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4142               // This will fold the two constants together, which may allow 
4143               // other simplifications.
4144               Value *NewCast = Builder->CreateTruncOrBitCast(
4145                 CastOp->getOperand(0), I.getType(), 
4146                 CastOp->getName()+".shrunk");
4147               // trunc_or_bitcast(C1)&C2
4148               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4149               C3 = ConstantExpr::getAnd(C3, AndRHS);
4150               return BinaryOperator::CreateAnd(NewCast, C3);
4151             } else if (CastOp->getOpcode() == Instruction::Or) {
4152               // Change: and (cast (or X, C1) to T), C2
4153               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4154               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4155               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4156                 // trunc(C1)&C2
4157                 return ReplaceInstUsesWith(I, AndRHS);
4158             }
4159           }
4160       }
4161     }
4162
4163     // Try to fold constant and into select arguments.
4164     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4165       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4166         return R;
4167     if (isa<PHINode>(Op0))
4168       if (Instruction *NV = FoldOpIntoPhi(I))
4169         return NV;
4170   }
4171
4172   Value *Op0NotVal = dyn_castNotVal(Op0);
4173   Value *Op1NotVal = dyn_castNotVal(Op1);
4174
4175   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4176     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4177
4178   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4179   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4180     Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4181                                   I.getName()+".demorgan");
4182     return BinaryOperator::CreateNot(Or);
4183   }
4184   
4185   {
4186     Value *A = 0, *B = 0, *C = 0, *D = 0;
4187     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4188       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4189         return ReplaceInstUsesWith(I, Op1);
4190     
4191       // (A|B) & ~(A&B) -> A^B
4192       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4193         if ((A == C && B == D) || (A == D && B == C))
4194           return BinaryOperator::CreateXor(A, B);
4195       }
4196     }
4197     
4198     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4199       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4200         return ReplaceInstUsesWith(I, Op0);
4201
4202       // ~(A&B) & (A|B) -> A^B
4203       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4204         if ((A == C && B == D) || (A == D && B == C))
4205           return BinaryOperator::CreateXor(A, B);
4206       }
4207     }
4208     
4209     if (Op0->hasOneUse() &&
4210         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4211       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4212         I.swapOperands();     // Simplify below
4213         std::swap(Op0, Op1);
4214       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4215         cast<BinaryOperator>(Op0)->swapOperands();
4216         I.swapOperands();     // Simplify below
4217         std::swap(Op0, Op1);
4218       }
4219     }
4220
4221     if (Op1->hasOneUse() &&
4222         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4223       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4224         cast<BinaryOperator>(Op1)->swapOperands();
4225         std::swap(A, B);
4226       }
4227       if (A == Op0)                                // A&(A^B) -> A & ~B
4228         return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
4229     }
4230
4231     // (A&((~A)|B)) -> A&B
4232     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4233         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4234       return BinaryOperator::CreateAnd(A, Op1);
4235     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4236         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4237       return BinaryOperator::CreateAnd(A, Op0);
4238   }
4239   
4240   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4241     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4242     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4243       return R;
4244
4245     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4246       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4247         return Res;
4248   }
4249
4250   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4251   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4252     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4253       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4254         const Type *SrcTy = Op0C->getOperand(0)->getType();
4255         if (SrcTy == Op1C->getOperand(0)->getType() &&
4256             SrcTy->isIntOrIntVector() &&
4257             // Only do this if the casts both really cause code to be generated.
4258             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4259                               I.getType(), TD) &&
4260             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4261                               I.getType(), TD)) {
4262           Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4263                                             Op1C->getOperand(0), I.getName());
4264           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4265         }
4266       }
4267     
4268   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4269   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4270     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4271       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4272           SI0->getOperand(1) == SI1->getOperand(1) &&
4273           (SI0->hasOneUse() || SI1->hasOneUse())) {
4274         Value *NewOp =
4275           Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4276                              SI0->getName());
4277         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4278                                       SI1->getOperand(1));
4279       }
4280   }
4281
4282   // If and'ing two fcmp, try combine them into one.
4283   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4284     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4285       if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4286         return Res;
4287   }
4288
4289   return Changed ? &I : 0;
4290 }
4291
4292 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4293 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4294 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4295 /// the expression came from the corresponding "byte swapped" byte in some other
4296 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4297 /// we know that the expression deposits the low byte of %X into the high byte
4298 /// of the bswap result and that all other bytes are zero.  This expression is
4299 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4300 /// match.
4301 ///
4302 /// This function returns true if the match was unsuccessful and false if so.
4303 /// On entry to the function the "OverallLeftShift" is a signed integer value
4304 /// indicating the number of bytes that the subexpression is later shifted.  For
4305 /// example, if the expression is later right shifted by 16 bits, the
4306 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4307 /// byte of ByteValues is actually being set.
4308 ///
4309 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4310 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4311 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4312 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4313 /// always in the local (OverallLeftShift) coordinate space.
4314 ///
4315 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4316                               SmallVector<Value*, 8> &ByteValues) {
4317   if (Instruction *I = dyn_cast<Instruction>(V)) {
4318     // If this is an or instruction, it may be an inner node of the bswap.
4319     if (I->getOpcode() == Instruction::Or) {
4320       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4321                                ByteValues) ||
4322              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4323                                ByteValues);
4324     }
4325   
4326     // If this is a logical shift by a constant multiple of 8, recurse with
4327     // OverallLeftShift and ByteMask adjusted.
4328     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4329       unsigned ShAmt = 
4330         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4331       // Ensure the shift amount is defined and of a byte value.
4332       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4333         return true;
4334
4335       unsigned ByteShift = ShAmt >> 3;
4336       if (I->getOpcode() == Instruction::Shl) {
4337         // X << 2 -> collect(X, +2)
4338         OverallLeftShift += ByteShift;
4339         ByteMask >>= ByteShift;
4340       } else {
4341         // X >>u 2 -> collect(X, -2)
4342         OverallLeftShift -= ByteShift;
4343         ByteMask <<= ByteShift;
4344         ByteMask &= (~0U >> (32-ByteValues.size()));
4345       }
4346
4347       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4348       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4349
4350       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4351                                ByteValues);
4352     }
4353
4354     // If this is a logical 'and' with a mask that clears bytes, clear the
4355     // corresponding bytes in ByteMask.
4356     if (I->getOpcode() == Instruction::And &&
4357         isa<ConstantInt>(I->getOperand(1))) {
4358       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4359       unsigned NumBytes = ByteValues.size();
4360       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4361       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4362       
4363       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4364         // If this byte is masked out by a later operation, we don't care what
4365         // the and mask is.
4366         if ((ByteMask & (1 << i)) == 0)
4367           continue;
4368         
4369         // If the AndMask is all zeros for this byte, clear the bit.
4370         APInt MaskB = AndMask & Byte;
4371         if (MaskB == 0) {
4372           ByteMask &= ~(1U << i);
4373           continue;
4374         }
4375         
4376         // If the AndMask is not all ones for this byte, it's not a bytezap.
4377         if (MaskB != Byte)
4378           return true;
4379
4380         // Otherwise, this byte is kept.
4381       }
4382
4383       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4384                                ByteValues);
4385     }
4386   }
4387   
4388   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4389   // the input value to the bswap.  Some observations: 1) if more than one byte
4390   // is demanded from this input, then it could not be successfully assembled
4391   // into a byteswap.  At least one of the two bytes would not be aligned with
4392   // their ultimate destination.
4393   if (!isPowerOf2_32(ByteMask)) return true;
4394   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4395   
4396   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4397   // is demanded, it needs to go into byte 0 of the result.  This means that the
4398   // byte needs to be shifted until it lands in the right byte bucket.  The
4399   // shift amount depends on the position: if the byte is coming from the high
4400   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4401   // low part, it must be shifted left.
4402   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4403   if (InputByteNo < ByteValues.size()/2) {
4404     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4405       return true;
4406   } else {
4407     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4408       return true;
4409   }
4410   
4411   // If the destination byte value is already defined, the values are or'd
4412   // together, which isn't a bswap (unless it's an or of the same bits).
4413   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4414     return true;
4415   ByteValues[DestByteNo] = V;
4416   return false;
4417 }
4418
4419 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4420 /// If so, insert the new bswap intrinsic and return it.
4421 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4422   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4423   if (!ITy || ITy->getBitWidth() % 16 || 
4424       // ByteMask only allows up to 32-byte values.
4425       ITy->getBitWidth() > 32*8) 
4426     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4427   
4428   /// ByteValues - For each byte of the result, we keep track of which value
4429   /// defines each byte.
4430   SmallVector<Value*, 8> ByteValues;
4431   ByteValues.resize(ITy->getBitWidth()/8);
4432     
4433   // Try to find all the pieces corresponding to the bswap.
4434   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4435   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4436     return 0;
4437   
4438   // Check to see if all of the bytes come from the same value.
4439   Value *V = ByteValues[0];
4440   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4441   
4442   // Check to make sure that all of the bytes come from the same value.
4443   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4444     if (ByteValues[i] != V)
4445       return 0;
4446   const Type *Tys[] = { ITy };
4447   Module *M = I.getParent()->getParent()->getParent();
4448   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4449   return CallInst::Create(F, V);
4450 }
4451
4452 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4453 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4454 /// we can simplify this expression to "cond ? C : D or B".
4455 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4456                                          Value *C, Value *D,
4457                                          LLVMContext *Context) {
4458   // If A is not a select of -1/0, this cannot match.
4459   Value *Cond = 0;
4460   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4461     return 0;
4462
4463   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4464   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4465     return SelectInst::Create(Cond, C, B);
4466   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4467     return SelectInst::Create(Cond, C, B);
4468   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4469   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4470     return SelectInst::Create(Cond, C, D);
4471   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4472     return SelectInst::Create(Cond, C, D);
4473   return 0;
4474 }
4475
4476 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4477 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4478                                          ICmpInst *LHS, ICmpInst *RHS) {
4479   Value *Val, *Val2;
4480   ConstantInt *LHSCst, *RHSCst;
4481   ICmpInst::Predicate LHSCC, RHSCC;
4482   
4483   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4484   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4485              m_ConstantInt(LHSCst))) ||
4486       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4487              m_ConstantInt(RHSCst))))
4488     return 0;
4489   
4490   // From here on, we only handle:
4491   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4492   if (Val != Val2) return 0;
4493   
4494   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4495   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4496       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4497       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4498       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4499     return 0;
4500   
4501   // We can't fold (ugt x, C) | (sgt x, C2).
4502   if (!PredicatesFoldable(LHSCC, RHSCC))
4503     return 0;
4504   
4505   // Ensure that the larger constant is on the RHS.
4506   bool ShouldSwap;
4507   if (ICmpInst::isSignedPredicate(LHSCC) ||
4508       (ICmpInst::isEquality(LHSCC) && 
4509        ICmpInst::isSignedPredicate(RHSCC)))
4510     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4511   else
4512     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4513   
4514   if (ShouldSwap) {
4515     std::swap(LHS, RHS);
4516     std::swap(LHSCst, RHSCst);
4517     std::swap(LHSCC, RHSCC);
4518   }
4519   
4520   // At this point, we know we have have two icmp instructions
4521   // comparing a value against two constants and or'ing the result
4522   // together.  Because of the above check, we know that we only have
4523   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4524   // FoldICmpLogical check above), that the two constants are not
4525   // equal.
4526   assert(LHSCst != RHSCst && "Compares not folded above?");
4527
4528   switch (LHSCC) {
4529   default: llvm_unreachable("Unknown integer condition code!");
4530   case ICmpInst::ICMP_EQ:
4531     switch (RHSCC) {
4532     default: llvm_unreachable("Unknown integer condition code!");
4533     case ICmpInst::ICMP_EQ:
4534       if (LHSCst == SubOne(RHSCst)) {
4535         // (X == 13 | X == 14) -> X-13 <u 2
4536         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4537         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4538         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4539         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4540       }
4541       break;                         // (X == 13 | X == 15) -> no change
4542     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4543     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4544       break;
4545     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4546     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4547     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4548       return ReplaceInstUsesWith(I, RHS);
4549     }
4550     break;
4551   case ICmpInst::ICMP_NE:
4552     switch (RHSCC) {
4553     default: llvm_unreachable("Unknown integer condition code!");
4554     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4555     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4556     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4557       return ReplaceInstUsesWith(I, LHS);
4558     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4559     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4560     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4561       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4562     }
4563     break;
4564   case ICmpInst::ICMP_ULT:
4565     switch (RHSCC) {
4566     default: llvm_unreachable("Unknown integer condition code!");
4567     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4568       break;
4569     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4570       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4571       // this can cause overflow.
4572       if (RHSCst->isMaxValue(false))
4573         return ReplaceInstUsesWith(I, LHS);
4574       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4575                              false, false, I);
4576     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4577       break;
4578     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4579     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4580       return ReplaceInstUsesWith(I, RHS);
4581     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4582       break;
4583     }
4584     break;
4585   case ICmpInst::ICMP_SLT:
4586     switch (RHSCC) {
4587     default: llvm_unreachable("Unknown integer condition code!");
4588     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4589       break;
4590     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4591       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4592       // this can cause overflow.
4593       if (RHSCst->isMaxValue(true))
4594         return ReplaceInstUsesWith(I, LHS);
4595       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4596                              true, false, I);
4597     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4598       break;
4599     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4600     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4601       return ReplaceInstUsesWith(I, RHS);
4602     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4603       break;
4604     }
4605     break;
4606   case ICmpInst::ICMP_UGT:
4607     switch (RHSCC) {
4608     default: llvm_unreachable("Unknown integer condition code!");
4609     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4610     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4611       return ReplaceInstUsesWith(I, LHS);
4612     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4613       break;
4614     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4615     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4616       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4617     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4618       break;
4619     }
4620     break;
4621   case ICmpInst::ICMP_SGT:
4622     switch (RHSCC) {
4623     default: llvm_unreachable("Unknown integer condition code!");
4624     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4625     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4626       return ReplaceInstUsesWith(I, LHS);
4627     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4628       break;
4629     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4630     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4631       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4632     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4633       break;
4634     }
4635     break;
4636   }
4637   return 0;
4638 }
4639
4640 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4641                                          FCmpInst *RHS) {
4642   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4643       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4644       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4645     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4646       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4647         // If either of the constants are nans, then the whole thing returns
4648         // true.
4649         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4650           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4651         
4652         // Otherwise, no need to compare the two constants, compare the
4653         // rest.
4654         return new FCmpInst(FCmpInst::FCMP_UNO,
4655                             LHS->getOperand(0), RHS->getOperand(0));
4656       }
4657     
4658     // Handle vector zeros.  This occurs because the canonical form of
4659     // "fcmp uno x,x" is "fcmp uno x, 0".
4660     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4661         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4662       return new FCmpInst(FCmpInst::FCMP_UNO,
4663                           LHS->getOperand(0), RHS->getOperand(0));
4664     
4665     return 0;
4666   }
4667   
4668   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4669   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4670   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4671   
4672   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4673     // Swap RHS operands to match LHS.
4674     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4675     std::swap(Op1LHS, Op1RHS);
4676   }
4677   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4678     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4679     if (Op0CC == Op1CC)
4680       return new FCmpInst((FCmpInst::Predicate)Op0CC,
4681                           Op0LHS, Op0RHS);
4682     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4683       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4684     if (Op0CC == FCmpInst::FCMP_FALSE)
4685       return ReplaceInstUsesWith(I, RHS);
4686     if (Op1CC == FCmpInst::FCMP_FALSE)
4687       return ReplaceInstUsesWith(I, LHS);
4688     bool Op0Ordered;
4689     bool Op1Ordered;
4690     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4691     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4692     if (Op0Ordered == Op1Ordered) {
4693       // If both are ordered or unordered, return a new fcmp with
4694       // or'ed predicates.
4695       Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4696                                Op0LHS, Op0RHS, Context);
4697       if (Instruction *I = dyn_cast<Instruction>(RV))
4698         return I;
4699       // Otherwise, it's a constant boolean value...
4700       return ReplaceInstUsesWith(I, RV);
4701     }
4702   }
4703   return 0;
4704 }
4705
4706 /// FoldOrWithConstants - This helper function folds:
4707 ///
4708 ///     ((A | B) & C1) | (B & C2)
4709 ///
4710 /// into:
4711 /// 
4712 ///     (A & C1) | B
4713 ///
4714 /// when the XOR of the two constants is "all ones" (-1).
4715 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4716                                                Value *A, Value *B, Value *C) {
4717   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4718   if (!CI1) return 0;
4719
4720   Value *V1 = 0;
4721   ConstantInt *CI2 = 0;
4722   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4723
4724   APInt Xor = CI1->getValue() ^ CI2->getValue();
4725   if (!Xor.isAllOnesValue()) return 0;
4726
4727   if (V1 == A || V1 == B) {
4728     Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
4729     return BinaryOperator::CreateOr(NewOp, V1);
4730   }
4731
4732   return 0;
4733 }
4734
4735 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4736   bool Changed = SimplifyCommutative(I);
4737   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4738
4739   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4740     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4741
4742   // or X, X = X
4743   if (Op0 == Op1)
4744     return ReplaceInstUsesWith(I, Op0);
4745
4746   // See if we can simplify any instructions used by the instruction whose sole 
4747   // purpose is to compute bits we don't care about.
4748   if (SimplifyDemandedInstructionBits(I))
4749     return &I;
4750   if (isa<VectorType>(I.getType())) {
4751     if (isa<ConstantAggregateZero>(Op1)) {
4752       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4753     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4754       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4755         return ReplaceInstUsesWith(I, I.getOperand(1));
4756     }
4757   }
4758
4759   // or X, -1 == -1
4760   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4761     ConstantInt *C1 = 0; Value *X = 0;
4762     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4763     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
4764         isOnlyUse(Op0)) {
4765       Value *Or = Builder->CreateOr(X, RHS);
4766       Or->takeName(Op0);
4767       return BinaryOperator::CreateAnd(Or, 
4768                ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
4769     }
4770
4771     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4772     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
4773         isOnlyUse(Op0)) {
4774       Value *Or = Builder->CreateOr(X, RHS);
4775       Or->takeName(Op0);
4776       return BinaryOperator::CreateXor(Or,
4777                  ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
4778     }
4779
4780     // Try to fold constant and into select arguments.
4781     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4782       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4783         return R;
4784     if (isa<PHINode>(Op0))
4785       if (Instruction *NV = FoldOpIntoPhi(I))
4786         return NV;
4787   }
4788
4789   Value *A = 0, *B = 0;
4790   ConstantInt *C1 = 0, *C2 = 0;
4791
4792   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4793     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4794       return ReplaceInstUsesWith(I, Op1);
4795   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4796     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4797       return ReplaceInstUsesWith(I, Op0);
4798
4799   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4800   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4801   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4802       match(Op1, m_Or(m_Value(), m_Value())) ||
4803       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4804        match(Op1, m_Shift(m_Value(), m_Value())))) {
4805     if (Instruction *BSwap = MatchBSwap(I))
4806       return BSwap;
4807   }
4808   
4809   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4810   if (Op0->hasOneUse() &&
4811       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4812       MaskedValueIsZero(Op1, C1->getValue())) {
4813     Value *NOr = Builder->CreateOr(A, Op1);
4814     NOr->takeName(Op0);
4815     return BinaryOperator::CreateXor(NOr, C1);
4816   }
4817
4818   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4819   if (Op1->hasOneUse() &&
4820       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4821       MaskedValueIsZero(Op0, C1->getValue())) {
4822     Value *NOr = Builder->CreateOr(A, Op0);
4823     NOr->takeName(Op0);
4824     return BinaryOperator::CreateXor(NOr, C1);
4825   }
4826
4827   // (A & C)|(B & D)
4828   Value *C = 0, *D = 0;
4829   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4830       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4831     Value *V1 = 0, *V2 = 0, *V3 = 0;
4832     C1 = dyn_cast<ConstantInt>(C);
4833     C2 = dyn_cast<ConstantInt>(D);
4834     if (C1 && C2) {  // (A & C1)|(B & C2)
4835       // If we have: ((V + N) & C1) | (V & C2)
4836       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4837       // replace with V+N.
4838       if (C1->getValue() == ~C2->getValue()) {
4839         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4840             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4841           // Add commutes, try both ways.
4842           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4843             return ReplaceInstUsesWith(I, A);
4844           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4845             return ReplaceInstUsesWith(I, A);
4846         }
4847         // Or commutes, try both ways.
4848         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4849             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4850           // Add commutes, try both ways.
4851           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4852             return ReplaceInstUsesWith(I, B);
4853           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4854             return ReplaceInstUsesWith(I, B);
4855         }
4856       }
4857       V1 = 0; V2 = 0; V3 = 0;
4858     }
4859     
4860     // Check to see if we have any common things being and'ed.  If so, find the
4861     // terms for V1 & (V2|V3).
4862     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4863       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4864         V1 = A, V2 = C, V3 = D;
4865       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4866         V1 = A, V2 = B, V3 = C;
4867       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4868         V1 = C, V2 = A, V3 = D;
4869       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4870         V1 = C, V2 = A, V3 = B;
4871       
4872       if (V1) {
4873         Value *Or = Builder->CreateOr(V2, V3, "tmp");
4874         return BinaryOperator::CreateAnd(V1, Or);
4875       }
4876     }
4877
4878     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4879     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4880       return Match;
4881     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4882       return Match;
4883     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4884       return Match;
4885     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4886       return Match;
4887
4888     // ((A&~B)|(~A&B)) -> A^B
4889     if ((match(C, m_Not(m_Specific(D))) &&
4890          match(B, m_Not(m_Specific(A)))))
4891       return BinaryOperator::CreateXor(A, D);
4892     // ((~B&A)|(~A&B)) -> A^B
4893     if ((match(A, m_Not(m_Specific(D))) &&
4894          match(B, m_Not(m_Specific(C)))))
4895       return BinaryOperator::CreateXor(C, D);
4896     // ((A&~B)|(B&~A)) -> A^B
4897     if ((match(C, m_Not(m_Specific(B))) &&
4898          match(D, m_Not(m_Specific(A)))))
4899       return BinaryOperator::CreateXor(A, B);
4900     // ((~B&A)|(B&~A)) -> A^B
4901     if ((match(A, m_Not(m_Specific(B))) &&
4902          match(D, m_Not(m_Specific(C)))))
4903       return BinaryOperator::CreateXor(C, B);
4904   }
4905   
4906   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4907   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4908     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4909       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4910           SI0->getOperand(1) == SI1->getOperand(1) &&
4911           (SI0->hasOneUse() || SI1->hasOneUse())) {
4912         Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4913                                          SI0->getName());
4914         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4915                                       SI1->getOperand(1));
4916       }
4917   }
4918
4919   // ((A|B)&1)|(B&-2) -> (A&1) | B
4920   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4921       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4922     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4923     if (Ret) return Ret;
4924   }
4925   // (B&-2)|((A|B)&1) -> (A&1) | B
4926   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4927       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4928     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4929     if (Ret) return Ret;
4930   }
4931
4932   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4933     if (A == Op1)   // ~A | A == -1
4934       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4935   } else {
4936     A = 0;
4937   }
4938   // Note, A is still live here!
4939   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4940     if (Op0 == B)
4941       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4942
4943     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4944     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4945       Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
4946       return BinaryOperator::CreateNot(And);
4947     }
4948   }
4949
4950   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4951   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4952     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4953       return R;
4954
4955     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4956       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4957         return Res;
4958   }
4959     
4960   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4961   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4962     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4963       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4964         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4965             !isa<ICmpInst>(Op1C->getOperand(0))) {
4966           const Type *SrcTy = Op0C->getOperand(0)->getType();
4967           if (SrcTy == Op1C->getOperand(0)->getType() &&
4968               SrcTy->isIntOrIntVector() &&
4969               // Only do this if the casts both really cause code to be
4970               // generated.
4971               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4972                                 I.getType(), TD) &&
4973               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4974                                 I.getType(), TD)) {
4975             Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
4976                                              Op1C->getOperand(0), I.getName());
4977             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4978           }
4979         }
4980       }
4981   }
4982   
4983     
4984   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4985   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4986     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4987       if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4988         return Res;
4989   }
4990
4991   return Changed ? &I : 0;
4992 }
4993
4994 namespace {
4995
4996 // XorSelf - Implements: X ^ X --> 0
4997 struct XorSelf {
4998   Value *RHS;
4999   XorSelf(Value *rhs) : RHS(rhs) {}
5000   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5001   Instruction *apply(BinaryOperator &Xor) const {
5002     return &Xor;
5003   }
5004 };
5005
5006 }
5007
5008 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5009   bool Changed = SimplifyCommutative(I);
5010   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5011
5012   if (isa<UndefValue>(Op1)) {
5013     if (isa<UndefValue>(Op0))
5014       // Handle undef ^ undef -> 0 special case. This is a common
5015       // idiom (misuse).
5016       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5017     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5018   }
5019
5020   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5021   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
5022     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5023     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5024   }
5025   
5026   // See if we can simplify any instructions used by the instruction whose sole 
5027   // purpose is to compute bits we don't care about.
5028   if (SimplifyDemandedInstructionBits(I))
5029     return &I;
5030   if (isa<VectorType>(I.getType()))
5031     if (isa<ConstantAggregateZero>(Op1))
5032       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5033
5034   // Is this a ~ operation?
5035   if (Value *NotOp = dyn_castNotVal(&I)) {
5036     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5037     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5038     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5039       if (Op0I->getOpcode() == Instruction::And || 
5040           Op0I->getOpcode() == Instruction::Or) {
5041         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5042         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5043           Value *NotY =
5044             Builder->CreateNot(Op0I->getOperand(1),
5045                                Op0I->getOperand(1)->getName()+".not");
5046           if (Op0I->getOpcode() == Instruction::And)
5047             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5048           return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5049         }
5050       }
5051     }
5052   }
5053   
5054   
5055   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5056     if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
5057       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5058       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5059         return new ICmpInst(ICI->getInversePredicate(),
5060                             ICI->getOperand(0), ICI->getOperand(1));
5061
5062       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5063         return new FCmpInst(FCI->getInversePredicate(),
5064                             FCI->getOperand(0), FCI->getOperand(1));
5065     }
5066
5067     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5068     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5069       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5070         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5071           Instruction::CastOps Opcode = Op0C->getOpcode();
5072           if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5073               (RHS == ConstantExpr::getCast(Opcode, 
5074                                             ConstantInt::getTrue(*Context),
5075                                             Op0C->getDestTy()))) {
5076             CI->setPredicate(CI->getInversePredicate());
5077             return CastInst::Create(Opcode, CI, Op0C->getType());
5078           }
5079         }
5080       }
5081     }
5082
5083     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5084       // ~(c-X) == X-c-1 == X+(-c-1)
5085       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5086         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5087           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5088           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5089                                       ConstantInt::get(I.getType(), 1));
5090           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5091         }
5092           
5093       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5094         if (Op0I->getOpcode() == Instruction::Add) {
5095           // ~(X-c) --> (-c-1)-X
5096           if (RHS->isAllOnesValue()) {
5097             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5098             return BinaryOperator::CreateSub(
5099                            ConstantExpr::getSub(NegOp0CI,
5100                                       ConstantInt::get(I.getType(), 1)),
5101                                       Op0I->getOperand(0));
5102           } else if (RHS->getValue().isSignBit()) {
5103             // (X + C) ^ signbit -> (X + C + signbit)
5104             Constant *C = ConstantInt::get(*Context,
5105                                            RHS->getValue() + Op0CI->getValue());
5106             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5107
5108           }
5109         } else if (Op0I->getOpcode() == Instruction::Or) {
5110           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5111           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5112             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5113             // Anything in both C1 and C2 is known to be zero, remove it from
5114             // NewRHS.
5115             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5116             NewRHS = ConstantExpr::getAnd(NewRHS, 
5117                                        ConstantExpr::getNot(CommonBits));
5118             Worklist.Add(Op0I);
5119             I.setOperand(0, Op0I->getOperand(0));
5120             I.setOperand(1, NewRHS);
5121             return &I;
5122           }
5123         }
5124       }
5125     }
5126
5127     // Try to fold constant and into select arguments.
5128     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5129       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5130         return R;
5131     if (isa<PHINode>(Op0))
5132       if (Instruction *NV = FoldOpIntoPhi(I))
5133         return NV;
5134   }
5135
5136   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5137     if (X == Op1)
5138       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5139
5140   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5141     if (X == Op0)
5142       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5143
5144   
5145   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5146   if (Op1I) {
5147     Value *A, *B;
5148     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5149       if (A == Op0) {              // B^(B|A) == (A|B)^B
5150         Op1I->swapOperands();
5151         I.swapOperands();
5152         std::swap(Op0, Op1);
5153       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5154         I.swapOperands();     // Simplified below.
5155         std::swap(Op0, Op1);
5156       }
5157     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5158       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5159     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5160       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5161     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && 
5162                Op1I->hasOneUse()){
5163       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5164         Op1I->swapOperands();
5165         std::swap(A, B);
5166       }
5167       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5168         I.swapOperands();     // Simplified below.
5169         std::swap(Op0, Op1);
5170       }
5171     }
5172   }
5173   
5174   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5175   if (Op0I) {
5176     Value *A, *B;
5177     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5178         Op0I->hasOneUse()) {
5179       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5180         std::swap(A, B);
5181       if (B == Op1)                                  // (A|B)^B == A & ~B
5182         return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
5183     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5184       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5185     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5186       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5187     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && 
5188                Op0I->hasOneUse()){
5189       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5190         std::swap(A, B);
5191       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5192           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5193         return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
5194       }
5195     }
5196   }
5197   
5198   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5199   if (Op0I && Op1I && Op0I->isShift() && 
5200       Op0I->getOpcode() == Op1I->getOpcode() && 
5201       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5202       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5203     Value *NewOp =
5204       Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5205                          Op0I->getName());
5206     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5207                                   Op1I->getOperand(1));
5208   }
5209     
5210   if (Op0I && Op1I) {
5211     Value *A, *B, *C, *D;
5212     // (A & B)^(A | B) -> A ^ B
5213     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5214         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5215       if ((A == C && B == D) || (A == D && B == C)) 
5216         return BinaryOperator::CreateXor(A, B);
5217     }
5218     // (A | B)^(A & B) -> A ^ B
5219     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5220         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5221       if ((A == C && B == D) || (A == D && B == C)) 
5222         return BinaryOperator::CreateXor(A, B);
5223     }
5224     
5225     // (A & B)^(C & D)
5226     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5227         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5228         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5229       // (X & Y)^(X & Y) -> (Y^Z) & X
5230       Value *X = 0, *Y = 0, *Z = 0;
5231       if (A == C)
5232         X = A, Y = B, Z = D;
5233       else if (A == D)
5234         X = A, Y = B, Z = C;
5235       else if (B == C)
5236         X = B, Y = A, Z = D;
5237       else if (B == D)
5238         X = B, Y = A, Z = C;
5239       
5240       if (X) {
5241         Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
5242         return BinaryOperator::CreateAnd(NewOp, X);
5243       }
5244     }
5245   }
5246     
5247   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5248   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5249     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5250       return R;
5251
5252   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5253   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5254     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5255       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5256         const Type *SrcTy = Op0C->getOperand(0)->getType();
5257         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5258             // Only do this if the casts both really cause code to be generated.
5259             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5260                               I.getType(), TD) &&
5261             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5262                               I.getType(), TD)) {
5263           Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5264                                             Op1C->getOperand(0), I.getName());
5265           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5266         }
5267       }
5268   }
5269
5270   return Changed ? &I : 0;
5271 }
5272
5273 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5274                                    LLVMContext *Context) {
5275   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5276 }
5277
5278 static bool HasAddOverflow(ConstantInt *Result,
5279                            ConstantInt *In1, ConstantInt *In2,
5280                            bool IsSigned) {
5281   if (IsSigned)
5282     if (In2->getValue().isNegative())
5283       return Result->getValue().sgt(In1->getValue());
5284     else
5285       return Result->getValue().slt(In1->getValue());
5286   else
5287     return Result->getValue().ult(In1->getValue());
5288 }
5289
5290 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5291 /// overflowed for this type.
5292 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5293                             Constant *In2, LLVMContext *Context,
5294                             bool IsSigned = false) {
5295   Result = ConstantExpr::getAdd(In1, In2);
5296
5297   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5298     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5299       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5300       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5301                          ExtractElement(In1, Idx, Context),
5302                          ExtractElement(In2, Idx, Context),
5303                          IsSigned))
5304         return true;
5305     }
5306     return false;
5307   }
5308
5309   return HasAddOverflow(cast<ConstantInt>(Result),
5310                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5311                         IsSigned);
5312 }
5313
5314 static bool HasSubOverflow(ConstantInt *Result,
5315                            ConstantInt *In1, ConstantInt *In2,
5316                            bool IsSigned) {
5317   if (IsSigned)
5318     if (In2->getValue().isNegative())
5319       return Result->getValue().slt(In1->getValue());
5320     else
5321       return Result->getValue().sgt(In1->getValue());
5322   else
5323     return Result->getValue().ugt(In1->getValue());
5324 }
5325
5326 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5327 /// overflowed for this type.
5328 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5329                             Constant *In2, LLVMContext *Context,
5330                             bool IsSigned = false) {
5331   Result = ConstantExpr::getSub(In1, In2);
5332
5333   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5334     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5335       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5336       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5337                          ExtractElement(In1, Idx, Context),
5338                          ExtractElement(In2, Idx, Context),
5339                          IsSigned))
5340         return true;
5341     }
5342     return false;
5343   }
5344
5345   return HasSubOverflow(cast<ConstantInt>(Result),
5346                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5347                         IsSigned);
5348 }
5349
5350 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5351 /// code necessary to compute the offset from the base pointer (without adding
5352 /// in the base pointer).  Return the result as a signed integer of intptr size.
5353 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5354   TargetData &TD = *IC.getTargetData();
5355   gep_type_iterator GTI = gep_type_begin(GEP);
5356   const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
5357   Value *Result = Constant::getNullValue(IntPtrTy);
5358
5359   // Build a mask for high order bits.
5360   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5361   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5362
5363   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5364        ++i, ++GTI) {
5365     Value *Op = *i;
5366     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5367     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5368       if (OpC->isZero()) continue;
5369       
5370       // Handle a struct index, which adds its field offset to the pointer.
5371       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5372         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5373         
5374         Result = IC.Builder->CreateAdd(Result,
5375                                        ConstantInt::get(IntPtrTy, Size),
5376                                        GEP->getName()+".offs");
5377         continue;
5378       }
5379       
5380       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5381       Constant *OC =
5382               ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5383       Scale = ConstantExpr::getMul(OC, Scale);
5384       // Emit an add instruction.
5385       Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
5386       continue;
5387     }
5388     // Convert to correct type.
5389     if (Op->getType() != IntPtrTy)
5390       Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
5391     if (Size != 1) {
5392       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5393       // We'll let instcombine(mul) convert this to a shl if possible.
5394       Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
5395     }
5396
5397     // Emit an add instruction.
5398     Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
5399   }
5400   return Result;
5401 }
5402
5403
5404 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5405 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
5406 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
5407 /// be complex, and scales are involved.  The above expression would also be
5408 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5409 /// This later form is less amenable to optimization though, and we are allowed
5410 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5411 ///
5412 /// If we can't emit an optimized form for this expression, this returns null.
5413 /// 
5414 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5415                                           InstCombiner &IC) {
5416   TargetData &TD = *IC.getTargetData();
5417   gep_type_iterator GTI = gep_type_begin(GEP);
5418
5419   // Check to see if this gep only has a single variable index.  If so, and if
5420   // any constant indices are a multiple of its scale, then we can compute this
5421   // in terms of the scale of the variable index.  For example, if the GEP
5422   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5423   // because the expression will cross zero at the same point.
5424   unsigned i, e = GEP->getNumOperands();
5425   int64_t Offset = 0;
5426   for (i = 1; i != e; ++i, ++GTI) {
5427     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5428       // Compute the aggregate offset of constant indices.
5429       if (CI->isZero()) continue;
5430
5431       // Handle a struct index, which adds its field offset to the pointer.
5432       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5433         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5434       } else {
5435         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5436         Offset += Size*CI->getSExtValue();
5437       }
5438     } else {
5439       // Found our variable index.
5440       break;
5441     }
5442   }
5443   
5444   // If there are no variable indices, we must have a constant offset, just
5445   // evaluate it the general way.
5446   if (i == e) return 0;
5447   
5448   Value *VariableIdx = GEP->getOperand(i);
5449   // Determine the scale factor of the variable element.  For example, this is
5450   // 4 if the variable index is into an array of i32.
5451   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5452   
5453   // Verify that there are no other variable indices.  If so, emit the hard way.
5454   for (++i, ++GTI; i != e; ++i, ++GTI) {
5455     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5456     if (!CI) return 0;
5457    
5458     // Compute the aggregate offset of constant indices.
5459     if (CI->isZero()) continue;
5460     
5461     // Handle a struct index, which adds its field offset to the pointer.
5462     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5463       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5464     } else {
5465       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5466       Offset += Size*CI->getSExtValue();
5467     }
5468   }
5469   
5470   // Okay, we know we have a single variable index, which must be a
5471   // pointer/array/vector index.  If there is no offset, life is simple, return
5472   // the index.
5473   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5474   if (Offset == 0) {
5475     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5476     // we don't need to bother extending: the extension won't affect where the
5477     // computation crosses zero.
5478     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5479       VariableIdx = new TruncInst(VariableIdx, 
5480                                   TD.getIntPtrType(VariableIdx->getContext()),
5481                                   VariableIdx->getName(), &I);
5482     return VariableIdx;
5483   }
5484   
5485   // Otherwise, there is an index.  The computation we will do will be modulo
5486   // the pointer size, so get it.
5487   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5488   
5489   Offset &= PtrSizeMask;
5490   VariableScale &= PtrSizeMask;
5491
5492   // To do this transformation, any constant index must be a multiple of the
5493   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5494   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5495   // multiple of the variable scale.
5496   int64_t NewOffs = Offset / (int64_t)VariableScale;
5497   if (Offset != NewOffs*(int64_t)VariableScale)
5498     return 0;
5499
5500   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5501   const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
5502   if (VariableIdx->getType() != IntPtrTy)
5503     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5504                                               true /*SExt*/, 
5505                                               VariableIdx->getName(), &I);
5506   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5507   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5508 }
5509
5510
5511 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5512 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5513 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5514                                        ICmpInst::Predicate Cond,
5515                                        Instruction &I) {
5516   // Look through bitcasts.
5517   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5518     RHS = BCI->getOperand(0);
5519
5520   Value *PtrBase = GEPLHS->getOperand(0);
5521   if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5522     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5523     // This transformation (ignoring the base and scales) is valid because we
5524     // know pointers can't overflow since the gep is inbounds.  See if we can
5525     // output an optimized form.
5526     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5527     
5528     // If not, synthesize the offset the hard way.
5529     if (Offset == 0)
5530       Offset = EmitGEPOffset(GEPLHS, I, *this);
5531     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5532                         Constant::getNullValue(Offset->getType()));
5533   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5534     // If the base pointers are different, but the indices are the same, just
5535     // compare the base pointer.
5536     if (PtrBase != GEPRHS->getOperand(0)) {
5537       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5538       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5539                         GEPRHS->getOperand(0)->getType();
5540       if (IndicesTheSame)
5541         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5542           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5543             IndicesTheSame = false;
5544             break;
5545           }
5546
5547       // If all indices are the same, just compare the base pointers.
5548       if (IndicesTheSame)
5549         return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5550                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5551
5552       // Otherwise, the base pointers are different and the indices are
5553       // different, bail out.
5554       return 0;
5555     }
5556
5557     // If one of the GEPs has all zero indices, recurse.
5558     bool AllZeros = true;
5559     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5560       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5561           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5562         AllZeros = false;
5563         break;
5564       }
5565     if (AllZeros)
5566       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5567                           ICmpInst::getSwappedPredicate(Cond), I);
5568
5569     // If the other GEP has all zero indices, recurse.
5570     AllZeros = true;
5571     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5572       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5573           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5574         AllZeros = false;
5575         break;
5576       }
5577     if (AllZeros)
5578       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5579
5580     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5581       // If the GEPs only differ by one index, compare it.
5582       unsigned NumDifferences = 0;  // Keep track of # differences.
5583       unsigned DiffOperand = 0;     // The operand that differs.
5584       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5585         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5586           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5587                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5588             // Irreconcilable differences.
5589             NumDifferences = 2;
5590             break;
5591           } else {
5592             if (NumDifferences++) break;
5593             DiffOperand = i;
5594           }
5595         }
5596
5597       if (NumDifferences == 0)   // SAME GEP?
5598         return ReplaceInstUsesWith(I, // No comparison is needed here.
5599                                    ConstantInt::get(Type::getInt1Ty(*Context),
5600                                              ICmpInst::isTrueWhenEqual(Cond)));
5601
5602       else if (NumDifferences == 1) {
5603         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5604         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5605         // Make sure we do a signed comparison here.
5606         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5607       }
5608     }
5609
5610     // Only lower this if the icmp is the only user of the GEP or if we expect
5611     // the result to fold to a constant!
5612     if (TD &&
5613         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5614         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5615       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5616       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5617       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5618       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5619     }
5620   }
5621   return 0;
5622 }
5623
5624 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5625 ///
5626 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5627                                                 Instruction *LHSI,
5628                                                 Constant *RHSC) {
5629   if (!isa<ConstantFP>(RHSC)) return 0;
5630   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5631   
5632   // Get the width of the mantissa.  We don't want to hack on conversions that
5633   // might lose information from the integer, e.g. "i64 -> float"
5634   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5635   if (MantissaWidth == -1) return 0;  // Unknown.
5636   
5637   // Check to see that the input is converted from an integer type that is small
5638   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5639   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5640   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5641   
5642   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5643   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5644   if (LHSUnsigned)
5645     ++InputSize;
5646   
5647   // If the conversion would lose info, don't hack on this.
5648   if ((int)InputSize > MantissaWidth)
5649     return 0;
5650   
5651   // Otherwise, we can potentially simplify the comparison.  We know that it
5652   // will always come through as an integer value and we know the constant is
5653   // not a NAN (it would have been previously simplified).
5654   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5655   
5656   ICmpInst::Predicate Pred;
5657   switch (I.getPredicate()) {
5658   default: llvm_unreachable("Unexpected predicate!");
5659   case FCmpInst::FCMP_UEQ:
5660   case FCmpInst::FCMP_OEQ:
5661     Pred = ICmpInst::ICMP_EQ;
5662     break;
5663   case FCmpInst::FCMP_UGT:
5664   case FCmpInst::FCMP_OGT:
5665     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5666     break;
5667   case FCmpInst::FCMP_UGE:
5668   case FCmpInst::FCMP_OGE:
5669     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5670     break;
5671   case FCmpInst::FCMP_ULT:
5672   case FCmpInst::FCMP_OLT:
5673     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5674     break;
5675   case FCmpInst::FCMP_ULE:
5676   case FCmpInst::FCMP_OLE:
5677     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5678     break;
5679   case FCmpInst::FCMP_UNE:
5680   case FCmpInst::FCMP_ONE:
5681     Pred = ICmpInst::ICMP_NE;
5682     break;
5683   case FCmpInst::FCMP_ORD:
5684     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5685   case FCmpInst::FCMP_UNO:
5686     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5687   }
5688   
5689   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5690   
5691   // Now we know that the APFloat is a normal number, zero or inf.
5692   
5693   // See if the FP constant is too large for the integer.  For example,
5694   // comparing an i8 to 300.0.
5695   unsigned IntWidth = IntTy->getScalarSizeInBits();
5696   
5697   if (!LHSUnsigned) {
5698     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5699     // and large values.
5700     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5701     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5702                           APFloat::rmNearestTiesToEven);
5703     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5704       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5705           Pred == ICmpInst::ICMP_SLE)
5706         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5707       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5708     }
5709   } else {
5710     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5711     // +INF and large values.
5712     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5713     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5714                           APFloat::rmNearestTiesToEven);
5715     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5716       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5717           Pred == ICmpInst::ICMP_ULE)
5718         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5719       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5720     }
5721   }
5722   
5723   if (!LHSUnsigned) {
5724     // See if the RHS value is < SignedMin.
5725     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5726     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5727                           APFloat::rmNearestTiesToEven);
5728     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5729       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5730           Pred == ICmpInst::ICMP_SGE)
5731         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5732       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5733     }
5734   }
5735
5736   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5737   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5738   // casting the FP value to the integer value and back, checking for equality.
5739   // Don't do this for zero, because -0.0 is not fractional.
5740   Constant *RHSInt = LHSUnsigned
5741     ? ConstantExpr::getFPToUI(RHSC, IntTy)
5742     : ConstantExpr::getFPToSI(RHSC, IntTy);
5743   if (!RHS.isZero()) {
5744     bool Equal = LHSUnsigned
5745       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5746       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5747     if (!Equal) {
5748       // If we had a comparison against a fractional value, we have to adjust
5749       // the compare predicate and sometimes the value.  RHSC is rounded towards
5750       // zero at this point.
5751       switch (Pred) {
5752       default: llvm_unreachable("Unexpected integer comparison!");
5753       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5754         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5755       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5756         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5757       case ICmpInst::ICMP_ULE:
5758         // (float)int <= 4.4   --> int <= 4
5759         // (float)int <= -4.4  --> false
5760         if (RHS.isNegative())
5761           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5762         break;
5763       case ICmpInst::ICMP_SLE:
5764         // (float)int <= 4.4   --> int <= 4
5765         // (float)int <= -4.4  --> int < -4
5766         if (RHS.isNegative())
5767           Pred = ICmpInst::ICMP_SLT;
5768         break;
5769       case ICmpInst::ICMP_ULT:
5770         // (float)int < -4.4   --> false
5771         // (float)int < 4.4    --> int <= 4
5772         if (RHS.isNegative())
5773           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5774         Pred = ICmpInst::ICMP_ULE;
5775         break;
5776       case ICmpInst::ICMP_SLT:
5777         // (float)int < -4.4   --> int < -4
5778         // (float)int < 4.4    --> int <= 4
5779         if (!RHS.isNegative())
5780           Pred = ICmpInst::ICMP_SLE;
5781         break;
5782       case ICmpInst::ICMP_UGT:
5783         // (float)int > 4.4    --> int > 4
5784         // (float)int > -4.4   --> true
5785         if (RHS.isNegative())
5786           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5787         break;
5788       case ICmpInst::ICMP_SGT:
5789         // (float)int > 4.4    --> int > 4
5790         // (float)int > -4.4   --> int >= -4
5791         if (RHS.isNegative())
5792           Pred = ICmpInst::ICMP_SGE;
5793         break;
5794       case ICmpInst::ICMP_UGE:
5795         // (float)int >= -4.4   --> true
5796         // (float)int >= 4.4    --> int > 4
5797         if (!RHS.isNegative())
5798           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5799         Pred = ICmpInst::ICMP_UGT;
5800         break;
5801       case ICmpInst::ICMP_SGE:
5802         // (float)int >= -4.4   --> int >= -4
5803         // (float)int >= 4.4    --> int > 4
5804         if (!RHS.isNegative())
5805           Pred = ICmpInst::ICMP_SGT;
5806         break;
5807       }
5808     }
5809   }
5810
5811   // Lower this FP comparison into an appropriate integer version of the
5812   // comparison.
5813   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5814 }
5815
5816 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5817   bool Changed = SimplifyCompare(I);
5818   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5819
5820   // Fold trivial predicates.
5821   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5822     return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
5823   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5824     return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
5825   
5826   // Simplify 'fcmp pred X, X'
5827   if (Op0 == Op1) {
5828     switch (I.getPredicate()) {
5829     default: llvm_unreachable("Unknown predicate!");
5830     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5831     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5832     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5833       return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
5834     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5835     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5836     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5837       return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
5838       
5839     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5840     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5841     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5842     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5843       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5844       I.setPredicate(FCmpInst::FCMP_UNO);
5845       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5846       return &I;
5847       
5848     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5849     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5850     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5851     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5852       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5853       I.setPredicate(FCmpInst::FCMP_ORD);
5854       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5855       return &I;
5856     }
5857   }
5858     
5859   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5860     return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
5861
5862   // Handle fcmp with constant RHS
5863   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5864     // If the constant is a nan, see if we can fold the comparison based on it.
5865     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5866       if (CFP->getValueAPF().isNaN()) {
5867         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5868           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5869         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5870                "Comparison must be either ordered or unordered!");
5871         // True if unordered.
5872         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5873       }
5874     }
5875     
5876     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5877       switch (LHSI->getOpcode()) {
5878       case Instruction::PHI:
5879         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5880         // block.  If in the same block, we're encouraging jump threading.  If
5881         // not, we are just pessimizing the code by making an i1 phi.
5882         if (LHSI->getParent() == I.getParent())
5883           if (Instruction *NV = FoldOpIntoPhi(I, true))
5884             return NV;
5885         break;
5886       case Instruction::SIToFP:
5887       case Instruction::UIToFP:
5888         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5889           return NV;
5890         break;
5891       case Instruction::Select:
5892         // If either operand of the select is a constant, we can fold the
5893         // comparison into the select arms, which will cause one to be
5894         // constant folded and the select turned into a bitwise or.
5895         Value *Op1 = 0, *Op2 = 0;
5896         if (LHSI->hasOneUse()) {
5897           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5898             // Fold the known value into the constant operand.
5899             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5900             // Insert a new FCmp of the other select operand.
5901             Op2 = Builder->CreateFCmp(I.getPredicate(),
5902                                       LHSI->getOperand(2), RHSC, I.getName());
5903           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5904             // Fold the known value into the constant operand.
5905             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5906             // Insert a new FCmp of the other select operand.
5907             Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5908                                       RHSC, I.getName());
5909           }
5910         }
5911
5912         if (Op1)
5913           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5914         break;
5915       }
5916   }
5917
5918   return Changed ? &I : 0;
5919 }
5920
5921 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5922   bool Changed = SimplifyCompare(I);
5923   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5924   const Type *Ty = Op0->getType();
5925
5926   // icmp X, X
5927   if (Op0 == Op1)
5928     return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
5929                                                    I.isTrueWhenEqual()));
5930
5931   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5932     return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
5933   
5934   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5935   // addresses never equal each other!  We already know that Op0 != Op1.
5936   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) || isMalloc(Op0) ||
5937        isa<ConstantPointerNull>(Op0)) &&
5938       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) || isMalloc(Op1) ||
5939        isa<ConstantPointerNull>(Op1)))
5940     return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context), 
5941                                                    !I.isTrueWhenEqual()));
5942
5943   // icmp's with boolean values can always be turned into bitwise operations
5944   if (Ty == Type::getInt1Ty(*Context)) {
5945     switch (I.getPredicate()) {
5946     default: llvm_unreachable("Invalid icmp instruction!");
5947     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5948       Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
5949       return BinaryOperator::CreateNot(Xor);
5950     }
5951     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5952       return BinaryOperator::CreateXor(Op0, Op1);
5953
5954     case ICmpInst::ICMP_UGT:
5955       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5956       // FALL THROUGH
5957     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5958       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
5959       return BinaryOperator::CreateAnd(Not, Op1);
5960     }
5961     case ICmpInst::ICMP_SGT:
5962       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5963       // FALL THROUGH
5964     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5965       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
5966       return BinaryOperator::CreateAnd(Not, Op0);
5967     }
5968     case ICmpInst::ICMP_UGE:
5969       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5970       // FALL THROUGH
5971     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5972       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
5973       return BinaryOperator::CreateOr(Not, Op1);
5974     }
5975     case ICmpInst::ICMP_SGE:
5976       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5977       // FALL THROUGH
5978     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5979       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
5980       return BinaryOperator::CreateOr(Not, Op0);
5981     }
5982     }
5983   }
5984
5985   unsigned BitWidth = 0;
5986   if (TD)
5987     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
5988   else if (Ty->isIntOrIntVector())
5989     BitWidth = Ty->getScalarSizeInBits();
5990
5991   bool isSignBit = false;
5992
5993   // See if we are doing a comparison with a constant.
5994   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5995     Value *A = 0, *B = 0;
5996     
5997     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5998     if (I.isEquality() && CI->isNullValue() &&
5999         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
6000       // (icmp cond A B) if cond is equality
6001       return new ICmpInst(I.getPredicate(), A, B);
6002     }
6003     
6004     // If we have an icmp le or icmp ge instruction, turn it into the
6005     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6006     // them being folded in the code below.
6007     switch (I.getPredicate()) {
6008     default: break;
6009     case ICmpInst::ICMP_ULE:
6010       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6011         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6012       return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
6013                           AddOne(CI));
6014     case ICmpInst::ICMP_SLE:
6015       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6016         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6017       return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6018                           AddOne(CI));
6019     case ICmpInst::ICMP_UGE:
6020       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6021         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6022       return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
6023                           SubOne(CI));
6024     case ICmpInst::ICMP_SGE:
6025       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6026         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6027       return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6028                           SubOne(CI));
6029     }
6030     
6031     // If this comparison is a normal comparison, it demands all
6032     // bits, if it is a sign bit comparison, it only demands the sign bit.
6033     bool UnusedBit;
6034     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6035   }
6036
6037   // See if we can fold the comparison based on range information we can get
6038   // by checking whether bits are known to be zero or one in the input.
6039   if (BitWidth != 0) {
6040     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6041     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6042
6043     if (SimplifyDemandedBits(I.getOperandUse(0),
6044                              isSignBit ? APInt::getSignBit(BitWidth)
6045                                        : APInt::getAllOnesValue(BitWidth),
6046                              Op0KnownZero, Op0KnownOne, 0))
6047       return &I;
6048     if (SimplifyDemandedBits(I.getOperandUse(1),
6049                              APInt::getAllOnesValue(BitWidth),
6050                              Op1KnownZero, Op1KnownOne, 0))
6051       return &I;
6052
6053     // Given the known and unknown bits, compute a range that the LHS could be
6054     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6055     // EQ and NE we use unsigned values.
6056     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6057     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6058     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6059       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6060                                              Op0Min, Op0Max);
6061       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6062                                              Op1Min, Op1Max);
6063     } else {
6064       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6065                                                Op0Min, Op0Max);
6066       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6067                                                Op1Min, Op1Max);
6068     }
6069
6070     // If Min and Max are known to be the same, then SimplifyDemandedBits
6071     // figured out that the LHS is a constant.  Just constant fold this now so
6072     // that code below can assume that Min != Max.
6073     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6074       return new ICmpInst(I.getPredicate(),
6075                           ConstantInt::get(*Context, Op0Min), Op1);
6076     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6077       return new ICmpInst(I.getPredicate(), Op0,
6078                           ConstantInt::get(*Context, Op1Min));
6079
6080     // Based on the range information we know about the LHS, see if we can
6081     // simplify this comparison.  For example, (x&4) < 8  is always true.
6082     switch (I.getPredicate()) {
6083     default: llvm_unreachable("Unknown icmp opcode!");
6084     case ICmpInst::ICMP_EQ:
6085       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6086         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6087       break;
6088     case ICmpInst::ICMP_NE:
6089       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6090         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6091       break;
6092     case ICmpInst::ICMP_ULT:
6093       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6094         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6095       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6096         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6097       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6098         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6099       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6100         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6101           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6102                               SubOne(CI));
6103
6104         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6105         if (CI->isMinValue(true))
6106           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6107                            Constant::getAllOnesValue(Op0->getType()));
6108       }
6109       break;
6110     case ICmpInst::ICMP_UGT:
6111       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6112         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6113       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6114         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6115
6116       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6117         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6118       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6119         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6120           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6121                               AddOne(CI));
6122
6123         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6124         if (CI->isMaxValue(true))
6125           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6126                               Constant::getNullValue(Op0->getType()));
6127       }
6128       break;
6129     case ICmpInst::ICMP_SLT:
6130       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6131         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6132       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6133         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6134       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6135         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6136       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6137         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6138           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6139                               SubOne(CI));
6140       }
6141       break;
6142     case ICmpInst::ICMP_SGT:
6143       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6144         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6145       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6146         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6147
6148       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6149         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6150       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6151         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6152           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6153                               AddOne(CI));
6154       }
6155       break;
6156     case ICmpInst::ICMP_SGE:
6157       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6158       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6159         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6160       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6161         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6162       break;
6163     case ICmpInst::ICMP_SLE:
6164       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6165       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6166         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6167       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6168         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6169       break;
6170     case ICmpInst::ICMP_UGE:
6171       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6172       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6173         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6174       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6175         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6176       break;
6177     case ICmpInst::ICMP_ULE:
6178       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6179       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6180         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6181       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6182         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6183       break;
6184     }
6185
6186     // Turn a signed comparison into an unsigned one if both operands
6187     // are known to have the same sign.
6188     if (I.isSignedPredicate() &&
6189         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6190          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6191       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6192   }
6193
6194   // Test if the ICmpInst instruction is used exclusively by a select as
6195   // part of a minimum or maximum operation. If so, refrain from doing
6196   // any other folding. This helps out other analyses which understand
6197   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6198   // and CodeGen. And in this case, at least one of the comparison
6199   // operands has at least one user besides the compare (the select),
6200   // which would often largely negate the benefit of folding anyway.
6201   if (I.hasOneUse())
6202     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6203       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6204           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6205         return 0;
6206
6207   // See if we are doing a comparison between a constant and an instruction that
6208   // can be folded into the comparison.
6209   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6210     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6211     // instruction, see if that instruction also has constants so that the 
6212     // instruction can be folded into the icmp 
6213     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6214       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6215         return Res;
6216   }
6217
6218   // Handle icmp with constant (but not simple integer constant) RHS
6219   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6220     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6221       switch (LHSI->getOpcode()) {
6222       case Instruction::GetElementPtr:
6223         if (RHSC->isNullValue()) {
6224           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6225           bool isAllZeros = true;
6226           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6227             if (!isa<Constant>(LHSI->getOperand(i)) ||
6228                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6229               isAllZeros = false;
6230               break;
6231             }
6232           if (isAllZeros)
6233             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6234                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6235         }
6236         break;
6237
6238       case Instruction::PHI:
6239         // Only fold icmp into the PHI if the phi and icmp are in the same
6240         // block.  If in the same block, we're encouraging jump threading.  If
6241         // not, we are just pessimizing the code by making an i1 phi.
6242         if (LHSI->getParent() == I.getParent())
6243           if (Instruction *NV = FoldOpIntoPhi(I, true))
6244             return NV;
6245         break;
6246       case Instruction::Select: {
6247         // If either operand of the select is a constant, we can fold the
6248         // comparison into the select arms, which will cause one to be
6249         // constant folded and the select turned into a bitwise or.
6250         Value *Op1 = 0, *Op2 = 0;
6251         if (LHSI->hasOneUse()) {
6252           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6253             // Fold the known value into the constant operand.
6254             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6255             // Insert a new ICmp of the other select operand.
6256             Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6257                                       RHSC, I.getName());
6258           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6259             // Fold the known value into the constant operand.
6260             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6261             // Insert a new ICmp of the other select operand.
6262             Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6263                                       RHSC, I.getName());
6264           }
6265         }
6266
6267         if (Op1)
6268           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6269         break;
6270       }
6271       case Instruction::Malloc:
6272         // If we have (malloc != null), and if the malloc has a single use, we
6273         // can assume it is successful and remove the malloc.
6274         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6275           Worklist.Add(LHSI);
6276           return ReplaceInstUsesWith(I,
6277                                      ConstantInt::get(Type::getInt1Ty(*Context),
6278                                                       !I.isTrueWhenEqual()));
6279         }
6280         break;
6281       case Instruction::Call:
6282         // If we have (malloc != null), and if the malloc has a single use, we
6283         // can assume it is successful and remove the malloc.
6284         if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6285             isa<ConstantPointerNull>(RHSC)) {
6286           Worklist.Add(LHSI);
6287           return ReplaceInstUsesWith(I,
6288                                      ConstantInt::get(Type::getInt1Ty(*Context),
6289                                                       !I.isTrueWhenEqual()));
6290         }
6291         break;
6292       }
6293   }
6294
6295   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6296   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6297     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6298       return NI;
6299   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6300     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6301                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6302       return NI;
6303
6304   // Test to see if the operands of the icmp are casted versions of other
6305   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6306   // now.
6307   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6308     if (isa<PointerType>(Op0->getType()) && 
6309         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6310       // We keep moving the cast from the left operand over to the right
6311       // operand, where it can often be eliminated completely.
6312       Op0 = CI->getOperand(0);
6313
6314       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6315       // so eliminate it as well.
6316       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6317         Op1 = CI2->getOperand(0);
6318
6319       // If Op1 is a constant, we can fold the cast into the constant.
6320       if (Op0->getType() != Op1->getType()) {
6321         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6322           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6323         } else {
6324           // Otherwise, cast the RHS right before the icmp
6325           Op1 = Builder->CreateBitCast(Op1, Op0->getType());
6326         }
6327       }
6328       return new ICmpInst(I.getPredicate(), Op0, Op1);
6329     }
6330   }
6331   
6332   if (isa<CastInst>(Op0)) {
6333     // Handle the special case of: icmp (cast bool to X), <cst>
6334     // This comes up when you have code like
6335     //   int X = A < B;
6336     //   if (X) ...
6337     // For generality, we handle any zero-extension of any operand comparison
6338     // with a constant or another cast from the same type.
6339     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6340       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6341         return R;
6342   }
6343   
6344   // See if it's the same type of instruction on the left and right.
6345   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6346     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6347       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6348           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6349         switch (Op0I->getOpcode()) {
6350         default: break;
6351         case Instruction::Add:
6352         case Instruction::Sub:
6353         case Instruction::Xor:
6354           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6355             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6356                                 Op1I->getOperand(0));
6357           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6358           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6359             if (CI->getValue().isSignBit()) {
6360               ICmpInst::Predicate Pred = I.isSignedPredicate()
6361                                              ? I.getUnsignedPredicate()
6362                                              : I.getSignedPredicate();
6363               return new ICmpInst(Pred, Op0I->getOperand(0),
6364                                   Op1I->getOperand(0));
6365             }
6366             
6367             if (CI->getValue().isMaxSignedValue()) {
6368               ICmpInst::Predicate Pred = I.isSignedPredicate()
6369                                              ? I.getUnsignedPredicate()
6370                                              : I.getSignedPredicate();
6371               Pred = I.getSwappedPredicate(Pred);
6372               return new ICmpInst(Pred, Op0I->getOperand(0),
6373                                   Op1I->getOperand(0));
6374             }
6375           }
6376           break;
6377         case Instruction::Mul:
6378           if (!I.isEquality())
6379             break;
6380
6381           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6382             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6383             // Mask = -1 >> count-trailing-zeros(Cst).
6384             if (!CI->isZero() && !CI->isOne()) {
6385               const APInt &AP = CI->getValue();
6386               ConstantInt *Mask = ConstantInt::get(*Context, 
6387                                       APInt::getLowBitsSet(AP.getBitWidth(),
6388                                                            AP.getBitWidth() -
6389                                                       AP.countTrailingZeros()));
6390               Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6391               Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
6392               return new ICmpInst(I.getPredicate(), And1, And2);
6393             }
6394           }
6395           break;
6396         }
6397       }
6398     }
6399   }
6400   
6401   // ~x < ~y --> y < x
6402   { Value *A, *B;
6403     if (match(Op0, m_Not(m_Value(A))) &&
6404         match(Op1, m_Not(m_Value(B))))
6405       return new ICmpInst(I.getPredicate(), B, A);
6406   }
6407   
6408   if (I.isEquality()) {
6409     Value *A, *B, *C, *D;
6410     
6411     // -x == -y --> x == y
6412     if (match(Op0, m_Neg(m_Value(A))) &&
6413         match(Op1, m_Neg(m_Value(B))))
6414       return new ICmpInst(I.getPredicate(), A, B);
6415     
6416     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6417       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6418         Value *OtherVal = A == Op1 ? B : A;
6419         return new ICmpInst(I.getPredicate(), OtherVal,
6420                             Constant::getNullValue(A->getType()));
6421       }
6422
6423       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6424         // A^c1 == C^c2 --> A == C^(c1^c2)
6425         ConstantInt *C1, *C2;
6426         if (match(B, m_ConstantInt(C1)) &&
6427             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6428           Constant *NC = 
6429                    ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6430           Value *Xor = Builder->CreateXor(C, NC, "tmp");
6431           return new ICmpInst(I.getPredicate(), A, Xor);
6432         }
6433         
6434         // A^B == A^D -> B == D
6435         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6436         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6437         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6438         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6439       }
6440     }
6441     
6442     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6443         (A == Op0 || B == Op0)) {
6444       // A == (A^B)  ->  B == 0
6445       Value *OtherVal = A == Op0 ? B : A;
6446       return new ICmpInst(I.getPredicate(), OtherVal,
6447                           Constant::getNullValue(A->getType()));
6448     }
6449
6450     // (A-B) == A  ->  B == 0
6451     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6452       return new ICmpInst(I.getPredicate(), B, 
6453                           Constant::getNullValue(B->getType()));
6454
6455     // A == (A-B)  ->  B == 0
6456     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6457       return new ICmpInst(I.getPredicate(), B,
6458                           Constant::getNullValue(B->getType()));
6459     
6460     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6461     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6462         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6463         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6464       Value *X = 0, *Y = 0, *Z = 0;
6465       
6466       if (A == C) {
6467         X = B; Y = D; Z = A;
6468       } else if (A == D) {
6469         X = B; Y = C; Z = A;
6470       } else if (B == C) {
6471         X = A; Y = D; Z = B;
6472       } else if (B == D) {
6473         X = A; Y = C; Z = B;
6474       }
6475       
6476       if (X) {   // Build (X^Y) & Z
6477         Op1 = Builder->CreateXor(X, Y, "tmp");
6478         Op1 = Builder->CreateAnd(Op1, Z, "tmp");
6479         I.setOperand(0, Op1);
6480         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6481         return &I;
6482       }
6483     }
6484   }
6485   return Changed ? &I : 0;
6486 }
6487
6488
6489 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6490 /// and CmpRHS are both known to be integer constants.
6491 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6492                                           ConstantInt *DivRHS) {
6493   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6494   const APInt &CmpRHSV = CmpRHS->getValue();
6495   
6496   // FIXME: If the operand types don't match the type of the divide 
6497   // then don't attempt this transform. The code below doesn't have the
6498   // logic to deal with a signed divide and an unsigned compare (and
6499   // vice versa). This is because (x /s C1) <s C2  produces different 
6500   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6501   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6502   // work. :(  The if statement below tests that condition and bails 
6503   // if it finds it. 
6504   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6505   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6506     return 0;
6507   if (DivRHS->isZero())
6508     return 0; // The ProdOV computation fails on divide by zero.
6509   if (DivIsSigned && DivRHS->isAllOnesValue())
6510     return 0; // The overflow computation also screws up here
6511   if (DivRHS->isOne())
6512     return 0; // Not worth bothering, and eliminates some funny cases
6513               // with INT_MIN.
6514
6515   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6516   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6517   // C2 (CI). By solving for X we can turn this into a range check 
6518   // instead of computing a divide. 
6519   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6520
6521   // Determine if the product overflows by seeing if the product is
6522   // not equal to the divide. Make sure we do the same kind of divide
6523   // as in the LHS instruction that we're folding. 
6524   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6525                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6526
6527   // Get the ICmp opcode
6528   ICmpInst::Predicate Pred = ICI.getPredicate();
6529
6530   // Figure out the interval that is being checked.  For example, a comparison
6531   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6532   // Compute this interval based on the constants involved and the signedness of
6533   // the compare/divide.  This computes a half-open interval, keeping track of
6534   // whether either value in the interval overflows.  After analysis each
6535   // overflow variable is set to 0 if it's corresponding bound variable is valid
6536   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6537   int LoOverflow = 0, HiOverflow = 0;
6538   Constant *LoBound = 0, *HiBound = 0;
6539   
6540   if (!DivIsSigned) {  // udiv
6541     // e.g. X/5 op 3  --> [15, 20)
6542     LoBound = Prod;
6543     HiOverflow = LoOverflow = ProdOV;
6544     if (!HiOverflow)
6545       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6546   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6547     if (CmpRHSV == 0) {       // (X / pos) op 0
6548       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6549       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6550       HiBound = DivRHS;
6551     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6552       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6553       HiOverflow = LoOverflow = ProdOV;
6554       if (!HiOverflow)
6555         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6556     } else {                       // (X / pos) op neg
6557       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6558       HiBound = AddOne(Prod);
6559       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6560       if (!LoOverflow) {
6561         ConstantInt* DivNeg =
6562                          cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6563         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6564                                      true) ? -1 : 0;
6565        }
6566     }
6567   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6568     if (CmpRHSV == 0) {       // (X / neg) op 0
6569       // e.g. X/-5 op 0  --> [-4, 5)
6570       LoBound = AddOne(DivRHS);
6571       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6572       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6573         HiOverflow = 1;            // [INTMIN+1, overflow)
6574         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6575       }
6576     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6577       // e.g. X/-5 op 3  --> [-19, -14)
6578       HiBound = AddOne(Prod);
6579       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6580       if (!LoOverflow)
6581         LoOverflow = AddWithOverflow(LoBound, HiBound,
6582                                      DivRHS, Context, true) ? -1 : 0;
6583     } else {                       // (X / neg) op neg
6584       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6585       LoOverflow = HiOverflow = ProdOV;
6586       if (!HiOverflow)
6587         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6588     }
6589     
6590     // Dividing by a negative swaps the condition.  LT <-> GT
6591     Pred = ICmpInst::getSwappedPredicate(Pred);
6592   }
6593
6594   Value *X = DivI->getOperand(0);
6595   switch (Pred) {
6596   default: llvm_unreachable("Unhandled icmp opcode!");
6597   case ICmpInst::ICMP_EQ:
6598     if (LoOverflow && HiOverflow)
6599       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6600     else if (HiOverflow)
6601       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6602                           ICmpInst::ICMP_UGE, X, LoBound);
6603     else if (LoOverflow)
6604       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6605                           ICmpInst::ICMP_ULT, X, HiBound);
6606     else
6607       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6608   case ICmpInst::ICMP_NE:
6609     if (LoOverflow && HiOverflow)
6610       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6611     else if (HiOverflow)
6612       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6613                           ICmpInst::ICMP_ULT, X, LoBound);
6614     else if (LoOverflow)
6615       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6616                           ICmpInst::ICMP_UGE, X, HiBound);
6617     else
6618       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6619   case ICmpInst::ICMP_ULT:
6620   case ICmpInst::ICMP_SLT:
6621     if (LoOverflow == +1)   // Low bound is greater than input range.
6622       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6623     if (LoOverflow == -1)   // Low bound is less than input range.
6624       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6625     return new ICmpInst(Pred, X, LoBound);
6626   case ICmpInst::ICMP_UGT:
6627   case ICmpInst::ICMP_SGT:
6628     if (HiOverflow == +1)       // High bound greater than input range.
6629       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6630     else if (HiOverflow == -1)  // High bound less than input range.
6631       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6632     if (Pred == ICmpInst::ICMP_UGT)
6633       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6634     else
6635       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6636   }
6637 }
6638
6639
6640 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6641 ///
6642 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6643                                                           Instruction *LHSI,
6644                                                           ConstantInt *RHS) {
6645   const APInt &RHSV = RHS->getValue();
6646   
6647   switch (LHSI->getOpcode()) {
6648   case Instruction::Trunc:
6649     if (ICI.isEquality() && LHSI->hasOneUse()) {
6650       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6651       // of the high bits truncated out of x are known.
6652       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6653              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6654       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6655       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6656       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6657       
6658       // If all the high bits are known, we can do this xform.
6659       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6660         // Pull in the high bits from known-ones set.
6661         APInt NewRHS(RHS->getValue());
6662         NewRHS.zext(SrcBits);
6663         NewRHS |= KnownOne;
6664         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6665                             ConstantInt::get(*Context, NewRHS));
6666       }
6667     }
6668     break;
6669       
6670   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6671     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6672       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6673       // fold the xor.
6674       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6675           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6676         Value *CompareVal = LHSI->getOperand(0);
6677         
6678         // If the sign bit of the XorCST is not set, there is no change to
6679         // the operation, just stop using the Xor.
6680         if (!XorCST->getValue().isNegative()) {
6681           ICI.setOperand(0, CompareVal);
6682           Worklist.Add(LHSI);
6683           return &ICI;
6684         }
6685         
6686         // Was the old condition true if the operand is positive?
6687         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6688         
6689         // If so, the new one isn't.
6690         isTrueIfPositive ^= true;
6691         
6692         if (isTrueIfPositive)
6693           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
6694                               SubOne(RHS));
6695         else
6696           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
6697                               AddOne(RHS));
6698       }
6699
6700       if (LHSI->hasOneUse()) {
6701         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6702         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6703           const APInt &SignBit = XorCST->getValue();
6704           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6705                                          ? ICI.getUnsignedPredicate()
6706                                          : ICI.getSignedPredicate();
6707           return new ICmpInst(Pred, LHSI->getOperand(0),
6708                               ConstantInt::get(*Context, RHSV ^ SignBit));
6709         }
6710
6711         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6712         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6713           const APInt &NotSignBit = XorCST->getValue();
6714           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6715                                          ? ICI.getUnsignedPredicate()
6716                                          : ICI.getSignedPredicate();
6717           Pred = ICI.getSwappedPredicate(Pred);
6718           return new ICmpInst(Pred, LHSI->getOperand(0),
6719                               ConstantInt::get(*Context, RHSV ^ NotSignBit));
6720         }
6721       }
6722     }
6723     break;
6724   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6725     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6726         LHSI->getOperand(0)->hasOneUse()) {
6727       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6728       
6729       // If the LHS is an AND of a truncating cast, we can widen the
6730       // and/compare to be the input width without changing the value
6731       // produced, eliminating a cast.
6732       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6733         // We can do this transformation if either the AND constant does not
6734         // have its sign bit set or if it is an equality comparison. 
6735         // Extending a relational comparison when we're checking the sign
6736         // bit would not work.
6737         if (Cast->hasOneUse() &&
6738             (ICI.isEquality() ||
6739              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6740           uint32_t BitWidth = 
6741             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6742           APInt NewCST = AndCST->getValue();
6743           NewCST.zext(BitWidth);
6744           APInt NewCI = RHSV;
6745           NewCI.zext(BitWidth);
6746           Value *NewAnd = 
6747             Builder->CreateAnd(Cast->getOperand(0),
6748                            ConstantInt::get(*Context, NewCST), LHSI->getName());
6749           return new ICmpInst(ICI.getPredicate(), NewAnd,
6750                               ConstantInt::get(*Context, NewCI));
6751         }
6752       }
6753       
6754       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6755       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6756       // happens a LOT in code produced by the C front-end, for bitfield
6757       // access.
6758       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6759       if (Shift && !Shift->isShift())
6760         Shift = 0;
6761       
6762       ConstantInt *ShAmt;
6763       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6764       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6765       const Type *AndTy = AndCST->getType();          // Type of the and.
6766       
6767       // We can fold this as long as we can't shift unknown bits
6768       // into the mask.  This can only happen with signed shift
6769       // rights, as they sign-extend.
6770       if (ShAmt) {
6771         bool CanFold = Shift->isLogicalShift();
6772         if (!CanFold) {
6773           // To test for the bad case of the signed shr, see if any
6774           // of the bits shifted in could be tested after the mask.
6775           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6776           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6777           
6778           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6779           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6780                AndCST->getValue()) == 0)
6781             CanFold = true;
6782         }
6783         
6784         if (CanFold) {
6785           Constant *NewCst;
6786           if (Shift->getOpcode() == Instruction::Shl)
6787             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6788           else
6789             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6790           
6791           // Check to see if we are shifting out any of the bits being
6792           // compared.
6793           if (ConstantExpr::get(Shift->getOpcode(),
6794                                        NewCst, ShAmt) != RHS) {
6795             // If we shifted bits out, the fold is not going to work out.
6796             // As a special case, check to see if this means that the
6797             // result is always true or false now.
6798             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6799               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6800             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6801               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6802           } else {
6803             ICI.setOperand(1, NewCst);
6804             Constant *NewAndCST;
6805             if (Shift->getOpcode() == Instruction::Shl)
6806               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6807             else
6808               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6809             LHSI->setOperand(1, NewAndCST);
6810             LHSI->setOperand(0, Shift->getOperand(0));
6811             Worklist.Add(Shift); // Shift is dead.
6812             return &ICI;
6813           }
6814         }
6815       }
6816       
6817       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6818       // preferable because it allows the C<<Y expression to be hoisted out
6819       // of a loop if Y is invariant and X is not.
6820       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6821           ICI.isEquality() && !Shift->isArithmeticShift() &&
6822           !isa<Constant>(Shift->getOperand(0))) {
6823         // Compute C << Y.
6824         Value *NS;
6825         if (Shift->getOpcode() == Instruction::LShr) {
6826           NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
6827         } else {
6828           // Insert a logical shift.
6829           NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
6830         }
6831         
6832         // Compute X & (C << Y).
6833         Value *NewAnd = 
6834           Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6835         
6836         ICI.setOperand(0, NewAnd);
6837         return &ICI;
6838       }
6839     }
6840     break;
6841     
6842   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6843     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6844     if (!ShAmt) break;
6845     
6846     uint32_t TypeBits = RHSV.getBitWidth();
6847     
6848     // Check that the shift amount is in range.  If not, don't perform
6849     // undefined shifts.  When the shift is visited it will be
6850     // simplified.
6851     if (ShAmt->uge(TypeBits))
6852       break;
6853     
6854     if (ICI.isEquality()) {
6855       // If we are comparing against bits always shifted out, the
6856       // comparison cannot succeed.
6857       Constant *Comp =
6858         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
6859                                                                  ShAmt);
6860       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6861         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6862         Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6863         return ReplaceInstUsesWith(ICI, Cst);
6864       }
6865       
6866       if (LHSI->hasOneUse()) {
6867         // Otherwise strength reduce the shift into an and.
6868         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6869         Constant *Mask =
6870           ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits, 
6871                                                        TypeBits-ShAmtVal));
6872         
6873         Value *And =
6874           Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
6875         return new ICmpInst(ICI.getPredicate(), And,
6876                             ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
6877       }
6878     }
6879     
6880     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6881     bool TrueIfSigned = false;
6882     if (LHSI->hasOneUse() &&
6883         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6884       // (X << 31) <s 0  --> (X&1) != 0
6885       Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
6886                                            (TypeBits-ShAmt->getZExtValue()-1));
6887       Value *And =
6888         Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
6889       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6890                           And, Constant::getNullValue(And->getType()));
6891     }
6892     break;
6893   }
6894     
6895   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6896   case Instruction::AShr: {
6897     // Only handle equality comparisons of shift-by-constant.
6898     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6899     if (!ShAmt || !ICI.isEquality()) break;
6900
6901     // Check that the shift amount is in range.  If not, don't perform
6902     // undefined shifts.  When the shift is visited it will be
6903     // simplified.
6904     uint32_t TypeBits = RHSV.getBitWidth();
6905     if (ShAmt->uge(TypeBits))
6906       break;
6907     
6908     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6909       
6910     // If we are comparing against bits always shifted out, the
6911     // comparison cannot succeed.
6912     APInt Comp = RHSV << ShAmtVal;
6913     if (LHSI->getOpcode() == Instruction::LShr)
6914       Comp = Comp.lshr(ShAmtVal);
6915     else
6916       Comp = Comp.ashr(ShAmtVal);
6917     
6918     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6919       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6920       Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6921       return ReplaceInstUsesWith(ICI, Cst);
6922     }
6923     
6924     // Otherwise, check to see if the bits shifted out are known to be zero.
6925     // If so, we can compare against the unshifted value:
6926     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6927     if (LHSI->hasOneUse() &&
6928         MaskedValueIsZero(LHSI->getOperand(0), 
6929                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6930       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6931                           ConstantExpr::getShl(RHS, ShAmt));
6932     }
6933       
6934     if (LHSI->hasOneUse()) {
6935       // Otherwise strength reduce the shift into an and.
6936       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6937       Constant *Mask = ConstantInt::get(*Context, Val);
6938       
6939       Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6940                                       Mask, LHSI->getName()+".mask");
6941       return new ICmpInst(ICI.getPredicate(), And,
6942                           ConstantExpr::getShl(RHS, ShAmt));
6943     }
6944     break;
6945   }
6946     
6947   case Instruction::SDiv:
6948   case Instruction::UDiv:
6949     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6950     // Fold this div into the comparison, producing a range check. 
6951     // Determine, based on the divide type, what the range is being 
6952     // checked.  If there is an overflow on the low or high side, remember 
6953     // it, otherwise compute the range [low, hi) bounding the new value.
6954     // See: InsertRangeTest above for the kinds of replacements possible.
6955     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6956       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6957                                           DivRHS))
6958         return R;
6959     break;
6960
6961   case Instruction::Add:
6962     // Fold: icmp pred (add, X, C1), C2
6963
6964     if (!ICI.isEquality()) {
6965       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6966       if (!LHSC) break;
6967       const APInt &LHSV = LHSC->getValue();
6968
6969       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6970                             .subtract(LHSV);
6971
6972       if (ICI.isSignedPredicate()) {
6973         if (CR.getLower().isSignBit()) {
6974           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6975                               ConstantInt::get(*Context, CR.getUpper()));
6976         } else if (CR.getUpper().isSignBit()) {
6977           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6978                               ConstantInt::get(*Context, CR.getLower()));
6979         }
6980       } else {
6981         if (CR.getLower().isMinValue()) {
6982           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6983                               ConstantInt::get(*Context, CR.getUpper()));
6984         } else if (CR.getUpper().isMinValue()) {
6985           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6986                               ConstantInt::get(*Context, CR.getLower()));
6987         }
6988       }
6989     }
6990     break;
6991   }
6992   
6993   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6994   if (ICI.isEquality()) {
6995     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6996     
6997     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6998     // the second operand is a constant, simplify a bit.
6999     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7000       switch (BO->getOpcode()) {
7001       case Instruction::SRem:
7002         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7003         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7004           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7005           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7006             Value *NewRem =
7007               Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7008                                   BO->getName());
7009             return new ICmpInst(ICI.getPredicate(), NewRem,
7010                                 Constant::getNullValue(BO->getType()));
7011           }
7012         }
7013         break;
7014       case Instruction::Add:
7015         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7016         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7017           if (BO->hasOneUse())
7018             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7019                                 ConstantExpr::getSub(RHS, BOp1C));
7020         } else if (RHSV == 0) {
7021           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7022           // efficiently invertible, or if the add has just this one use.
7023           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7024           
7025           if (Value *NegVal = dyn_castNegVal(BOp1))
7026             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
7027           else if (Value *NegVal = dyn_castNegVal(BOp0))
7028             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
7029           else if (BO->hasOneUse()) {
7030             Value *Neg = Builder->CreateNeg(BOp1);
7031             Neg->takeName(BO);
7032             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
7033           }
7034         }
7035         break;
7036       case Instruction::Xor:
7037         // For the xor case, we can xor two constants together, eliminating
7038         // the explicit xor.
7039         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7040           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
7041                               ConstantExpr::getXor(RHS, BOC));
7042         
7043         // FALLTHROUGH
7044       case Instruction::Sub:
7045         // Replace (([sub|xor] A, B) != 0) with (A != B)
7046         if (RHSV == 0)
7047           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7048                               BO->getOperand(1));
7049         break;
7050         
7051       case Instruction::Or:
7052         // If bits are being or'd in that are not present in the constant we
7053         // are comparing against, then the comparison could never succeed!
7054         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7055           Constant *NotCI = ConstantExpr::getNot(RHS);
7056           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7057             return ReplaceInstUsesWith(ICI,
7058                                        ConstantInt::get(Type::getInt1Ty(*Context), 
7059                                        isICMP_NE));
7060         }
7061         break;
7062         
7063       case Instruction::And:
7064         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7065           // If bits are being compared against that are and'd out, then the
7066           // comparison can never succeed!
7067           if ((RHSV & ~BOC->getValue()) != 0)
7068             return ReplaceInstUsesWith(ICI,
7069                                        ConstantInt::get(Type::getInt1Ty(*Context),
7070                                        isICMP_NE));
7071           
7072           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7073           if (RHS == BOC && RHSV.isPowerOf2())
7074             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7075                                 ICmpInst::ICMP_NE, LHSI,
7076                                 Constant::getNullValue(RHS->getType()));
7077           
7078           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7079           if (BOC->getValue().isSignBit()) {
7080             Value *X = BO->getOperand(0);
7081             Constant *Zero = Constant::getNullValue(X->getType());
7082             ICmpInst::Predicate pred = isICMP_NE ? 
7083               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7084             return new ICmpInst(pred, X, Zero);
7085           }
7086           
7087           // ((X & ~7) == 0) --> X < 8
7088           if (RHSV == 0 && isHighOnes(BOC)) {
7089             Value *X = BO->getOperand(0);
7090             Constant *NegX = ConstantExpr::getNeg(BOC);
7091             ICmpInst::Predicate pred = isICMP_NE ? 
7092               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7093             return new ICmpInst(pred, X, NegX);
7094           }
7095         }
7096       default: break;
7097       }
7098     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7099       // Handle icmp {eq|ne} <intrinsic>, intcst.
7100       if (II->getIntrinsicID() == Intrinsic::bswap) {
7101         Worklist.Add(II);
7102         ICI.setOperand(0, II->getOperand(1));
7103         ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7104         return &ICI;
7105       }
7106     }
7107   }
7108   return 0;
7109 }
7110
7111 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7112 /// We only handle extending casts so far.
7113 ///
7114 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7115   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7116   Value *LHSCIOp        = LHSCI->getOperand(0);
7117   const Type *SrcTy     = LHSCIOp->getType();
7118   const Type *DestTy    = LHSCI->getType();
7119   Value *RHSCIOp;
7120
7121   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7122   // integer type is the same size as the pointer type.
7123   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7124       TD->getPointerSizeInBits() ==
7125          cast<IntegerType>(DestTy)->getBitWidth()) {
7126     Value *RHSOp = 0;
7127     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7128       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7129     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7130       RHSOp = RHSC->getOperand(0);
7131       // If the pointer types don't match, insert a bitcast.
7132       if (LHSCIOp->getType() != RHSOp->getType())
7133         RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
7134     }
7135
7136     if (RHSOp)
7137       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7138   }
7139   
7140   // The code below only handles extension cast instructions, so far.
7141   // Enforce this.
7142   if (LHSCI->getOpcode() != Instruction::ZExt &&
7143       LHSCI->getOpcode() != Instruction::SExt)
7144     return 0;
7145
7146   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7147   bool isSignedCmp = ICI.isSignedPredicate();
7148
7149   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7150     // Not an extension from the same type?
7151     RHSCIOp = CI->getOperand(0);
7152     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7153       return 0;
7154     
7155     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7156     // and the other is a zext), then we can't handle this.
7157     if (CI->getOpcode() != LHSCI->getOpcode())
7158       return 0;
7159
7160     // Deal with equality cases early.
7161     if (ICI.isEquality())
7162       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7163
7164     // A signed comparison of sign extended values simplifies into a
7165     // signed comparison.
7166     if (isSignedCmp && isSignedExt)
7167       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7168
7169     // The other three cases all fold into an unsigned comparison.
7170     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7171   }
7172
7173   // If we aren't dealing with a constant on the RHS, exit early
7174   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7175   if (!CI)
7176     return 0;
7177
7178   // Compute the constant that would happen if we truncated to SrcTy then
7179   // reextended to DestTy.
7180   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7181   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7182                                                 Res1, DestTy);
7183
7184   // If the re-extended constant didn't change...
7185   if (Res2 == CI) {
7186     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7187     // For example, we might have:
7188     //    %A = sext i16 %X to i32
7189     //    %B = icmp ugt i32 %A, 1330
7190     // It is incorrect to transform this into 
7191     //    %B = icmp ugt i16 %X, 1330
7192     // because %A may have negative value. 
7193     //
7194     // However, we allow this when the compare is EQ/NE, because they are
7195     // signless.
7196     if (isSignedExt == isSignedCmp || ICI.isEquality())
7197       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7198     return 0;
7199   }
7200
7201   // The re-extended constant changed so the constant cannot be represented 
7202   // in the shorter type. Consequently, we cannot emit a simple comparison.
7203
7204   // First, handle some easy cases. We know the result cannot be equal at this
7205   // point so handle the ICI.isEquality() cases
7206   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7207     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7208   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7209     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7210
7211   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7212   // should have been folded away previously and not enter in here.
7213   Value *Result;
7214   if (isSignedCmp) {
7215     // We're performing a signed comparison.
7216     if (cast<ConstantInt>(CI)->getValue().isNegative())
7217       Result = ConstantInt::getFalse(*Context);          // X < (small) --> false
7218     else
7219       Result = ConstantInt::getTrue(*Context);           // X < (large) --> true
7220   } else {
7221     // We're performing an unsigned comparison.
7222     if (isSignedExt) {
7223       // We're performing an unsigned comp with a sign extended value.
7224       // This is true if the input is >= 0. [aka >s -1]
7225       Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7226       Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
7227     } else {
7228       // Unsigned extend & unsigned compare -> always true.
7229       Result = ConstantInt::getTrue(*Context);
7230     }
7231   }
7232
7233   // Finally, return the value computed.
7234   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7235       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7236     return ReplaceInstUsesWith(ICI, Result);
7237
7238   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7239           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7240          "ICmp should be folded!");
7241   if (Constant *CI = dyn_cast<Constant>(Result))
7242     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7243   return BinaryOperator::CreateNot(Result);
7244 }
7245
7246 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7247   return commonShiftTransforms(I);
7248 }
7249
7250 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7251   return commonShiftTransforms(I);
7252 }
7253
7254 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7255   if (Instruction *R = commonShiftTransforms(I))
7256     return R;
7257   
7258   Value *Op0 = I.getOperand(0);
7259   
7260   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7261   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7262     if (CSI->isAllOnesValue())
7263       return ReplaceInstUsesWith(I, CSI);
7264
7265   // See if we can turn a signed shr into an unsigned shr.
7266   if (MaskedValueIsZero(Op0,
7267                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7268     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7269
7270   // Arithmetic shifting an all-sign-bit value is a no-op.
7271   unsigned NumSignBits = ComputeNumSignBits(Op0);
7272   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7273     return ReplaceInstUsesWith(I, Op0);
7274
7275   return 0;
7276 }
7277
7278 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7279   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7280   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7281
7282   // shl X, 0 == X and shr X, 0 == X
7283   // shl 0, X == 0 and shr 0, X == 0
7284   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7285       Op0 == Constant::getNullValue(Op0->getType()))
7286     return ReplaceInstUsesWith(I, Op0);
7287   
7288   if (isa<UndefValue>(Op0)) {            
7289     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7290       return ReplaceInstUsesWith(I, Op0);
7291     else                                    // undef << X -> 0, undef >>u X -> 0
7292       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7293   }
7294   if (isa<UndefValue>(Op1)) {
7295     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7296       return ReplaceInstUsesWith(I, Op0);          
7297     else                                     // X << undef, X >>u undef -> 0
7298       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7299   }
7300
7301   // See if we can fold away this shift.
7302   if (SimplifyDemandedInstructionBits(I))
7303     return &I;
7304
7305   // Try to fold constant and into select arguments.
7306   if (isa<Constant>(Op0))
7307     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7308       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7309         return R;
7310
7311   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7312     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7313       return Res;
7314   return 0;
7315 }
7316
7317 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7318                                                BinaryOperator &I) {
7319   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7320
7321   // See if we can simplify any instructions used by the instruction whose sole 
7322   // purpose is to compute bits we don't care about.
7323   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7324   
7325   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7326   // a signed shift.
7327   //
7328   if (Op1->uge(TypeBits)) {
7329     if (I.getOpcode() != Instruction::AShr)
7330       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7331     else {
7332       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7333       return &I;
7334     }
7335   }
7336   
7337   // ((X*C1) << C2) == (X * (C1 << C2))
7338   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7339     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7340       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7341         return BinaryOperator::CreateMul(BO->getOperand(0),
7342                                         ConstantExpr::getShl(BOOp, Op1));
7343   
7344   // Try to fold constant and into select arguments.
7345   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7346     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7347       return R;
7348   if (isa<PHINode>(Op0))
7349     if (Instruction *NV = FoldOpIntoPhi(I))
7350       return NV;
7351   
7352   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7353   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7354     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7355     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7356     // place.  Don't try to do this transformation in this case.  Also, we
7357     // require that the input operand is a shift-by-constant so that we have
7358     // confidence that the shifts will get folded together.  We could do this
7359     // xform in more cases, but it is unlikely to be profitable.
7360     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7361         isa<ConstantInt>(TrOp->getOperand(1))) {
7362       // Okay, we'll do this xform.  Make the shift of shift.
7363       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7364       // (shift2 (shift1 & 0x00FF), c2)
7365       Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
7366
7367       // For logical shifts, the truncation has the effect of making the high
7368       // part of the register be zeros.  Emulate this by inserting an AND to
7369       // clear the top bits as needed.  This 'and' will usually be zapped by
7370       // other xforms later if dead.
7371       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7372       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7373       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7374       
7375       // The mask we constructed says what the trunc would do if occurring
7376       // between the shifts.  We want to know the effect *after* the second
7377       // shift.  We know that it is a logical shift by a constant, so adjust the
7378       // mask as appropriate.
7379       if (I.getOpcode() == Instruction::Shl)
7380         MaskV <<= Op1->getZExtValue();
7381       else {
7382         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7383         MaskV = MaskV.lshr(Op1->getZExtValue());
7384       }
7385
7386       // shift1 & 0x00FF
7387       Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7388                                       TI->getName());
7389
7390       // Return the value truncated to the interesting size.
7391       return new TruncInst(And, I.getType());
7392     }
7393   }
7394   
7395   if (Op0->hasOneUse()) {
7396     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7397       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7398       Value *V1, *V2;
7399       ConstantInt *CC;
7400       switch (Op0BO->getOpcode()) {
7401         default: break;
7402         case Instruction::Add:
7403         case Instruction::And:
7404         case Instruction::Or:
7405         case Instruction::Xor: {
7406           // These operators commute.
7407           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7408           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7409               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7410                     m_Specific(Op1)))) {
7411             Value *YS =         // (Y << C)
7412               Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7413             // (X + (Y << C))
7414             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7415                                             Op0BO->getOperand(1)->getName());
7416             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7417             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7418                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7419           }
7420           
7421           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7422           Value *Op0BOOp1 = Op0BO->getOperand(1);
7423           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7424               match(Op0BOOp1, 
7425                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7426                           m_ConstantInt(CC))) &&
7427               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7428             Value *YS =   // (Y << C)
7429               Builder->CreateShl(Op0BO->getOperand(0), Op1,
7430                                            Op0BO->getName());
7431             // X & (CC << C)
7432             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7433                                            V1->getName()+".mask");
7434             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7435           }
7436         }
7437           
7438         // FALL THROUGH.
7439         case Instruction::Sub: {
7440           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7441           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7442               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7443                     m_Specific(Op1)))) {
7444             Value *YS =  // (Y << C)
7445               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7446             // (X + (Y << C))
7447             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7448                                             Op0BO->getOperand(0)->getName());
7449             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7450             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7451                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7452           }
7453           
7454           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7455           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7456               match(Op0BO->getOperand(0),
7457                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7458                           m_ConstantInt(CC))) && V2 == Op1 &&
7459               cast<BinaryOperator>(Op0BO->getOperand(0))
7460                   ->getOperand(0)->hasOneUse()) {
7461             Value *YS = // (Y << C)
7462               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7463             // X & (CC << C)
7464             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7465                                            V1->getName()+".mask");
7466             
7467             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7468           }
7469           
7470           break;
7471         }
7472       }
7473       
7474       
7475       // If the operand is an bitwise operator with a constant RHS, and the
7476       // shift is the only use, we can pull it out of the shift.
7477       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7478         bool isValid = true;     // Valid only for And, Or, Xor
7479         bool highBitSet = false; // Transform if high bit of constant set?
7480         
7481         switch (Op0BO->getOpcode()) {
7482           default: isValid = false; break;   // Do not perform transform!
7483           case Instruction::Add:
7484             isValid = isLeftShift;
7485             break;
7486           case Instruction::Or:
7487           case Instruction::Xor:
7488             highBitSet = false;
7489             break;
7490           case Instruction::And:
7491             highBitSet = true;
7492             break;
7493         }
7494         
7495         // If this is a signed shift right, and the high bit is modified
7496         // by the logical operation, do not perform the transformation.
7497         // The highBitSet boolean indicates the value of the high bit of
7498         // the constant which would cause it to be modified for this
7499         // operation.
7500         //
7501         if (isValid && I.getOpcode() == Instruction::AShr)
7502           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7503         
7504         if (isValid) {
7505           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7506           
7507           Value *NewShift =
7508             Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
7509           NewShift->takeName(Op0BO);
7510           
7511           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7512                                         NewRHS);
7513         }
7514       }
7515     }
7516   }
7517   
7518   // Find out if this is a shift of a shift by a constant.
7519   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7520   if (ShiftOp && !ShiftOp->isShift())
7521     ShiftOp = 0;
7522   
7523   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7524     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7525     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7526     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7527     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7528     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7529     Value *X = ShiftOp->getOperand(0);
7530     
7531     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7532     
7533     const IntegerType *Ty = cast<IntegerType>(I.getType());
7534     
7535     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7536     if (I.getOpcode() == ShiftOp->getOpcode()) {
7537       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7538       // saturates.
7539       if (AmtSum >= TypeBits) {
7540         if (I.getOpcode() != Instruction::AShr)
7541           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7542         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7543       }
7544       
7545       return BinaryOperator::Create(I.getOpcode(), X,
7546                                     ConstantInt::get(Ty, AmtSum));
7547     }
7548     
7549     if (ShiftOp->getOpcode() == Instruction::LShr &&
7550         I.getOpcode() == Instruction::AShr) {
7551       if (AmtSum >= TypeBits)
7552         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7553       
7554       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7555       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7556     }
7557     
7558     if (ShiftOp->getOpcode() == Instruction::AShr &&
7559         I.getOpcode() == Instruction::LShr) {
7560       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7561       if (AmtSum >= TypeBits)
7562         AmtSum = TypeBits-1;
7563       
7564       Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7565
7566       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7567       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7568     }
7569     
7570     // Okay, if we get here, one shift must be left, and the other shift must be
7571     // right.  See if the amounts are equal.
7572     if (ShiftAmt1 == ShiftAmt2) {
7573       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7574       if (I.getOpcode() == Instruction::Shl) {
7575         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7576         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7577       }
7578       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7579       if (I.getOpcode() == Instruction::LShr) {
7580         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7581         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7582       }
7583       // We can simplify ((X << C) >>s C) into a trunc + sext.
7584       // NOTE: we could do this for any C, but that would make 'unusual' integer
7585       // types.  For now, just stick to ones well-supported by the code
7586       // generators.
7587       const Type *SExtType = 0;
7588       switch (Ty->getBitWidth() - ShiftAmt1) {
7589       case 1  :
7590       case 8  :
7591       case 16 :
7592       case 32 :
7593       case 64 :
7594       case 128:
7595         SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
7596         break;
7597       default: break;
7598       }
7599       if (SExtType)
7600         return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
7601       // Otherwise, we can't handle it yet.
7602     } else if (ShiftAmt1 < ShiftAmt2) {
7603       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7604       
7605       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7606       if (I.getOpcode() == Instruction::Shl) {
7607         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7608                ShiftOp->getOpcode() == Instruction::AShr);
7609         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7610         
7611         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7612         return BinaryOperator::CreateAnd(Shift,
7613                                          ConstantInt::get(*Context, Mask));
7614       }
7615       
7616       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7617       if (I.getOpcode() == Instruction::LShr) {
7618         assert(ShiftOp->getOpcode() == Instruction::Shl);
7619         Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7620         
7621         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7622         return BinaryOperator::CreateAnd(Shift,
7623                                          ConstantInt::get(*Context, Mask));
7624       }
7625       
7626       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7627     } else {
7628       assert(ShiftAmt2 < ShiftAmt1);
7629       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7630
7631       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7632       if (I.getOpcode() == Instruction::Shl) {
7633         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7634                ShiftOp->getOpcode() == Instruction::AShr);
7635         Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7636                                             ConstantInt::get(Ty, ShiftDiff));
7637         
7638         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7639         return BinaryOperator::CreateAnd(Shift,
7640                                          ConstantInt::get(*Context, Mask));
7641       }
7642       
7643       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7644       if (I.getOpcode() == Instruction::LShr) {
7645         assert(ShiftOp->getOpcode() == Instruction::Shl);
7646         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7647         
7648         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7649         return BinaryOperator::CreateAnd(Shift,
7650                                          ConstantInt::get(*Context, Mask));
7651       }
7652       
7653       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7654     }
7655   }
7656   return 0;
7657 }
7658
7659
7660 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7661 /// expression.  If so, decompose it, returning some value X, such that Val is
7662 /// X*Scale+Offset.
7663 ///
7664 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7665                                         int &Offset, LLVMContext *Context) {
7666   assert(Val->getType() == Type::getInt32Ty(*Context) && 
7667          "Unexpected allocation size type!");
7668   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7669     Offset = CI->getZExtValue();
7670     Scale  = 0;
7671     return ConstantInt::get(Type::getInt32Ty(*Context), 0);
7672   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7673     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7674       if (I->getOpcode() == Instruction::Shl) {
7675         // This is a value scaled by '1 << the shift amt'.
7676         Scale = 1U << RHS->getZExtValue();
7677         Offset = 0;
7678         return I->getOperand(0);
7679       } else if (I->getOpcode() == Instruction::Mul) {
7680         // This value is scaled by 'RHS'.
7681         Scale = RHS->getZExtValue();
7682         Offset = 0;
7683         return I->getOperand(0);
7684       } else if (I->getOpcode() == Instruction::Add) {
7685         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7686         // where C1 is divisible by C2.
7687         unsigned SubScale;
7688         Value *SubVal = 
7689           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7690                                     Offset, Context);
7691         Offset += RHS->getZExtValue();
7692         Scale = SubScale;
7693         return SubVal;
7694       }
7695     }
7696   }
7697
7698   // Otherwise, we can't look past this.
7699   Scale = 1;
7700   Offset = 0;
7701   return Val;
7702 }
7703
7704
7705 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7706 /// try to eliminate the cast by moving the type information into the alloc.
7707 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7708                                                    AllocationInst &AI) {
7709   const PointerType *PTy = cast<PointerType>(CI.getType());
7710   
7711   BuilderTy AllocaBuilder(*Builder);
7712   AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7713   
7714   // Remove any uses of AI that are dead.
7715   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7716   
7717   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7718     Instruction *User = cast<Instruction>(*UI++);
7719     if (isInstructionTriviallyDead(User)) {
7720       while (UI != E && *UI == User)
7721         ++UI; // If this instruction uses AI more than once, don't break UI.
7722       
7723       ++NumDeadInst;
7724       DEBUG(errs() << "IC: DCE: " << *User << '\n');
7725       EraseInstFromFunction(*User);
7726     }
7727   }
7728
7729   // This requires TargetData to get the alloca alignment and size information.
7730   if (!TD) return 0;
7731
7732   // Get the type really allocated and the type casted to.
7733   const Type *AllocElTy = AI.getAllocatedType();
7734   const Type *CastElTy = PTy->getElementType();
7735   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7736
7737   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7738   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7739   if (CastElTyAlign < AllocElTyAlign) return 0;
7740
7741   // If the allocation has multiple uses, only promote it if we are strictly
7742   // increasing the alignment of the resultant allocation.  If we keep it the
7743   // same, we open the door to infinite loops of various kinds.  (A reference
7744   // from a dbg.declare doesn't count as a use for this purpose.)
7745   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7746       CastElTyAlign == AllocElTyAlign) return 0;
7747
7748   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7749   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7750   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7751
7752   // See if we can satisfy the modulus by pulling a scale out of the array
7753   // size argument.
7754   unsigned ArraySizeScale;
7755   int ArrayOffset;
7756   Value *NumElements = // See if the array size is a decomposable linear expr.
7757     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7758                               ArrayOffset, Context);
7759  
7760   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7761   // do the xform.
7762   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7763       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7764
7765   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7766   Value *Amt = 0;
7767   if (Scale == 1) {
7768     Amt = NumElements;
7769   } else {
7770     Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
7771     // Insert before the alloca, not before the cast.
7772     Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
7773   }
7774   
7775   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7776     Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
7777     Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
7778   }
7779   
7780   AllocationInst *New;
7781   if (isa<MallocInst>(AI))
7782     New = AllocaBuilder.CreateMalloc(CastElTy, Amt);
7783   else
7784     New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7785   New->setAlignment(AI.getAlignment());
7786   New->takeName(&AI);
7787   
7788   // If the allocation has one real use plus a dbg.declare, just remove the
7789   // declare.
7790   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7791     EraseInstFromFunction(*DI);
7792   }
7793   // If the allocation has multiple real uses, insert a cast and change all
7794   // things that used it to use the new cast.  This will also hack on CI, but it
7795   // will die soon.
7796   else if (!AI.hasOneUse()) {
7797     // New is the allocation instruction, pointer typed. AI is the original
7798     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7799     Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
7800     AI.replaceAllUsesWith(NewCast);
7801   }
7802   return ReplaceInstUsesWith(CI, New);
7803 }
7804
7805 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7806 /// and return it as type Ty without inserting any new casts and without
7807 /// changing the computed value.  This is used by code that tries to decide
7808 /// whether promoting or shrinking integer operations to wider or smaller types
7809 /// will allow us to eliminate a truncate or extend.
7810 ///
7811 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7812 /// extension operation if Ty is larger.
7813 ///
7814 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7815 /// should return true if trunc(V) can be computed by computing V in the smaller
7816 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7817 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7818 /// efficiently truncated.
7819 ///
7820 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7821 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7822 /// the final result.
7823 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7824                                               unsigned CastOpc,
7825                                               int &NumCastsRemoved){
7826   // We can always evaluate constants in another type.
7827   if (isa<Constant>(V))
7828     return true;
7829   
7830   Instruction *I = dyn_cast<Instruction>(V);
7831   if (!I) return false;
7832   
7833   const Type *OrigTy = V->getType();
7834   
7835   // If this is an extension or truncate, we can often eliminate it.
7836   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7837     // If this is a cast from the destination type, we can trivially eliminate
7838     // it, and this will remove a cast overall.
7839     if (I->getOperand(0)->getType() == Ty) {
7840       // If the first operand is itself a cast, and is eliminable, do not count
7841       // this as an eliminable cast.  We would prefer to eliminate those two
7842       // casts first.
7843       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7844         ++NumCastsRemoved;
7845       return true;
7846     }
7847   }
7848
7849   // We can't extend or shrink something that has multiple uses: doing so would
7850   // require duplicating the instruction in general, which isn't profitable.
7851   if (!I->hasOneUse()) return false;
7852
7853   unsigned Opc = I->getOpcode();
7854   switch (Opc) {
7855   case Instruction::Add:
7856   case Instruction::Sub:
7857   case Instruction::Mul:
7858   case Instruction::And:
7859   case Instruction::Or:
7860   case Instruction::Xor:
7861     // These operators can all arbitrarily be extended or truncated.
7862     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7863                                       NumCastsRemoved) &&
7864            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7865                                       NumCastsRemoved);
7866
7867   case Instruction::UDiv:
7868   case Instruction::URem: {
7869     // UDiv and URem can be truncated if all the truncated bits are zero.
7870     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7871     uint32_t BitWidth = Ty->getScalarSizeInBits();
7872     if (BitWidth < OrigBitWidth) {
7873       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7874       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7875           MaskedValueIsZero(I->getOperand(1), Mask)) {
7876         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7877                                           NumCastsRemoved) &&
7878                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7879                                           NumCastsRemoved);
7880       }
7881     }
7882     break;
7883   }
7884   case Instruction::Shl:
7885     // If we are truncating the result of this SHL, and if it's a shift of a
7886     // constant amount, we can always perform a SHL in a smaller type.
7887     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7888       uint32_t BitWidth = Ty->getScalarSizeInBits();
7889       if (BitWidth < OrigTy->getScalarSizeInBits() &&
7890           CI->getLimitedValue(BitWidth) < BitWidth)
7891         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7892                                           NumCastsRemoved);
7893     }
7894     break;
7895   case Instruction::LShr:
7896     // If this is a truncate of a logical shr, we can truncate it to a smaller
7897     // lshr iff we know that the bits we would otherwise be shifting in are
7898     // already zeros.
7899     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7900       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7901       uint32_t BitWidth = Ty->getScalarSizeInBits();
7902       if (BitWidth < OrigBitWidth &&
7903           MaskedValueIsZero(I->getOperand(0),
7904             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7905           CI->getLimitedValue(BitWidth) < BitWidth) {
7906         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7907                                           NumCastsRemoved);
7908       }
7909     }
7910     break;
7911   case Instruction::ZExt:
7912   case Instruction::SExt:
7913   case Instruction::Trunc:
7914     // If this is the same kind of case as our original (e.g. zext+zext), we
7915     // can safely replace it.  Note that replacing it does not reduce the number
7916     // of casts in the input.
7917     if (Opc == CastOpc)
7918       return true;
7919
7920     // sext (zext ty1), ty2 -> zext ty2
7921     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7922       return true;
7923     break;
7924   case Instruction::Select: {
7925     SelectInst *SI = cast<SelectInst>(I);
7926     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7927                                       NumCastsRemoved) &&
7928            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7929                                       NumCastsRemoved);
7930   }
7931   case Instruction::PHI: {
7932     // We can change a phi if we can change all operands.
7933     PHINode *PN = cast<PHINode>(I);
7934     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7935       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7936                                       NumCastsRemoved))
7937         return false;
7938     return true;
7939   }
7940   default:
7941     // TODO: Can handle more cases here.
7942     break;
7943   }
7944   
7945   return false;
7946 }
7947
7948 /// EvaluateInDifferentType - Given an expression that 
7949 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7950 /// evaluate the expression.
7951 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7952                                              bool isSigned) {
7953   if (Constant *C = dyn_cast<Constant>(V))
7954     return ConstantExpr::getIntegerCast(C, Ty,
7955                                                isSigned /*Sext or ZExt*/);
7956
7957   // Otherwise, it must be an instruction.
7958   Instruction *I = cast<Instruction>(V);
7959   Instruction *Res = 0;
7960   unsigned Opc = I->getOpcode();
7961   switch (Opc) {
7962   case Instruction::Add:
7963   case Instruction::Sub:
7964   case Instruction::Mul:
7965   case Instruction::And:
7966   case Instruction::Or:
7967   case Instruction::Xor:
7968   case Instruction::AShr:
7969   case Instruction::LShr:
7970   case Instruction::Shl:
7971   case Instruction::UDiv:
7972   case Instruction::URem: {
7973     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7974     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7975     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7976     break;
7977   }    
7978   case Instruction::Trunc:
7979   case Instruction::ZExt:
7980   case Instruction::SExt:
7981     // If the source type of the cast is the type we're trying for then we can
7982     // just return the source.  There's no need to insert it because it is not
7983     // new.
7984     if (I->getOperand(0)->getType() == Ty)
7985       return I->getOperand(0);
7986     
7987     // Otherwise, must be the same type of cast, so just reinsert a new one.
7988     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7989                            Ty);
7990     break;
7991   case Instruction::Select: {
7992     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7993     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7994     Res = SelectInst::Create(I->getOperand(0), True, False);
7995     break;
7996   }
7997   case Instruction::PHI: {
7998     PHINode *OPN = cast<PHINode>(I);
7999     PHINode *NPN = PHINode::Create(Ty);
8000     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8001       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8002       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8003     }
8004     Res = NPN;
8005     break;
8006   }
8007   default: 
8008     // TODO: Can handle more cases here.
8009     llvm_unreachable("Unreachable!");
8010     break;
8011   }
8012   
8013   Res->takeName(I);
8014   return InsertNewInstBefore(Res, *I);
8015 }
8016
8017 /// @brief Implement the transforms common to all CastInst visitors.
8018 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8019   Value *Src = CI.getOperand(0);
8020
8021   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8022   // eliminate it now.
8023   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8024     if (Instruction::CastOps opc = 
8025         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8026       // The first cast (CSrc) is eliminable so we need to fix up or replace
8027       // the second cast (CI). CSrc will then have a good chance of being dead.
8028       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8029     }
8030   }
8031
8032   // If we are casting a select then fold the cast into the select
8033   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8034     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8035       return NV;
8036
8037   // If we are casting a PHI then fold the cast into the PHI
8038   if (isa<PHINode>(Src))
8039     if (Instruction *NV = FoldOpIntoPhi(CI))
8040       return NV;
8041   
8042   return 0;
8043 }
8044
8045 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8046 /// or not there is a sequence of GEP indices into the type that will land us at
8047 /// the specified offset.  If so, fill them into NewIndices and return the
8048 /// resultant element type, otherwise return null.
8049 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8050                                        SmallVectorImpl<Value*> &NewIndices,
8051                                        const TargetData *TD,
8052                                        LLVMContext *Context) {
8053   if (!TD) return 0;
8054   if (!Ty->isSized()) return 0;
8055   
8056   // Start with the index over the outer type.  Note that the type size
8057   // might be zero (even if the offset isn't zero) if the indexed type
8058   // is something like [0 x {int, int}]
8059   const Type *IntPtrTy = TD->getIntPtrType(*Context);
8060   int64_t FirstIdx = 0;
8061   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8062     FirstIdx = Offset/TySize;
8063     Offset -= FirstIdx*TySize;
8064     
8065     // Handle hosts where % returns negative instead of values [0..TySize).
8066     if (Offset < 0) {
8067       --FirstIdx;
8068       Offset += TySize;
8069       assert(Offset >= 0);
8070     }
8071     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8072   }
8073   
8074   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8075     
8076   // Index into the types.  If we fail, set OrigBase to null.
8077   while (Offset) {
8078     // Indexing into tail padding between struct/array elements.
8079     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8080       return 0;
8081     
8082     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8083       const StructLayout *SL = TD->getStructLayout(STy);
8084       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8085              "Offset must stay within the indexed type");
8086       
8087       unsigned Elt = SL->getElementContainingOffset(Offset);
8088       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8089       
8090       Offset -= SL->getElementOffset(Elt);
8091       Ty = STy->getElementType(Elt);
8092     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8093       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8094       assert(EltSize && "Cannot index into a zero-sized array");
8095       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8096       Offset %= EltSize;
8097       Ty = AT->getElementType();
8098     } else {
8099       // Otherwise, we can't index into the middle of this atomic type, bail.
8100       return 0;
8101     }
8102   }
8103   
8104   return Ty;
8105 }
8106
8107 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8108 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8109   Value *Src = CI.getOperand(0);
8110   
8111   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8112     // If casting the result of a getelementptr instruction with no offset, turn
8113     // this into a cast of the original pointer!
8114     if (GEP->hasAllZeroIndices()) {
8115       // Changing the cast operand is usually not a good idea but it is safe
8116       // here because the pointer operand is being replaced with another 
8117       // pointer operand so the opcode doesn't need to change.
8118       Worklist.Add(GEP);
8119       CI.setOperand(0, GEP->getOperand(0));
8120       return &CI;
8121     }
8122     
8123     // If the GEP has a single use, and the base pointer is a bitcast, and the
8124     // GEP computes a constant offset, see if we can convert these three
8125     // instructions into fewer.  This typically happens with unions and other
8126     // non-type-safe code.
8127     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8128       if (GEP->hasAllConstantIndices()) {
8129         // We are guaranteed to get a constant from EmitGEPOffset.
8130         ConstantInt *OffsetV =
8131                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8132         int64_t Offset = OffsetV->getSExtValue();
8133         
8134         // Get the base pointer input of the bitcast, and the type it points to.
8135         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8136         const Type *GEPIdxTy =
8137           cast<PointerType>(OrigBase->getType())->getElementType();
8138         SmallVector<Value*, 8> NewIndices;
8139         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8140           // If we were able to index down into an element, create the GEP
8141           // and bitcast the result.  This eliminates one bitcast, potentially
8142           // two.
8143           Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8144             Builder->CreateInBoundsGEP(OrigBase,
8145                                        NewIndices.begin(), NewIndices.end()) :
8146             Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
8147           NGEP->takeName(GEP);
8148           
8149           if (isa<BitCastInst>(CI))
8150             return new BitCastInst(NGEP, CI.getType());
8151           assert(isa<PtrToIntInst>(CI));
8152           return new PtrToIntInst(NGEP, CI.getType());
8153         }
8154       }      
8155     }
8156   }
8157     
8158   return commonCastTransforms(CI);
8159 }
8160
8161 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8162 /// type like i42.  We don't want to introduce operations on random non-legal
8163 /// integer types where they don't already exist in the code.  In the future,
8164 /// we should consider making this based off target-data, so that 32-bit targets
8165 /// won't get i64 operations etc.
8166 static bool isSafeIntegerType(const Type *Ty) {
8167   switch (Ty->getPrimitiveSizeInBits()) {
8168   case 8:
8169   case 16:
8170   case 32:
8171   case 64:
8172     return true;
8173   default: 
8174     return false;
8175   }
8176 }
8177
8178 /// commonIntCastTransforms - This function implements the common transforms
8179 /// for trunc, zext, and sext.
8180 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8181   if (Instruction *Result = commonCastTransforms(CI))
8182     return Result;
8183
8184   Value *Src = CI.getOperand(0);
8185   const Type *SrcTy = Src->getType();
8186   const Type *DestTy = CI.getType();
8187   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8188   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8189
8190   // See if we can simplify any instructions used by the LHS whose sole 
8191   // purpose is to compute bits we don't care about.
8192   if (SimplifyDemandedInstructionBits(CI))
8193     return &CI;
8194
8195   // If the source isn't an instruction or has more than one use then we
8196   // can't do anything more. 
8197   Instruction *SrcI = dyn_cast<Instruction>(Src);
8198   if (!SrcI || !Src->hasOneUse())
8199     return 0;
8200
8201   // Attempt to propagate the cast into the instruction for int->int casts.
8202   int NumCastsRemoved = 0;
8203   // Only do this if the dest type is a simple type, don't convert the
8204   // expression tree to something weird like i93 unless the source is also
8205   // strange.
8206   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8207        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8208       CanEvaluateInDifferentType(SrcI, DestTy,
8209                                  CI.getOpcode(), NumCastsRemoved)) {
8210     // If this cast is a truncate, evaluting in a different type always
8211     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8212     // we need to do an AND to maintain the clear top-part of the computation,
8213     // so we require that the input have eliminated at least one cast.  If this
8214     // is a sign extension, we insert two new casts (to do the extension) so we
8215     // require that two casts have been eliminated.
8216     bool DoXForm = false;
8217     bool JustReplace = false;
8218     switch (CI.getOpcode()) {
8219     default:
8220       // All the others use floating point so we shouldn't actually 
8221       // get here because of the check above.
8222       llvm_unreachable("Unknown cast type");
8223     case Instruction::Trunc:
8224       DoXForm = true;
8225       break;
8226     case Instruction::ZExt: {
8227       DoXForm = NumCastsRemoved >= 1;
8228       if (!DoXForm && 0) {
8229         // If it's unnecessary to issue an AND to clear the high bits, it's
8230         // always profitable to do this xform.
8231         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8232         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8233         if (MaskedValueIsZero(TryRes, Mask))
8234           return ReplaceInstUsesWith(CI, TryRes);
8235         
8236         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8237           if (TryI->use_empty())
8238             EraseInstFromFunction(*TryI);
8239       }
8240       break;
8241     }
8242     case Instruction::SExt: {
8243       DoXForm = NumCastsRemoved >= 2;
8244       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8245         // If we do not have to emit the truncate + sext pair, then it's always
8246         // profitable to do this xform.
8247         //
8248         // It's not safe to eliminate the trunc + sext pair if one of the
8249         // eliminated cast is a truncate. e.g.
8250         // t2 = trunc i32 t1 to i16
8251         // t3 = sext i16 t2 to i32
8252         // !=
8253         // i32 t1
8254         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8255         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8256         if (NumSignBits > (DestBitSize - SrcBitSize))
8257           return ReplaceInstUsesWith(CI, TryRes);
8258         
8259         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8260           if (TryI->use_empty())
8261             EraseInstFromFunction(*TryI);
8262       }
8263       break;
8264     }
8265     }
8266     
8267     if (DoXForm) {
8268       DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8269             " to avoid cast: " << CI);
8270       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8271                                            CI.getOpcode() == Instruction::SExt);
8272       if (JustReplace)
8273         // Just replace this cast with the result.
8274         return ReplaceInstUsesWith(CI, Res);
8275
8276       assert(Res->getType() == DestTy);
8277       switch (CI.getOpcode()) {
8278       default: llvm_unreachable("Unknown cast type!");
8279       case Instruction::Trunc:
8280         // Just replace this cast with the result.
8281         return ReplaceInstUsesWith(CI, Res);
8282       case Instruction::ZExt: {
8283         assert(SrcBitSize < DestBitSize && "Not a zext?");
8284
8285         // If the high bits are already zero, just replace this cast with the
8286         // result.
8287         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8288         if (MaskedValueIsZero(Res, Mask))
8289           return ReplaceInstUsesWith(CI, Res);
8290
8291         // We need to emit an AND to clear the high bits.
8292         Constant *C = ConstantInt::get(*Context, 
8293                                  APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8294         return BinaryOperator::CreateAnd(Res, C);
8295       }
8296       case Instruction::SExt: {
8297         // If the high bits are already filled with sign bit, just replace this
8298         // cast with the result.
8299         unsigned NumSignBits = ComputeNumSignBits(Res);
8300         if (NumSignBits > (DestBitSize - SrcBitSize))
8301           return ReplaceInstUsesWith(CI, Res);
8302
8303         // We need to emit a cast to truncate, then a cast to sext.
8304         return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
8305       }
8306       }
8307     }
8308   }
8309   
8310   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8311   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8312
8313   switch (SrcI->getOpcode()) {
8314   case Instruction::Add:
8315   case Instruction::Mul:
8316   case Instruction::And:
8317   case Instruction::Or:
8318   case Instruction::Xor:
8319     // If we are discarding information, rewrite.
8320     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8321       // Don't insert two casts unless at least one can be eliminated.
8322       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8323           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8324         Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8325         Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8326         return BinaryOperator::Create(
8327             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8328       }
8329     }
8330
8331     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8332     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8333         SrcI->getOpcode() == Instruction::Xor &&
8334         Op1 == ConstantInt::getTrue(*Context) &&
8335         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8336       Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
8337       return BinaryOperator::CreateXor(New,
8338                                       ConstantInt::get(CI.getType(), 1));
8339     }
8340     break;
8341
8342   case Instruction::Shl: {
8343     // Canonicalize trunc inside shl, if we can.
8344     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8345     if (CI && DestBitSize < SrcBitSize &&
8346         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8347       Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8348       Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8349       return BinaryOperator::CreateShl(Op0c, Op1c);
8350     }
8351     break;
8352   }
8353   }
8354   return 0;
8355 }
8356
8357 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8358   if (Instruction *Result = commonIntCastTransforms(CI))
8359     return Result;
8360   
8361   Value *Src = CI.getOperand(0);
8362   const Type *Ty = CI.getType();
8363   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8364   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8365
8366   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8367   if (DestBitWidth == 1) {
8368     Constant *One = ConstantInt::get(Src->getType(), 1);
8369     Src = Builder->CreateAnd(Src, One, "tmp");
8370     Value *Zero = Constant::getNullValue(Src->getType());
8371     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8372   }
8373
8374   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8375   ConstantInt *ShAmtV = 0;
8376   Value *ShiftOp = 0;
8377   if (Src->hasOneUse() &&
8378       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8379     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8380     
8381     // Get a mask for the bits shifting in.
8382     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8383     if (MaskedValueIsZero(ShiftOp, Mask)) {
8384       if (ShAmt >= DestBitWidth)        // All zeros.
8385         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8386       
8387       // Okay, we can shrink this.  Truncate the input, then return a new
8388       // shift.
8389       Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
8390       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8391       return BinaryOperator::CreateLShr(V1, V2);
8392     }
8393   }
8394   
8395   return 0;
8396 }
8397
8398 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8399 /// in order to eliminate the icmp.
8400 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8401                                              bool DoXform) {
8402   // If we are just checking for a icmp eq of a single bit and zext'ing it
8403   // to an integer, then shift the bit to the appropriate place and then
8404   // cast to integer to avoid the comparison.
8405   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8406     const APInt &Op1CV = Op1C->getValue();
8407       
8408     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8409     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8410     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8411         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8412       if (!DoXform) return ICI;
8413
8414       Value *In = ICI->getOperand(0);
8415       Value *Sh = ConstantInt::get(In->getType(),
8416                                    In->getType()->getScalarSizeInBits()-1);
8417       In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
8418       if (In->getType() != CI.getType())
8419         In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
8420
8421       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8422         Constant *One = ConstantInt::get(In->getType(), 1);
8423         In = Builder->CreateXor(In, One, In->getName()+".not");
8424       }
8425
8426       return ReplaceInstUsesWith(CI, In);
8427     }
8428       
8429       
8430       
8431     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8432     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8433     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8434     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8435     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8436     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8437     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8438     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8439     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8440         // This only works for EQ and NE
8441         ICI->isEquality()) {
8442       // If Op1C some other power of two, convert:
8443       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8444       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8445       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8446       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8447         
8448       APInt KnownZeroMask(~KnownZero);
8449       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8450         if (!DoXform) return ICI;
8451
8452         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8453         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8454           // (X&4) == 2 --> false
8455           // (X&4) != 2 --> true
8456           Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8457           Res = ConstantExpr::getZExt(Res, CI.getType());
8458           return ReplaceInstUsesWith(CI, Res);
8459         }
8460           
8461         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8462         Value *In = ICI->getOperand(0);
8463         if (ShiftAmt) {
8464           // Perform a logical shr by shiftamt.
8465           // Insert the shift to put the result in the low bit.
8466           In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8467                                    In->getName()+".lobit");
8468         }
8469           
8470         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8471           Constant *One = ConstantInt::get(In->getType(), 1);
8472           In = Builder->CreateXor(In, One, "tmp");
8473         }
8474           
8475         if (CI.getType() == In->getType())
8476           return ReplaceInstUsesWith(CI, In);
8477         else
8478           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8479       }
8480     }
8481   }
8482
8483   return 0;
8484 }
8485
8486 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8487   // If one of the common conversion will work ..
8488   if (Instruction *Result = commonIntCastTransforms(CI))
8489     return Result;
8490
8491   Value *Src = CI.getOperand(0);
8492
8493   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8494   // types and if the sizes are just right we can convert this into a logical
8495   // 'and' which will be much cheaper than the pair of casts.
8496   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8497     // Get the sizes of the types involved.  We know that the intermediate type
8498     // will be smaller than A or C, but don't know the relation between A and C.
8499     Value *A = CSrc->getOperand(0);
8500     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8501     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8502     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8503     // If we're actually extending zero bits, then if
8504     // SrcSize <  DstSize: zext(a & mask)
8505     // SrcSize == DstSize: a & mask
8506     // SrcSize  > DstSize: trunc(a) & mask
8507     if (SrcSize < DstSize) {
8508       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8509       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8510       Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
8511       return new ZExtInst(And, CI.getType());
8512     }
8513     
8514     if (SrcSize == DstSize) {
8515       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8516       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8517                                                            AndValue));
8518     }
8519     if (SrcSize > DstSize) {
8520       Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
8521       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8522       return BinaryOperator::CreateAnd(Trunc, 
8523                                        ConstantInt::get(Trunc->getType(),
8524                                                                AndValue));
8525     }
8526   }
8527
8528   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8529     return transformZExtICmp(ICI, CI);
8530
8531   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8532   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8533     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8534     // of the (zext icmp) will be transformed.
8535     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8536     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8537     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8538         (transformZExtICmp(LHS, CI, false) ||
8539          transformZExtICmp(RHS, CI, false))) {
8540       Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8541       Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
8542       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8543     }
8544   }
8545
8546   // zext(trunc(t) & C) -> (t & zext(C)).
8547   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8548     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8549       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8550         Value *TI0 = TI->getOperand(0);
8551         if (TI0->getType() == CI.getType())
8552           return
8553             BinaryOperator::CreateAnd(TI0,
8554                                 ConstantExpr::getZExt(C, CI.getType()));
8555       }
8556
8557   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8558   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8559     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8560       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8561         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8562             And->getOperand(1) == C)
8563           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8564             Value *TI0 = TI->getOperand(0);
8565             if (TI0->getType() == CI.getType()) {
8566               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8567               Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
8568               return BinaryOperator::CreateXor(NewAnd, ZC);
8569             }
8570           }
8571
8572   return 0;
8573 }
8574
8575 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8576   if (Instruction *I = commonIntCastTransforms(CI))
8577     return I;
8578   
8579   Value *Src = CI.getOperand(0);
8580   
8581   // Canonicalize sign-extend from i1 to a select.
8582   if (Src->getType() == Type::getInt1Ty(*Context))
8583     return SelectInst::Create(Src,
8584                               Constant::getAllOnesValue(CI.getType()),
8585                               Constant::getNullValue(CI.getType()));
8586
8587   // See if the value being truncated is already sign extended.  If so, just
8588   // eliminate the trunc/sext pair.
8589   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8590     Value *Op = cast<User>(Src)->getOperand(0);
8591     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8592     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8593     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8594     unsigned NumSignBits = ComputeNumSignBits(Op);
8595
8596     if (OpBits == DestBits) {
8597       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8598       // bits, it is already ready.
8599       if (NumSignBits > DestBits-MidBits)
8600         return ReplaceInstUsesWith(CI, Op);
8601     } else if (OpBits < DestBits) {
8602       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8603       // bits, just sext from i32.
8604       if (NumSignBits > OpBits-MidBits)
8605         return new SExtInst(Op, CI.getType(), "tmp");
8606     } else {
8607       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8608       // bits, just truncate to i32.
8609       if (NumSignBits > OpBits-MidBits)
8610         return new TruncInst(Op, CI.getType(), "tmp");
8611     }
8612   }
8613
8614   // If the input is a shl/ashr pair of a same constant, then this is a sign
8615   // extension from a smaller value.  If we could trust arbitrary bitwidth
8616   // integers, we could turn this into a truncate to the smaller bit and then
8617   // use a sext for the whole extension.  Since we don't, look deeper and check
8618   // for a truncate.  If the source and dest are the same type, eliminate the
8619   // trunc and extend and just do shifts.  For example, turn:
8620   //   %a = trunc i32 %i to i8
8621   //   %b = shl i8 %a, 6
8622   //   %c = ashr i8 %b, 6
8623   //   %d = sext i8 %c to i32
8624   // into:
8625   //   %a = shl i32 %i, 30
8626   //   %d = ashr i32 %a, 30
8627   Value *A = 0;
8628   ConstantInt *BA = 0, *CA = 0;
8629   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8630                         m_ConstantInt(CA))) &&
8631       BA == CA && isa<TruncInst>(A)) {
8632     Value *I = cast<TruncInst>(A)->getOperand(0);
8633     if (I->getType() == CI.getType()) {
8634       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8635       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8636       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8637       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8638       I = Builder->CreateShl(I, ShAmtV, CI.getName());
8639       return BinaryOperator::CreateAShr(I, ShAmtV);
8640     }
8641   }
8642   
8643   return 0;
8644 }
8645
8646 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8647 /// in the specified FP type without changing its value.
8648 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8649                               LLVMContext *Context) {
8650   bool losesInfo;
8651   APFloat F = CFP->getValueAPF();
8652   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8653   if (!losesInfo)
8654     return ConstantFP::get(*Context, F);
8655   return 0;
8656 }
8657
8658 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8659 /// through it until we get the source value.
8660 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8661   if (Instruction *I = dyn_cast<Instruction>(V))
8662     if (I->getOpcode() == Instruction::FPExt)
8663       return LookThroughFPExtensions(I->getOperand(0), Context);
8664   
8665   // If this value is a constant, return the constant in the smallest FP type
8666   // that can accurately represent it.  This allows us to turn
8667   // (float)((double)X+2.0) into x+2.0f.
8668   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8669     if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
8670       return V;  // No constant folding of this.
8671     // See if the value can be truncated to float and then reextended.
8672     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8673       return V;
8674     if (CFP->getType() == Type::getDoubleTy(*Context))
8675       return V;  // Won't shrink.
8676     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8677       return V;
8678     // Don't try to shrink to various long double types.
8679   }
8680   
8681   return V;
8682 }
8683
8684 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8685   if (Instruction *I = commonCastTransforms(CI))
8686     return I;
8687   
8688   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8689   // smaller than the destination type, we can eliminate the truncate by doing
8690   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8691   // many builtins (sqrt, etc).
8692   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8693   if (OpI && OpI->hasOneUse()) {
8694     switch (OpI->getOpcode()) {
8695     default: break;
8696     case Instruction::FAdd:
8697     case Instruction::FSub:
8698     case Instruction::FMul:
8699     case Instruction::FDiv:
8700     case Instruction::FRem:
8701       const Type *SrcTy = OpI->getType();
8702       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8703       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8704       if (LHSTrunc->getType() != SrcTy && 
8705           RHSTrunc->getType() != SrcTy) {
8706         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8707         // If the source types were both smaller than the destination type of
8708         // the cast, do this xform.
8709         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8710             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8711           LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8712           RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
8713           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8714         }
8715       }
8716       break;  
8717     }
8718   }
8719   return 0;
8720 }
8721
8722 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8723   return commonCastTransforms(CI);
8724 }
8725
8726 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8727   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8728   if (OpI == 0)
8729     return commonCastTransforms(FI);
8730
8731   // fptoui(uitofp(X)) --> X
8732   // fptoui(sitofp(X)) --> X
8733   // This is safe if the intermediate type has enough bits in its mantissa to
8734   // accurately represent all values of X.  For example, do not do this with
8735   // i64->float->i64.  This is also safe for sitofp case, because any negative
8736   // 'X' value would cause an undefined result for the fptoui. 
8737   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8738       OpI->getOperand(0)->getType() == FI.getType() &&
8739       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8740                     OpI->getType()->getFPMantissaWidth())
8741     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8742
8743   return commonCastTransforms(FI);
8744 }
8745
8746 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8747   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8748   if (OpI == 0)
8749     return commonCastTransforms(FI);
8750   
8751   // fptosi(sitofp(X)) --> X
8752   // fptosi(uitofp(X)) --> X
8753   // This is safe if the intermediate type has enough bits in its mantissa to
8754   // accurately represent all values of X.  For example, do not do this with
8755   // i64->float->i64.  This is also safe for sitofp case, because any negative
8756   // 'X' value would cause an undefined result for the fptoui. 
8757   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8758       OpI->getOperand(0)->getType() == FI.getType() &&
8759       (int)FI.getType()->getScalarSizeInBits() <=
8760                     OpI->getType()->getFPMantissaWidth())
8761     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8762   
8763   return commonCastTransforms(FI);
8764 }
8765
8766 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8767   return commonCastTransforms(CI);
8768 }
8769
8770 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8771   return commonCastTransforms(CI);
8772 }
8773
8774 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8775   // If the destination integer type is smaller than the intptr_t type for
8776   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8777   // trunc to be exposed to other transforms.  Don't do this for extending
8778   // ptrtoint's, because we don't know if the target sign or zero extends its
8779   // pointers.
8780   if (TD &&
8781       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8782     Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8783                                        TD->getIntPtrType(CI.getContext()),
8784                                        "tmp");
8785     return new TruncInst(P, CI.getType());
8786   }
8787   
8788   return commonPointerCastTransforms(CI);
8789 }
8790
8791 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8792   // If the source integer type is larger than the intptr_t type for
8793   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8794   // allows the trunc to be exposed to other transforms.  Don't do this for
8795   // extending inttoptr's, because we don't know if the target sign or zero
8796   // extends to pointers.
8797   if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
8798       TD->getPointerSizeInBits()) {
8799     Value *P = Builder->CreateTrunc(CI.getOperand(0),
8800                                     TD->getIntPtrType(CI.getContext()), "tmp");
8801     return new IntToPtrInst(P, CI.getType());
8802   }
8803   
8804   if (Instruction *I = commonCastTransforms(CI))
8805     return I;
8806
8807   return 0;
8808 }
8809
8810 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8811   // If the operands are integer typed then apply the integer transforms,
8812   // otherwise just apply the common ones.
8813   Value *Src = CI.getOperand(0);
8814   const Type *SrcTy = Src->getType();
8815   const Type *DestTy = CI.getType();
8816
8817   if (isa<PointerType>(SrcTy)) {
8818     if (Instruction *I = commonPointerCastTransforms(CI))
8819       return I;
8820   } else {
8821     if (Instruction *Result = commonCastTransforms(CI))
8822       return Result;
8823   }
8824
8825
8826   // Get rid of casts from one type to the same type. These are useless and can
8827   // be replaced by the operand.
8828   if (DestTy == Src->getType())
8829     return ReplaceInstUsesWith(CI, Src);
8830
8831   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8832     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8833     const Type *DstElTy = DstPTy->getElementType();
8834     const Type *SrcElTy = SrcPTy->getElementType();
8835     
8836     // If the address spaces don't match, don't eliminate the bitcast, which is
8837     // required for changing types.
8838     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8839       return 0;
8840     
8841     // If we are casting a alloca to a pointer to a type of the same
8842     // size, rewrite the allocation instruction to allocate the "right" type.
8843     // There is no need to modify malloc calls because it is their bitcast that
8844     // needs to be cleaned up.
8845     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8846       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8847         return V;
8848     
8849     // If the source and destination are pointers, and this cast is equivalent
8850     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8851     // This can enhance SROA and other transforms that want type-safe pointers.
8852     Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
8853     unsigned NumZeros = 0;
8854     while (SrcElTy != DstElTy && 
8855            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8856            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8857       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8858       ++NumZeros;
8859     }
8860
8861     // If we found a path from the src to dest, create the getelementptr now.
8862     if (SrcElTy == DstElTy) {
8863       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8864       return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8865                                                ((Instruction*) NULL));
8866     }
8867   }
8868
8869   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8870     if (DestVTy->getNumElements() == 1) {
8871       if (!isa<VectorType>(SrcTy)) {
8872         Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
8873         return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
8874                             Constant::getNullValue(Type::getInt32Ty(*Context)));
8875       }
8876       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8877     }
8878   }
8879
8880   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8881     if (SrcVTy->getNumElements() == 1) {
8882       if (!isa<VectorType>(DestTy)) {
8883         Value *Elem = 
8884           Builder->CreateExtractElement(Src,
8885                             Constant::getNullValue(Type::getInt32Ty(*Context)));
8886         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8887       }
8888     }
8889   }
8890
8891   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8892     if (SVI->hasOneUse()) {
8893       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8894       // a bitconvert to a vector with the same # elts.
8895       if (isa<VectorType>(DestTy) && 
8896           cast<VectorType>(DestTy)->getNumElements() ==
8897                 SVI->getType()->getNumElements() &&
8898           SVI->getType()->getNumElements() ==
8899             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8900         CastInst *Tmp;
8901         // If either of the operands is a cast from CI.getType(), then
8902         // evaluating the shuffle in the casted destination's type will allow
8903         // us to eliminate at least one cast.
8904         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8905              Tmp->getOperand(0)->getType() == DestTy) ||
8906             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8907              Tmp->getOperand(0)->getType() == DestTy)) {
8908           Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8909           Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
8910           // Return a new shuffle vector.  Use the same element ID's, as we
8911           // know the vector types match #elts.
8912           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8913         }
8914       }
8915     }
8916   }
8917   return 0;
8918 }
8919
8920 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8921 ///   %C = or %A, %B
8922 ///   %D = select %cond, %C, %A
8923 /// into:
8924 ///   %C = select %cond, %B, 0
8925 ///   %D = or %A, %C
8926 ///
8927 /// Assuming that the specified instruction is an operand to the select, return
8928 /// a bitmask indicating which operands of this instruction are foldable if they
8929 /// equal the other incoming value of the select.
8930 ///
8931 static unsigned GetSelectFoldableOperands(Instruction *I) {
8932   switch (I->getOpcode()) {
8933   case Instruction::Add:
8934   case Instruction::Mul:
8935   case Instruction::And:
8936   case Instruction::Or:
8937   case Instruction::Xor:
8938     return 3;              // Can fold through either operand.
8939   case Instruction::Sub:   // Can only fold on the amount subtracted.
8940   case Instruction::Shl:   // Can only fold on the shift amount.
8941   case Instruction::LShr:
8942   case Instruction::AShr:
8943     return 1;
8944   default:
8945     return 0;              // Cannot fold
8946   }
8947 }
8948
8949 /// GetSelectFoldableConstant - For the same transformation as the previous
8950 /// function, return the identity constant that goes into the select.
8951 static Constant *GetSelectFoldableConstant(Instruction *I,
8952                                            LLVMContext *Context) {
8953   switch (I->getOpcode()) {
8954   default: llvm_unreachable("This cannot happen!");
8955   case Instruction::Add:
8956   case Instruction::Sub:
8957   case Instruction::Or:
8958   case Instruction::Xor:
8959   case Instruction::Shl:
8960   case Instruction::LShr:
8961   case Instruction::AShr:
8962     return Constant::getNullValue(I->getType());
8963   case Instruction::And:
8964     return Constant::getAllOnesValue(I->getType());
8965   case Instruction::Mul:
8966     return ConstantInt::get(I->getType(), 1);
8967   }
8968 }
8969
8970 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8971 /// have the same opcode and only one use each.  Try to simplify this.
8972 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8973                                           Instruction *FI) {
8974   if (TI->getNumOperands() == 1) {
8975     // If this is a non-volatile load or a cast from the same type,
8976     // merge.
8977     if (TI->isCast()) {
8978       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8979         return 0;
8980     } else {
8981       return 0;  // unknown unary op.
8982     }
8983
8984     // Fold this by inserting a select from the input values.
8985     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8986                                           FI->getOperand(0), SI.getName()+".v");
8987     InsertNewInstBefore(NewSI, SI);
8988     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8989                             TI->getType());
8990   }
8991
8992   // Only handle binary operators here.
8993   if (!isa<BinaryOperator>(TI))
8994     return 0;
8995
8996   // Figure out if the operations have any operands in common.
8997   Value *MatchOp, *OtherOpT, *OtherOpF;
8998   bool MatchIsOpZero;
8999   if (TI->getOperand(0) == FI->getOperand(0)) {
9000     MatchOp  = TI->getOperand(0);
9001     OtherOpT = TI->getOperand(1);
9002     OtherOpF = FI->getOperand(1);
9003     MatchIsOpZero = true;
9004   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9005     MatchOp  = TI->getOperand(1);
9006     OtherOpT = TI->getOperand(0);
9007     OtherOpF = FI->getOperand(0);
9008     MatchIsOpZero = false;
9009   } else if (!TI->isCommutative()) {
9010     return 0;
9011   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9012     MatchOp  = TI->getOperand(0);
9013     OtherOpT = TI->getOperand(1);
9014     OtherOpF = FI->getOperand(0);
9015     MatchIsOpZero = true;
9016   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9017     MatchOp  = TI->getOperand(1);
9018     OtherOpT = TI->getOperand(0);
9019     OtherOpF = FI->getOperand(1);
9020     MatchIsOpZero = true;
9021   } else {
9022     return 0;
9023   }
9024
9025   // If we reach here, they do have operations in common.
9026   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9027                                          OtherOpF, SI.getName()+".v");
9028   InsertNewInstBefore(NewSI, SI);
9029
9030   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9031     if (MatchIsOpZero)
9032       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9033     else
9034       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9035   }
9036   llvm_unreachable("Shouldn't get here");
9037   return 0;
9038 }
9039
9040 static bool isSelect01(Constant *C1, Constant *C2) {
9041   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9042   if (!C1I)
9043     return false;
9044   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9045   if (!C2I)
9046     return false;
9047   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9048 }
9049
9050 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9051 /// facilitate further optimization.
9052 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9053                                             Value *FalseVal) {
9054   // See the comment above GetSelectFoldableOperands for a description of the
9055   // transformation we are doing here.
9056   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9057     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9058         !isa<Constant>(FalseVal)) {
9059       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9060         unsigned OpToFold = 0;
9061         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9062           OpToFold = 1;
9063         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9064           OpToFold = 2;
9065         }
9066
9067         if (OpToFold) {
9068           Constant *C = GetSelectFoldableConstant(TVI, Context);
9069           Value *OOp = TVI->getOperand(2-OpToFold);
9070           // Avoid creating select between 2 constants unless it's selecting
9071           // between 0 and 1.
9072           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9073             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9074             InsertNewInstBefore(NewSel, SI);
9075             NewSel->takeName(TVI);
9076             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9077               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9078             llvm_unreachable("Unknown instruction!!");
9079           }
9080         }
9081       }
9082     }
9083   }
9084
9085   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9086     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9087         !isa<Constant>(TrueVal)) {
9088       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9089         unsigned OpToFold = 0;
9090         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9091           OpToFold = 1;
9092         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9093           OpToFold = 2;
9094         }
9095
9096         if (OpToFold) {
9097           Constant *C = GetSelectFoldableConstant(FVI, Context);
9098           Value *OOp = FVI->getOperand(2-OpToFold);
9099           // Avoid creating select between 2 constants unless it's selecting
9100           // between 0 and 1.
9101           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9102             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9103             InsertNewInstBefore(NewSel, SI);
9104             NewSel->takeName(FVI);
9105             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9106               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9107             llvm_unreachable("Unknown instruction!!");
9108           }
9109         }
9110       }
9111     }
9112   }
9113
9114   return 0;
9115 }
9116
9117 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9118 /// ICmpInst as its first operand.
9119 ///
9120 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9121                                                    ICmpInst *ICI) {
9122   bool Changed = false;
9123   ICmpInst::Predicate Pred = ICI->getPredicate();
9124   Value *CmpLHS = ICI->getOperand(0);
9125   Value *CmpRHS = ICI->getOperand(1);
9126   Value *TrueVal = SI.getTrueValue();
9127   Value *FalseVal = SI.getFalseValue();
9128
9129   // Check cases where the comparison is with a constant that
9130   // can be adjusted to fit the min/max idiom. We may edit ICI in
9131   // place here, so make sure the select is the only user.
9132   if (ICI->hasOneUse())
9133     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9134       switch (Pred) {
9135       default: break;
9136       case ICmpInst::ICMP_ULT:
9137       case ICmpInst::ICMP_SLT: {
9138         // X < MIN ? T : F  -->  F
9139         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9140           return ReplaceInstUsesWith(SI, FalseVal);
9141         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9142         Constant *AdjustedRHS = SubOne(CI);
9143         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9144             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9145           Pred = ICmpInst::getSwappedPredicate(Pred);
9146           CmpRHS = AdjustedRHS;
9147           std::swap(FalseVal, TrueVal);
9148           ICI->setPredicate(Pred);
9149           ICI->setOperand(1, CmpRHS);
9150           SI.setOperand(1, TrueVal);
9151           SI.setOperand(2, FalseVal);
9152           Changed = true;
9153         }
9154         break;
9155       }
9156       case ICmpInst::ICMP_UGT:
9157       case ICmpInst::ICMP_SGT: {
9158         // X > MAX ? T : F  -->  F
9159         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9160           return ReplaceInstUsesWith(SI, FalseVal);
9161         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9162         Constant *AdjustedRHS = AddOne(CI);
9163         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9164             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9165           Pred = ICmpInst::getSwappedPredicate(Pred);
9166           CmpRHS = AdjustedRHS;
9167           std::swap(FalseVal, TrueVal);
9168           ICI->setPredicate(Pred);
9169           ICI->setOperand(1, CmpRHS);
9170           SI.setOperand(1, TrueVal);
9171           SI.setOperand(2, FalseVal);
9172           Changed = true;
9173         }
9174         break;
9175       }
9176       }
9177
9178       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9179       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9180       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9181       if (match(TrueVal, m_ConstantInt<-1>()) &&
9182           match(FalseVal, m_ConstantInt<0>()))
9183         Pred = ICI->getPredicate();
9184       else if (match(TrueVal, m_ConstantInt<0>()) &&
9185                match(FalseVal, m_ConstantInt<-1>()))
9186         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9187       
9188       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9189         // If we are just checking for a icmp eq of a single bit and zext'ing it
9190         // to an integer, then shift the bit to the appropriate place and then
9191         // cast to integer to avoid the comparison.
9192         const APInt &Op1CV = CI->getValue();
9193     
9194         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9195         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9196         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9197             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9198           Value *In = ICI->getOperand(0);
9199           Value *Sh = ConstantInt::get(In->getType(),
9200                                        In->getType()->getScalarSizeInBits()-1);
9201           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9202                                                         In->getName()+".lobit"),
9203                                    *ICI);
9204           if (In->getType() != SI.getType())
9205             In = CastInst::CreateIntegerCast(In, SI.getType(),
9206                                              true/*SExt*/, "tmp", ICI);
9207     
9208           if (Pred == ICmpInst::ICMP_SGT)
9209             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9210                                        In->getName()+".not"), *ICI);
9211     
9212           return ReplaceInstUsesWith(SI, In);
9213         }
9214       }
9215     }
9216
9217   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9218     // Transform (X == Y) ? X : Y  -> Y
9219     if (Pred == ICmpInst::ICMP_EQ)
9220       return ReplaceInstUsesWith(SI, FalseVal);
9221     // Transform (X != Y) ? X : Y  -> X
9222     if (Pred == ICmpInst::ICMP_NE)
9223       return ReplaceInstUsesWith(SI, TrueVal);
9224     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9225
9226   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9227     // Transform (X == Y) ? Y : X  -> X
9228     if (Pred == ICmpInst::ICMP_EQ)
9229       return ReplaceInstUsesWith(SI, FalseVal);
9230     // Transform (X != Y) ? Y : X  -> Y
9231     if (Pred == ICmpInst::ICMP_NE)
9232       return ReplaceInstUsesWith(SI, TrueVal);
9233     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9234   }
9235
9236   /// NOTE: if we wanted to, this is where to detect integer ABS
9237
9238   return Changed ? &SI : 0;
9239 }
9240
9241 /// isDefinedInBB - Return true if the value is an instruction defined in the
9242 /// specified basicblock.
9243 static bool isDefinedInBB(const Value *V, const BasicBlock *BB) {
9244   const Instruction *I = dyn_cast<Instruction>(V);
9245   return I != 0 && I->getParent() == BB;
9246 }
9247
9248
9249 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9250   Value *CondVal = SI.getCondition();
9251   Value *TrueVal = SI.getTrueValue();
9252   Value *FalseVal = SI.getFalseValue();
9253
9254   // select true, X, Y  -> X
9255   // select false, X, Y -> Y
9256   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9257     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9258
9259   // select C, X, X -> X
9260   if (TrueVal == FalseVal)
9261     return ReplaceInstUsesWith(SI, TrueVal);
9262
9263   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9264     return ReplaceInstUsesWith(SI, FalseVal);
9265   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9266     return ReplaceInstUsesWith(SI, TrueVal);
9267   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9268     if (isa<Constant>(TrueVal))
9269       return ReplaceInstUsesWith(SI, TrueVal);
9270     else
9271       return ReplaceInstUsesWith(SI, FalseVal);
9272   }
9273
9274   if (SI.getType() == Type::getInt1Ty(*Context)) {
9275     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9276       if (C->getZExtValue()) {
9277         // Change: A = select B, true, C --> A = or B, C
9278         return BinaryOperator::CreateOr(CondVal, FalseVal);
9279       } else {
9280         // Change: A = select B, false, C --> A = and !B, C
9281         Value *NotCond =
9282           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9283                                              "not."+CondVal->getName()), SI);
9284         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9285       }
9286     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9287       if (C->getZExtValue() == false) {
9288         // Change: A = select B, C, false --> A = and B, C
9289         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9290       } else {
9291         // Change: A = select B, C, true --> A = or !B, C
9292         Value *NotCond =
9293           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9294                                              "not."+CondVal->getName()), SI);
9295         return BinaryOperator::CreateOr(NotCond, TrueVal);
9296       }
9297     }
9298     
9299     // select a, b, a  -> a&b
9300     // select a, a, b  -> a|b
9301     if (CondVal == TrueVal)
9302       return BinaryOperator::CreateOr(CondVal, FalseVal);
9303     else if (CondVal == FalseVal)
9304       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9305   }
9306
9307   // Selecting between two integer constants?
9308   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9309     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9310       // select C, 1, 0 -> zext C to int
9311       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9312         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9313       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9314         // select C, 0, 1 -> zext !C to int
9315         Value *NotCond =
9316           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9317                                                "not."+CondVal->getName()), SI);
9318         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9319       }
9320
9321       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9322         // If one of the constants is zero (we know they can't both be) and we
9323         // have an icmp instruction with zero, and we have an 'and' with the
9324         // non-constant value, eliminate this whole mess.  This corresponds to
9325         // cases like this: ((X & 27) ? 27 : 0)
9326         if (TrueValC->isZero() || FalseValC->isZero())
9327           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9328               cast<Constant>(IC->getOperand(1))->isNullValue())
9329             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9330               if (ICA->getOpcode() == Instruction::And &&
9331                   isa<ConstantInt>(ICA->getOperand(1)) &&
9332                   (ICA->getOperand(1) == TrueValC ||
9333                    ICA->getOperand(1) == FalseValC) &&
9334                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9335                 // Okay, now we know that everything is set up, we just don't
9336                 // know whether we have a icmp_ne or icmp_eq and whether the 
9337                 // true or false val is the zero.
9338                 bool ShouldNotVal = !TrueValC->isZero();
9339                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9340                 Value *V = ICA;
9341                 if (ShouldNotVal)
9342                   V = InsertNewInstBefore(BinaryOperator::Create(
9343                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9344                 return ReplaceInstUsesWith(SI, V);
9345               }
9346       }
9347     }
9348
9349   // See if we are selecting two values based on a comparison of the two values.
9350   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9351     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9352       // Transform (X == Y) ? X : Y  -> Y
9353       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9354         // This is not safe in general for floating point:  
9355         // consider X== -0, Y== +0.
9356         // It becomes safe if either operand is a nonzero constant.
9357         ConstantFP *CFPt, *CFPf;
9358         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9359               !CFPt->getValueAPF().isZero()) ||
9360             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9361              !CFPf->getValueAPF().isZero()))
9362         return ReplaceInstUsesWith(SI, FalseVal);
9363       }
9364       // Transform (X != Y) ? X : Y  -> X
9365       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9366         return ReplaceInstUsesWith(SI, TrueVal);
9367       // NOTE: if we wanted to, this is where to detect MIN/MAX
9368
9369     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9370       // Transform (X == Y) ? Y : X  -> X
9371       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9372         // This is not safe in general for floating point:  
9373         // consider X== -0, Y== +0.
9374         // It becomes safe if either operand is a nonzero constant.
9375         ConstantFP *CFPt, *CFPf;
9376         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9377               !CFPt->getValueAPF().isZero()) ||
9378             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9379              !CFPf->getValueAPF().isZero()))
9380           return ReplaceInstUsesWith(SI, FalseVal);
9381       }
9382       // Transform (X != Y) ? Y : X  -> Y
9383       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9384         return ReplaceInstUsesWith(SI, TrueVal);
9385       // NOTE: if we wanted to, this is where to detect MIN/MAX
9386     }
9387     // NOTE: if we wanted to, this is where to detect ABS
9388   }
9389
9390   // See if we are selecting two values based on a comparison of the two values.
9391   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9392     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9393       return Result;
9394
9395   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9396     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9397       if (TI->hasOneUse() && FI->hasOneUse()) {
9398         Instruction *AddOp = 0, *SubOp = 0;
9399
9400         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9401         if (TI->getOpcode() == FI->getOpcode())
9402           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9403             return IV;
9404
9405         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9406         // even legal for FP.
9407         if ((TI->getOpcode() == Instruction::Sub &&
9408              FI->getOpcode() == Instruction::Add) ||
9409             (TI->getOpcode() == Instruction::FSub &&
9410              FI->getOpcode() == Instruction::FAdd)) {
9411           AddOp = FI; SubOp = TI;
9412         } else if ((FI->getOpcode() == Instruction::Sub &&
9413                     TI->getOpcode() == Instruction::Add) ||
9414                    (FI->getOpcode() == Instruction::FSub &&
9415                     TI->getOpcode() == Instruction::FAdd)) {
9416           AddOp = TI; SubOp = FI;
9417         }
9418
9419         if (AddOp) {
9420           Value *OtherAddOp = 0;
9421           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9422             OtherAddOp = AddOp->getOperand(1);
9423           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9424             OtherAddOp = AddOp->getOperand(0);
9425           }
9426
9427           if (OtherAddOp) {
9428             // So at this point we know we have (Y -> OtherAddOp):
9429             //        select C, (add X, Y), (sub X, Z)
9430             Value *NegVal;  // Compute -Z
9431             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9432               NegVal = ConstantExpr::getNeg(C);
9433             } else {
9434               NegVal = InsertNewInstBefore(
9435                     BinaryOperator::CreateNeg(SubOp->getOperand(1),
9436                                               "tmp"), SI);
9437             }
9438
9439             Value *NewTrueOp = OtherAddOp;
9440             Value *NewFalseOp = NegVal;
9441             if (AddOp != TI)
9442               std::swap(NewTrueOp, NewFalseOp);
9443             Instruction *NewSel =
9444               SelectInst::Create(CondVal, NewTrueOp,
9445                                  NewFalseOp, SI.getName() + ".p");
9446
9447             NewSel = InsertNewInstBefore(NewSel, SI);
9448             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9449           }
9450         }
9451       }
9452
9453   // See if we can fold the select into one of our operands.
9454   if (SI.getType()->isInteger()) {
9455     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9456     if (FoldI)
9457       return FoldI;
9458   }
9459
9460   // See if we can fold the select into a phi node.  The true/false values have
9461   // to be live in the predecessor blocks.  If they are instructions in SI's
9462   // block, we can't map to the predecessor.
9463   if (isa<PHINode>(SI.getCondition()) &&
9464       (!isDefinedInBB(SI.getTrueValue(), SI.getParent()) ||
9465        isa<PHINode>(SI.getTrueValue())) &&
9466       (!isDefinedInBB(SI.getFalseValue(), SI.getParent()) ||
9467        isa<PHINode>(SI.getFalseValue())))
9468     if (Instruction *NV = FoldOpIntoPhi(SI))
9469       return NV;
9470
9471   if (BinaryOperator::isNot(CondVal)) {
9472     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9473     SI.setOperand(1, FalseVal);
9474     SI.setOperand(2, TrueVal);
9475     return &SI;
9476   }
9477
9478   return 0;
9479 }
9480
9481 /// EnforceKnownAlignment - If the specified pointer points to an object that
9482 /// we control, modify the object's alignment to PrefAlign. This isn't
9483 /// often possible though. If alignment is important, a more reliable approach
9484 /// is to simply align all global variables and allocation instructions to
9485 /// their preferred alignment from the beginning.
9486 ///
9487 static unsigned EnforceKnownAlignment(Value *V,
9488                                       unsigned Align, unsigned PrefAlign) {
9489
9490   User *U = dyn_cast<User>(V);
9491   if (!U) return Align;
9492
9493   switch (Operator::getOpcode(U)) {
9494   default: break;
9495   case Instruction::BitCast:
9496     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9497   case Instruction::GetElementPtr: {
9498     // If all indexes are zero, it is just the alignment of the base pointer.
9499     bool AllZeroOperands = true;
9500     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9501       if (!isa<Constant>(*i) ||
9502           !cast<Constant>(*i)->isNullValue()) {
9503         AllZeroOperands = false;
9504         break;
9505       }
9506
9507     if (AllZeroOperands) {
9508       // Treat this like a bitcast.
9509       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9510     }
9511     break;
9512   }
9513   }
9514
9515   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9516     // If there is a large requested alignment and we can, bump up the alignment
9517     // of the global.
9518     if (!GV->isDeclaration()) {
9519       if (GV->getAlignment() >= PrefAlign)
9520         Align = GV->getAlignment();
9521       else {
9522         GV->setAlignment(PrefAlign);
9523         Align = PrefAlign;
9524       }
9525     }
9526   } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9527     // If there is a requested alignment and if this is an alloca, round up.
9528     if (AI->getAlignment() >= PrefAlign)
9529       Align = AI->getAlignment();
9530     else {
9531       AI->setAlignment(PrefAlign);
9532       Align = PrefAlign;
9533     }
9534   }
9535
9536   return Align;
9537 }
9538
9539 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9540 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9541 /// and it is more than the alignment of the ultimate object, see if we can
9542 /// increase the alignment of the ultimate object, making this check succeed.
9543 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9544                                                   unsigned PrefAlign) {
9545   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9546                       sizeof(PrefAlign) * CHAR_BIT;
9547   APInt Mask = APInt::getAllOnesValue(BitWidth);
9548   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9549   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9550   unsigned TrailZ = KnownZero.countTrailingOnes();
9551   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9552
9553   if (PrefAlign > Align)
9554     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9555   
9556     // We don't need to make any adjustment.
9557   return Align;
9558 }
9559
9560 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9561   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9562   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9563   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9564   unsigned CopyAlign = MI->getAlignment();
9565
9566   if (CopyAlign < MinAlign) {
9567     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 
9568                                              MinAlign, false));
9569     return MI;
9570   }
9571   
9572   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9573   // load/store.
9574   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9575   if (MemOpLength == 0) return 0;
9576   
9577   // Source and destination pointer types are always "i8*" for intrinsic.  See
9578   // if the size is something we can handle with a single primitive load/store.
9579   // A single load+store correctly handles overlapping memory in the memmove
9580   // case.
9581   unsigned Size = MemOpLength->getZExtValue();
9582   if (Size == 0) return MI;  // Delete this mem transfer.
9583   
9584   if (Size > 8 || (Size&(Size-1)))
9585     return 0;  // If not 1/2/4/8 bytes, exit.
9586   
9587   // Use an integer load+store unless we can find something better.
9588   Type *NewPtrTy =
9589                 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
9590   
9591   // Memcpy forces the use of i8* for the source and destination.  That means
9592   // that if you're using memcpy to move one double around, you'll get a cast
9593   // from double* to i8*.  We'd much rather use a double load+store rather than
9594   // an i64 load+store, here because this improves the odds that the source or
9595   // dest address will be promotable.  See if we can find a better type than the
9596   // integer datatype.
9597   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9598     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9599     if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9600       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9601       // down through these levels if so.
9602       while (!SrcETy->isSingleValueType()) {
9603         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9604           if (STy->getNumElements() == 1)
9605             SrcETy = STy->getElementType(0);
9606           else
9607             break;
9608         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9609           if (ATy->getNumElements() == 1)
9610             SrcETy = ATy->getElementType();
9611           else
9612             break;
9613         } else
9614           break;
9615       }
9616       
9617       if (SrcETy->isSingleValueType())
9618         NewPtrTy = PointerType::getUnqual(SrcETy);
9619     }
9620   }
9621   
9622   
9623   // If the memcpy/memmove provides better alignment info than we can
9624   // infer, use it.
9625   SrcAlign = std::max(SrcAlign, CopyAlign);
9626   DstAlign = std::max(DstAlign, CopyAlign);
9627   
9628   Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9629   Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
9630   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9631   InsertNewInstBefore(L, *MI);
9632   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9633
9634   // Set the size of the copy to 0, it will be deleted on the next iteration.
9635   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9636   return MI;
9637 }
9638
9639 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9640   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9641   if (MI->getAlignment() < Alignment) {
9642     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9643                                              Alignment, false));
9644     return MI;
9645   }
9646   
9647   // Extract the length and alignment and fill if they are constant.
9648   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9649   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9650   if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
9651     return 0;
9652   uint64_t Len = LenC->getZExtValue();
9653   Alignment = MI->getAlignment();
9654   
9655   // If the length is zero, this is a no-op
9656   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9657   
9658   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9659   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9660     const Type *ITy = IntegerType::get(*Context, Len*8);  // n=1 -> i8.
9661     
9662     Value *Dest = MI->getDest();
9663     Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
9664
9665     // Alignment 0 is identity for alignment 1 for memset, but not store.
9666     if (Alignment == 0) Alignment = 1;
9667     
9668     // Extract the fill value and store.
9669     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9670     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9671                                       Dest, false, Alignment), *MI);
9672     
9673     // Set the size of the copy to 0, it will be deleted on the next iteration.
9674     MI->setLength(Constant::getNullValue(LenC->getType()));
9675     return MI;
9676   }
9677
9678   return 0;
9679 }
9680
9681
9682 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9683 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9684 /// the heavy lifting.
9685 ///
9686 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9687   // If the caller function is nounwind, mark the call as nounwind, even if the
9688   // callee isn't.
9689   if (CI.getParent()->getParent()->doesNotThrow() &&
9690       !CI.doesNotThrow()) {
9691     CI.setDoesNotThrow();
9692     return &CI;
9693   }
9694   
9695   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9696   if (!II) return visitCallSite(&CI);
9697   
9698   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9699   // visitCallSite.
9700   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9701     bool Changed = false;
9702
9703     // memmove/cpy/set of zero bytes is a noop.
9704     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9705       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9706
9707       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9708         if (CI->getZExtValue() == 1) {
9709           // Replace the instruction with just byte operations.  We would
9710           // transform other cases to loads/stores, but we don't know if
9711           // alignment is sufficient.
9712         }
9713     }
9714
9715     // If we have a memmove and the source operation is a constant global,
9716     // then the source and dest pointers can't alias, so we can change this
9717     // into a call to memcpy.
9718     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9719       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9720         if (GVSrc->isConstant()) {
9721           Module *M = CI.getParent()->getParent()->getParent();
9722           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9723           const Type *Tys[1];
9724           Tys[0] = CI.getOperand(3)->getType();
9725           CI.setOperand(0, 
9726                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9727           Changed = true;
9728         }
9729
9730       // memmove(x,x,size) -> noop.
9731       if (MMI->getSource() == MMI->getDest())
9732         return EraseInstFromFunction(CI);
9733     }
9734
9735     // If we can determine a pointer alignment that is bigger than currently
9736     // set, update the alignment.
9737     if (isa<MemTransferInst>(MI)) {
9738       if (Instruction *I = SimplifyMemTransfer(MI))
9739         return I;
9740     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9741       if (Instruction *I = SimplifyMemSet(MSI))
9742         return I;
9743     }
9744           
9745     if (Changed) return II;
9746   }
9747   
9748   switch (II->getIntrinsicID()) {
9749   default: break;
9750   case Intrinsic::bswap:
9751     // bswap(bswap(x)) -> x
9752     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9753       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9754         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9755     break;
9756   case Intrinsic::ppc_altivec_lvx:
9757   case Intrinsic::ppc_altivec_lvxl:
9758   case Intrinsic::x86_sse_loadu_ps:
9759   case Intrinsic::x86_sse2_loadu_pd:
9760   case Intrinsic::x86_sse2_loadu_dq:
9761     // Turn PPC lvx     -> load if the pointer is known aligned.
9762     // Turn X86 loadups -> load if the pointer is known aligned.
9763     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9764       Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9765                                          PointerType::getUnqual(II->getType()));
9766       return new LoadInst(Ptr);
9767     }
9768     break;
9769   case Intrinsic::ppc_altivec_stvx:
9770   case Intrinsic::ppc_altivec_stvxl:
9771     // Turn stvx -> store if the pointer is known aligned.
9772     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9773       const Type *OpPtrTy = 
9774         PointerType::getUnqual(II->getOperand(1)->getType());
9775       Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
9776       return new StoreInst(II->getOperand(1), Ptr);
9777     }
9778     break;
9779   case Intrinsic::x86_sse_storeu_ps:
9780   case Intrinsic::x86_sse2_storeu_pd:
9781   case Intrinsic::x86_sse2_storeu_dq:
9782     // Turn X86 storeu -> store if the pointer is known aligned.
9783     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9784       const Type *OpPtrTy = 
9785         PointerType::getUnqual(II->getOperand(2)->getType());
9786       Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
9787       return new StoreInst(II->getOperand(2), Ptr);
9788     }
9789     break;
9790     
9791   case Intrinsic::x86_sse_cvttss2si: {
9792     // These intrinsics only demands the 0th element of its input vector.  If
9793     // we can simplify the input based on that, do so now.
9794     unsigned VWidth =
9795       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9796     APInt DemandedElts(VWidth, 1);
9797     APInt UndefElts(VWidth, 0);
9798     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9799                                               UndefElts)) {
9800       II->setOperand(1, V);
9801       return II;
9802     }
9803     break;
9804   }
9805     
9806   case Intrinsic::ppc_altivec_vperm:
9807     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9808     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9809       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9810       
9811       // Check that all of the elements are integer constants or undefs.
9812       bool AllEltsOk = true;
9813       for (unsigned i = 0; i != 16; ++i) {
9814         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9815             !isa<UndefValue>(Mask->getOperand(i))) {
9816           AllEltsOk = false;
9817           break;
9818         }
9819       }
9820       
9821       if (AllEltsOk) {
9822         // Cast the input vectors to byte vectors.
9823         Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9824         Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
9825         Value *Result = UndefValue::get(Op0->getType());
9826         
9827         // Only extract each element once.
9828         Value *ExtractedElts[32];
9829         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9830         
9831         for (unsigned i = 0; i != 16; ++i) {
9832           if (isa<UndefValue>(Mask->getOperand(i)))
9833             continue;
9834           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9835           Idx &= 31;  // Match the hardware behavior.
9836           
9837           if (ExtractedElts[Idx] == 0) {
9838             ExtractedElts[Idx] = 
9839               Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1, 
9840                   ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9841                                             "tmp");
9842           }
9843         
9844           // Insert this value into the result vector.
9845           Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9846                          ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9847                                                 "tmp");
9848         }
9849         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9850       }
9851     }
9852     break;
9853
9854   case Intrinsic::stackrestore: {
9855     // If the save is right next to the restore, remove the restore.  This can
9856     // happen when variable allocas are DCE'd.
9857     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9858       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9859         BasicBlock::iterator BI = SS;
9860         if (&*++BI == II)
9861           return EraseInstFromFunction(CI);
9862       }
9863     }
9864     
9865     // Scan down this block to see if there is another stack restore in the
9866     // same block without an intervening call/alloca.
9867     BasicBlock::iterator BI = II;
9868     TerminatorInst *TI = II->getParent()->getTerminator();
9869     bool CannotRemove = false;
9870     for (++BI; &*BI != TI; ++BI) {
9871       if (isa<AllocaInst>(BI) || isMalloc(BI)) {
9872         CannotRemove = true;
9873         break;
9874       }
9875       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9876         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9877           // If there is a stackrestore below this one, remove this one.
9878           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9879             return EraseInstFromFunction(CI);
9880           // Otherwise, ignore the intrinsic.
9881         } else {
9882           // If we found a non-intrinsic call, we can't remove the stack
9883           // restore.
9884           CannotRemove = true;
9885           break;
9886         }
9887       }
9888     }
9889     
9890     // If the stack restore is in a return/unwind block and if there are no
9891     // allocas or calls between the restore and the return, nuke the restore.
9892     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9893       return EraseInstFromFunction(CI);
9894     break;
9895   }
9896   }
9897
9898   return visitCallSite(II);
9899 }
9900
9901 // InvokeInst simplification
9902 //
9903 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9904   return visitCallSite(&II);
9905 }
9906
9907 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9908 /// passed through the varargs area, we can eliminate the use of the cast.
9909 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9910                                          const CastInst * const CI,
9911                                          const TargetData * const TD,
9912                                          const int ix) {
9913   if (!CI->isLosslessCast())
9914     return false;
9915
9916   // The size of ByVal arguments is derived from the type, so we
9917   // can't change to a type with a different size.  If the size were
9918   // passed explicitly we could avoid this check.
9919   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9920     return true;
9921
9922   const Type* SrcTy = 
9923             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9924   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9925   if (!SrcTy->isSized() || !DstTy->isSized())
9926     return false;
9927   if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
9928     return false;
9929   return true;
9930 }
9931
9932 // visitCallSite - Improvements for call and invoke instructions.
9933 //
9934 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9935   bool Changed = false;
9936
9937   // If the callee is a constexpr cast of a function, attempt to move the cast
9938   // to the arguments of the call/invoke.
9939   if (transformConstExprCastCall(CS)) return 0;
9940
9941   Value *Callee = CS.getCalledValue();
9942
9943   if (Function *CalleeF = dyn_cast<Function>(Callee))
9944     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9945       Instruction *OldCall = CS.getInstruction();
9946       // If the call and callee calling conventions don't match, this call must
9947       // be unreachable, as the call is undefined.
9948       new StoreInst(ConstantInt::getTrue(*Context),
9949                 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), 
9950                                   OldCall);
9951       if (!OldCall->use_empty())
9952         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9953       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
9954         return EraseInstFromFunction(*OldCall);
9955       return 0;
9956     }
9957
9958   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9959     // This instruction is not reachable, just remove it.  We insert a store to
9960     // undef so that we know that this code is not reachable, despite the fact
9961     // that we can't modify the CFG here.
9962     new StoreInst(ConstantInt::getTrue(*Context),
9963                UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
9964                   CS.getInstruction());
9965
9966     if (!CS.getInstruction()->use_empty())
9967       CS.getInstruction()->
9968         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9969
9970     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9971       // Don't break the CFG, insert a dummy cond branch.
9972       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9973                          ConstantInt::getTrue(*Context), II);
9974     }
9975     return EraseInstFromFunction(*CS.getInstruction());
9976   }
9977
9978   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9979     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9980       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9981         return transformCallThroughTrampoline(CS);
9982
9983   const PointerType *PTy = cast<PointerType>(Callee->getType());
9984   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9985   if (FTy->isVarArg()) {
9986     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9987     // See if we can optimize any arguments passed through the varargs area of
9988     // the call.
9989     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9990            E = CS.arg_end(); I != E; ++I, ++ix) {
9991       CastInst *CI = dyn_cast<CastInst>(*I);
9992       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9993         *I = CI->getOperand(0);
9994         Changed = true;
9995       }
9996     }
9997   }
9998
9999   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10000     // Inline asm calls cannot throw - mark them 'nounwind'.
10001     CS.setDoesNotThrow();
10002     Changed = true;
10003   }
10004
10005   return Changed ? CS.getInstruction() : 0;
10006 }
10007
10008 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10009 // attempt to move the cast to the arguments of the call/invoke.
10010 //
10011 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10012   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10013   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10014   if (CE->getOpcode() != Instruction::BitCast || 
10015       !isa<Function>(CE->getOperand(0)))
10016     return false;
10017   Function *Callee = cast<Function>(CE->getOperand(0));
10018   Instruction *Caller = CS.getInstruction();
10019   const AttrListPtr &CallerPAL = CS.getAttributes();
10020
10021   // Okay, this is a cast from a function to a different type.  Unless doing so
10022   // would cause a type conversion of one of our arguments, change this call to
10023   // be a direct call with arguments casted to the appropriate types.
10024   //
10025   const FunctionType *FT = Callee->getFunctionType();
10026   const Type *OldRetTy = Caller->getType();
10027   const Type *NewRetTy = FT->getReturnType();
10028
10029   if (isa<StructType>(NewRetTy))
10030     return false; // TODO: Handle multiple return values.
10031
10032   // Check to see if we are changing the return type...
10033   if (OldRetTy != NewRetTy) {
10034     if (Callee->isDeclaration() &&
10035         // Conversion is ok if changing from one pointer type to another or from
10036         // a pointer to an integer of the same size.
10037         !((isa<PointerType>(OldRetTy) || !TD ||
10038            OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
10039           (isa<PointerType>(NewRetTy) || !TD ||
10040            NewRetTy == TD->getIntPtrType(Caller->getContext()))))
10041       return false;   // Cannot transform this return value.
10042
10043     if (!Caller->use_empty() &&
10044         // void -> non-void is handled specially
10045         NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
10046       return false;   // Cannot transform this return value.
10047
10048     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10049       Attributes RAttrs = CallerPAL.getRetAttributes();
10050       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10051         return false;   // Attribute not compatible with transformed value.
10052     }
10053
10054     // If the callsite is an invoke instruction, and the return value is used by
10055     // a PHI node in a successor, we cannot change the return type of the call
10056     // because there is no place to put the cast instruction (without breaking
10057     // the critical edge).  Bail out in this case.
10058     if (!Caller->use_empty())
10059       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10060         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10061              UI != E; ++UI)
10062           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10063             if (PN->getParent() == II->getNormalDest() ||
10064                 PN->getParent() == II->getUnwindDest())
10065               return false;
10066   }
10067
10068   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10069   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10070
10071   CallSite::arg_iterator AI = CS.arg_begin();
10072   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10073     const Type *ParamTy = FT->getParamType(i);
10074     const Type *ActTy = (*AI)->getType();
10075
10076     if (!CastInst::isCastable(ActTy, ParamTy))
10077       return false;   // Cannot transform this parameter value.
10078
10079     if (CallerPAL.getParamAttributes(i + 1) 
10080         & Attribute::typeIncompatible(ParamTy))
10081       return false;   // Attribute not compatible with transformed value.
10082
10083     // Converting from one pointer type to another or between a pointer and an
10084     // integer of the same size is safe even if we do not have a body.
10085     bool isConvertible = ActTy == ParamTy ||
10086       (TD && ((isa<PointerType>(ParamTy) ||
10087       ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10088               (isa<PointerType>(ActTy) ||
10089               ActTy == TD->getIntPtrType(Caller->getContext()))));
10090     if (Callee->isDeclaration() && !isConvertible) return false;
10091   }
10092
10093   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10094       Callee->isDeclaration())
10095     return false;   // Do not delete arguments unless we have a function body.
10096
10097   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10098       !CallerPAL.isEmpty())
10099     // In this case we have more arguments than the new function type, but we
10100     // won't be dropping them.  Check that these extra arguments have attributes
10101     // that are compatible with being a vararg call argument.
10102     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10103       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10104         break;
10105       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10106       if (PAttrs & Attribute::VarArgsIncompatible)
10107         return false;
10108     }
10109
10110   // Okay, we decided that this is a safe thing to do: go ahead and start
10111   // inserting cast instructions as necessary...
10112   std::vector<Value*> Args;
10113   Args.reserve(NumActualArgs);
10114   SmallVector<AttributeWithIndex, 8> attrVec;
10115   attrVec.reserve(NumCommonArgs);
10116
10117   // Get any return attributes.
10118   Attributes RAttrs = CallerPAL.getRetAttributes();
10119
10120   // If the return value is not being used, the type may not be compatible
10121   // with the existing attributes.  Wipe out any problematic attributes.
10122   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10123
10124   // Add the new return attributes.
10125   if (RAttrs)
10126     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10127
10128   AI = CS.arg_begin();
10129   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10130     const Type *ParamTy = FT->getParamType(i);
10131     if ((*AI)->getType() == ParamTy) {
10132       Args.push_back(*AI);
10133     } else {
10134       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10135           false, ParamTy, false);
10136       Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
10137     }
10138
10139     // Add any parameter attributes.
10140     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10141       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10142   }
10143
10144   // If the function takes more arguments than the call was taking, add them
10145   // now.
10146   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10147     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10148
10149   // If we are removing arguments to the function, emit an obnoxious warning.
10150   if (FT->getNumParams() < NumActualArgs) {
10151     if (!FT->isVarArg()) {
10152       errs() << "WARNING: While resolving call to function '"
10153              << Callee->getName() << "' arguments were dropped!\n";
10154     } else {
10155       // Add all of the arguments in their promoted form to the arg list.
10156       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10157         const Type *PTy = getPromotedType((*AI)->getType());
10158         if (PTy != (*AI)->getType()) {
10159           // Must promote to pass through va_arg area!
10160           Instruction::CastOps opcode =
10161             CastInst::getCastOpcode(*AI, false, PTy, false);
10162           Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
10163         } else {
10164           Args.push_back(*AI);
10165         }
10166
10167         // Add any parameter attributes.
10168         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10169           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10170       }
10171     }
10172   }
10173
10174   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10175     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10176
10177   if (NewRetTy == Type::getVoidTy(*Context))
10178     Caller->setName("");   // Void type should not have a name.
10179
10180   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10181                                                      attrVec.end());
10182
10183   Instruction *NC;
10184   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10185     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10186                             Args.begin(), Args.end(),
10187                             Caller->getName(), Caller);
10188     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10189     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10190   } else {
10191     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10192                           Caller->getName(), Caller);
10193     CallInst *CI = cast<CallInst>(Caller);
10194     if (CI->isTailCall())
10195       cast<CallInst>(NC)->setTailCall();
10196     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10197     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10198   }
10199
10200   // Insert a cast of the return type as necessary.
10201   Value *NV = NC;
10202   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10203     if (NV->getType() != Type::getVoidTy(*Context)) {
10204       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10205                                                             OldRetTy, false);
10206       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10207
10208       // If this is an invoke instruction, we should insert it after the first
10209       // non-phi, instruction in the normal successor block.
10210       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10211         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10212         InsertNewInstBefore(NC, *I);
10213       } else {
10214         // Otherwise, it's a call, just insert cast right after the call instr
10215         InsertNewInstBefore(NC, *Caller);
10216       }
10217       Worklist.AddUsersToWorkList(*Caller);
10218     } else {
10219       NV = UndefValue::get(Caller->getType());
10220     }
10221   }
10222
10223   
10224   if (!Caller->use_empty())
10225     Caller->replaceAllUsesWith(NV);
10226   
10227   EraseInstFromFunction(*Caller);
10228   return true;
10229 }
10230
10231 // transformCallThroughTrampoline - Turn a call to a function created by the
10232 // init_trampoline intrinsic into a direct call to the underlying function.
10233 //
10234 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10235   Value *Callee = CS.getCalledValue();
10236   const PointerType *PTy = cast<PointerType>(Callee->getType());
10237   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10238   const AttrListPtr &Attrs = CS.getAttributes();
10239
10240   // If the call already has the 'nest' attribute somewhere then give up -
10241   // otherwise 'nest' would occur twice after splicing in the chain.
10242   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10243     return 0;
10244
10245   IntrinsicInst *Tramp =
10246     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10247
10248   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10249   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10250   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10251
10252   const AttrListPtr &NestAttrs = NestF->getAttributes();
10253   if (!NestAttrs.isEmpty()) {
10254     unsigned NestIdx = 1;
10255     const Type *NestTy = 0;
10256     Attributes NestAttr = Attribute::None;
10257
10258     // Look for a parameter marked with the 'nest' attribute.
10259     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10260          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10261       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10262         // Record the parameter type and any other attributes.
10263         NestTy = *I;
10264         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10265         break;
10266       }
10267
10268     if (NestTy) {
10269       Instruction *Caller = CS.getInstruction();
10270       std::vector<Value*> NewArgs;
10271       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10272
10273       SmallVector<AttributeWithIndex, 8> NewAttrs;
10274       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10275
10276       // Insert the nest argument into the call argument list, which may
10277       // mean appending it.  Likewise for attributes.
10278
10279       // Add any result attributes.
10280       if (Attributes Attr = Attrs.getRetAttributes())
10281         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10282
10283       {
10284         unsigned Idx = 1;
10285         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10286         do {
10287           if (Idx == NestIdx) {
10288             // Add the chain argument and attributes.
10289             Value *NestVal = Tramp->getOperand(3);
10290             if (NestVal->getType() != NestTy)
10291               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10292             NewArgs.push_back(NestVal);
10293             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10294           }
10295
10296           if (I == E)
10297             break;
10298
10299           // Add the original argument and attributes.
10300           NewArgs.push_back(*I);
10301           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10302             NewAttrs.push_back
10303               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10304
10305           ++Idx, ++I;
10306         } while (1);
10307       }
10308
10309       // Add any function attributes.
10310       if (Attributes Attr = Attrs.getFnAttributes())
10311         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10312
10313       // The trampoline may have been bitcast to a bogus type (FTy).
10314       // Handle this by synthesizing a new function type, equal to FTy
10315       // with the chain parameter inserted.
10316
10317       std::vector<const Type*> NewTypes;
10318       NewTypes.reserve(FTy->getNumParams()+1);
10319
10320       // Insert the chain's type into the list of parameter types, which may
10321       // mean appending it.
10322       {
10323         unsigned Idx = 1;
10324         FunctionType::param_iterator I = FTy->param_begin(),
10325           E = FTy->param_end();
10326
10327         do {
10328           if (Idx == NestIdx)
10329             // Add the chain's type.
10330             NewTypes.push_back(NestTy);
10331
10332           if (I == E)
10333             break;
10334
10335           // Add the original type.
10336           NewTypes.push_back(*I);
10337
10338           ++Idx, ++I;
10339         } while (1);
10340       }
10341
10342       // Replace the trampoline call with a direct call.  Let the generic
10343       // code sort out any function type mismatches.
10344       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 
10345                                                 FTy->isVarArg());
10346       Constant *NewCallee =
10347         NestF->getType() == PointerType::getUnqual(NewFTy) ?
10348         NestF : ConstantExpr::getBitCast(NestF, 
10349                                          PointerType::getUnqual(NewFTy));
10350       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10351                                                    NewAttrs.end());
10352
10353       Instruction *NewCaller;
10354       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10355         NewCaller = InvokeInst::Create(NewCallee,
10356                                        II->getNormalDest(), II->getUnwindDest(),
10357                                        NewArgs.begin(), NewArgs.end(),
10358                                        Caller->getName(), Caller);
10359         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10360         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10361       } else {
10362         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10363                                      Caller->getName(), Caller);
10364         if (cast<CallInst>(Caller)->isTailCall())
10365           cast<CallInst>(NewCaller)->setTailCall();
10366         cast<CallInst>(NewCaller)->
10367           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10368         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10369       }
10370       if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
10371         Caller->replaceAllUsesWith(NewCaller);
10372       Caller->eraseFromParent();
10373       Worklist.Remove(Caller);
10374       return 0;
10375     }
10376   }
10377
10378   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10379   // parameter, there is no need to adjust the argument list.  Let the generic
10380   // code sort out any function type mismatches.
10381   Constant *NewCallee =
10382     NestF->getType() == PTy ? NestF : 
10383                               ConstantExpr::getBitCast(NestF, PTy);
10384   CS.setCalledFunction(NewCallee);
10385   return CS.getInstruction();
10386 }
10387
10388 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10389 /// and if a/b/c and the add's all have a single use, turn this into a phi
10390 /// and a single binop.
10391 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10392   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10393   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10394   unsigned Opc = FirstInst->getOpcode();
10395   Value *LHSVal = FirstInst->getOperand(0);
10396   Value *RHSVal = FirstInst->getOperand(1);
10397     
10398   const Type *LHSType = LHSVal->getType();
10399   const Type *RHSType = RHSVal->getType();
10400   
10401   // Scan to see if all operands are the same opcode, and all have one use.
10402   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10403     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10404     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10405         // Verify type of the LHS matches so we don't fold cmp's of different
10406         // types or GEP's with different index types.
10407         I->getOperand(0)->getType() != LHSType ||
10408         I->getOperand(1)->getType() != RHSType)
10409       return 0;
10410
10411     // If they are CmpInst instructions, check their predicates
10412     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10413       if (cast<CmpInst>(I)->getPredicate() !=
10414           cast<CmpInst>(FirstInst)->getPredicate())
10415         return 0;
10416     
10417     // Keep track of which operand needs a phi node.
10418     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10419     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10420   }
10421
10422   // If both LHS and RHS would need a PHI, don't do this transformation,
10423   // because it would increase the number of PHIs entering the block,
10424   // which leads to higher register pressure. This is especially
10425   // bad when the PHIs are in the header of a loop.
10426   if (!LHSVal && !RHSVal)
10427     return 0;
10428   
10429   // Otherwise, this is safe to transform!
10430   
10431   Value *InLHS = FirstInst->getOperand(0);
10432   Value *InRHS = FirstInst->getOperand(1);
10433   PHINode *NewLHS = 0, *NewRHS = 0;
10434   if (LHSVal == 0) {
10435     NewLHS = PHINode::Create(LHSType,
10436                              FirstInst->getOperand(0)->getName() + ".pn");
10437     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10438     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10439     InsertNewInstBefore(NewLHS, PN);
10440     LHSVal = NewLHS;
10441   }
10442   
10443   if (RHSVal == 0) {
10444     NewRHS = PHINode::Create(RHSType,
10445                              FirstInst->getOperand(1)->getName() + ".pn");
10446     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10447     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10448     InsertNewInstBefore(NewRHS, PN);
10449     RHSVal = NewRHS;
10450   }
10451   
10452   // Add all operands to the new PHIs.
10453   if (NewLHS || NewRHS) {
10454     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10455       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10456       if (NewLHS) {
10457         Value *NewInLHS = InInst->getOperand(0);
10458         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10459       }
10460       if (NewRHS) {
10461         Value *NewInRHS = InInst->getOperand(1);
10462         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10463       }
10464     }
10465   }
10466     
10467   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10468     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10469   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10470   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10471                          LHSVal, RHSVal);
10472 }
10473
10474 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10475   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10476   
10477   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10478                                         FirstInst->op_end());
10479   // This is true if all GEP bases are allocas and if all indices into them are
10480   // constants.
10481   bool AllBasePointersAreAllocas = true;
10482
10483   // We don't want to replace this phi if the replacement would require
10484   // more than one phi, which leads to higher register pressure. This is
10485   // especially bad when the PHIs are in the header of a loop.
10486   bool NeededPhi = false;
10487   
10488   // Scan to see if all operands are the same opcode, and all have one use.
10489   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10490     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10491     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10492       GEP->getNumOperands() != FirstInst->getNumOperands())
10493       return 0;
10494
10495     // Keep track of whether or not all GEPs are of alloca pointers.
10496     if (AllBasePointersAreAllocas &&
10497         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10498          !GEP->hasAllConstantIndices()))
10499       AllBasePointersAreAllocas = false;
10500     
10501     // Compare the operand lists.
10502     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10503       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10504         continue;
10505       
10506       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10507       // if one of the PHIs has a constant for the index.  The index may be
10508       // substantially cheaper to compute for the constants, so making it a
10509       // variable index could pessimize the path.  This also handles the case
10510       // for struct indices, which must always be constant.
10511       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10512           isa<ConstantInt>(GEP->getOperand(op)))
10513         return 0;
10514       
10515       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10516         return 0;
10517
10518       // If we already needed a PHI for an earlier operand, and another operand
10519       // also requires a PHI, we'd be introducing more PHIs than we're
10520       // eliminating, which increases register pressure on entry to the PHI's
10521       // block.
10522       if (NeededPhi)
10523         return 0;
10524
10525       FixedOperands[op] = 0;  // Needs a PHI.
10526       NeededPhi = true;
10527     }
10528   }
10529   
10530   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10531   // bother doing this transformation.  At best, this will just save a bit of
10532   // offset calculation, but all the predecessors will have to materialize the
10533   // stack address into a register anyway.  We'd actually rather *clone* the
10534   // load up into the predecessors so that we have a load of a gep of an alloca,
10535   // which can usually all be folded into the load.
10536   if (AllBasePointersAreAllocas)
10537     return 0;
10538   
10539   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10540   // that is variable.
10541   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10542   
10543   bool HasAnyPHIs = false;
10544   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10545     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10546     Value *FirstOp = FirstInst->getOperand(i);
10547     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10548                                      FirstOp->getName()+".pn");
10549     InsertNewInstBefore(NewPN, PN);
10550     
10551     NewPN->reserveOperandSpace(e);
10552     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10553     OperandPhis[i] = NewPN;
10554     FixedOperands[i] = NewPN;
10555     HasAnyPHIs = true;
10556   }
10557
10558   
10559   // Add all operands to the new PHIs.
10560   if (HasAnyPHIs) {
10561     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10562       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10563       BasicBlock *InBB = PN.getIncomingBlock(i);
10564       
10565       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10566         if (PHINode *OpPhi = OperandPhis[op])
10567           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10568     }
10569   }
10570   
10571   Value *Base = FixedOperands[0];
10572   return cast<GEPOperator>(FirstInst)->isInBounds() ?
10573     GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10574                                       FixedOperands.end()) :
10575     GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10576                               FixedOperands.end());
10577 }
10578
10579
10580 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10581 /// sink the load out of the block that defines it.  This means that it must be
10582 /// obvious the value of the load is not changed from the point of the load to
10583 /// the end of the block it is in.
10584 ///
10585 /// Finally, it is safe, but not profitable, to sink a load targetting a
10586 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10587 /// to a register.
10588 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10589   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10590   
10591   for (++BBI; BBI != E; ++BBI)
10592     if (BBI->mayWriteToMemory())
10593       return false;
10594   
10595   // Check for non-address taken alloca.  If not address-taken already, it isn't
10596   // profitable to do this xform.
10597   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10598     bool isAddressTaken = false;
10599     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10600          UI != E; ++UI) {
10601       if (isa<LoadInst>(UI)) continue;
10602       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10603         // If storing TO the alloca, then the address isn't taken.
10604         if (SI->getOperand(1) == AI) continue;
10605       }
10606       isAddressTaken = true;
10607       break;
10608     }
10609     
10610     if (!isAddressTaken && AI->isStaticAlloca())
10611       return false;
10612   }
10613   
10614   // If this load is a load from a GEP with a constant offset from an alloca,
10615   // then we don't want to sink it.  In its present form, it will be
10616   // load [constant stack offset].  Sinking it will cause us to have to
10617   // materialize the stack addresses in each predecessor in a register only to
10618   // do a shared load from register in the successor.
10619   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10620     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10621       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10622         return false;
10623   
10624   return true;
10625 }
10626
10627
10628 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10629 // operator and they all are only used by the PHI, PHI together their
10630 // inputs, and do the operation once, to the result of the PHI.
10631 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10632   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10633
10634   // Scan the instruction, looking for input operations that can be folded away.
10635   // If all input operands to the phi are the same instruction (e.g. a cast from
10636   // the same type or "+42") we can pull the operation through the PHI, reducing
10637   // code size and simplifying code.
10638   Constant *ConstantOp = 0;
10639   const Type *CastSrcTy = 0;
10640   bool isVolatile = false;
10641   if (isa<CastInst>(FirstInst)) {
10642     CastSrcTy = FirstInst->getOperand(0)->getType();
10643   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10644     // Can fold binop, compare or shift here if the RHS is a constant, 
10645     // otherwise call FoldPHIArgBinOpIntoPHI.
10646     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10647     if (ConstantOp == 0)
10648       return FoldPHIArgBinOpIntoPHI(PN);
10649   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10650     isVolatile = LI->isVolatile();
10651     // We can't sink the load if the loaded value could be modified between the
10652     // load and the PHI.
10653     if (LI->getParent() != PN.getIncomingBlock(0) ||
10654         !isSafeAndProfitableToSinkLoad(LI))
10655       return 0;
10656     
10657     // If the PHI is of volatile loads and the load block has multiple
10658     // successors, sinking it would remove a load of the volatile value from
10659     // the path through the other successor.
10660     if (isVolatile &&
10661         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10662       return 0;
10663     
10664   } else if (isa<GetElementPtrInst>(FirstInst)) {
10665     return FoldPHIArgGEPIntoPHI(PN);
10666   } else {
10667     return 0;  // Cannot fold this operation.
10668   }
10669
10670   // Check to see if all arguments are the same operation.
10671   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10672     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10673     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10674     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10675       return 0;
10676     if (CastSrcTy) {
10677       if (I->getOperand(0)->getType() != CastSrcTy)
10678         return 0;  // Cast operation must match.
10679     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10680       // We can't sink the load if the loaded value could be modified between 
10681       // the load and the PHI.
10682       if (LI->isVolatile() != isVolatile ||
10683           LI->getParent() != PN.getIncomingBlock(i) ||
10684           !isSafeAndProfitableToSinkLoad(LI))
10685         return 0;
10686       
10687       // If the PHI is of volatile loads and the load block has multiple
10688       // successors, sinking it would remove a load of the volatile value from
10689       // the path through the other successor.
10690       if (isVolatile &&
10691           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10692         return 0;
10693       
10694     } else if (I->getOperand(1) != ConstantOp) {
10695       return 0;
10696     }
10697   }
10698
10699   // Okay, they are all the same operation.  Create a new PHI node of the
10700   // correct type, and PHI together all of the LHS's of the instructions.
10701   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10702                                    PN.getName()+".in");
10703   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10704
10705   Value *InVal = FirstInst->getOperand(0);
10706   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10707
10708   // Add all operands to the new PHI.
10709   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10710     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10711     if (NewInVal != InVal)
10712       InVal = 0;
10713     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10714   }
10715
10716   Value *PhiVal;
10717   if (InVal) {
10718     // The new PHI unions all of the same values together.  This is really
10719     // common, so we handle it intelligently here for compile-time speed.
10720     PhiVal = InVal;
10721     delete NewPN;
10722   } else {
10723     InsertNewInstBefore(NewPN, PN);
10724     PhiVal = NewPN;
10725   }
10726
10727   // Insert and return the new operation.
10728   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10729     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10730   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10731     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10732   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10733     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10734                            PhiVal, ConstantOp);
10735   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10736   
10737   // If this was a volatile load that we are merging, make sure to loop through
10738   // and mark all the input loads as non-volatile.  If we don't do this, we will
10739   // insert a new volatile load and the old ones will not be deletable.
10740   if (isVolatile)
10741     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10742       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10743   
10744   return new LoadInst(PhiVal, "", isVolatile);
10745 }
10746
10747 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10748 /// that is dead.
10749 static bool DeadPHICycle(PHINode *PN,
10750                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10751   if (PN->use_empty()) return true;
10752   if (!PN->hasOneUse()) return false;
10753
10754   // Remember this node, and if we find the cycle, return.
10755   if (!PotentiallyDeadPHIs.insert(PN))
10756     return true;
10757   
10758   // Don't scan crazily complex things.
10759   if (PotentiallyDeadPHIs.size() == 16)
10760     return false;
10761
10762   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10763     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10764
10765   return false;
10766 }
10767
10768 /// PHIsEqualValue - Return true if this phi node is always equal to
10769 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10770 ///   z = some value; x = phi (y, z); y = phi (x, z)
10771 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10772                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10773   // See if we already saw this PHI node.
10774   if (!ValueEqualPHIs.insert(PN))
10775     return true;
10776   
10777   // Don't scan crazily complex things.
10778   if (ValueEqualPHIs.size() == 16)
10779     return false;
10780  
10781   // Scan the operands to see if they are either phi nodes or are equal to
10782   // the value.
10783   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10784     Value *Op = PN->getIncomingValue(i);
10785     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10786       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10787         return false;
10788     } else if (Op != NonPhiInVal)
10789       return false;
10790   }
10791   
10792   return true;
10793 }
10794
10795
10796 // PHINode simplification
10797 //
10798 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10799   // If LCSSA is around, don't mess with Phi nodes
10800   if (MustPreserveLCSSA) return 0;
10801   
10802   if (Value *V = PN.hasConstantValue())
10803     return ReplaceInstUsesWith(PN, V);
10804
10805   // If all PHI operands are the same operation, pull them through the PHI,
10806   // reducing code size.
10807   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10808       isa<Instruction>(PN.getIncomingValue(1)) &&
10809       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10810       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10811       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10812       // than themselves more than once.
10813       PN.getIncomingValue(0)->hasOneUse())
10814     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10815       return Result;
10816
10817   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10818   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10819   // PHI)... break the cycle.
10820   if (PN.hasOneUse()) {
10821     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10822     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10823       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10824       PotentiallyDeadPHIs.insert(&PN);
10825       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10826         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10827     }
10828    
10829     // If this phi has a single use, and if that use just computes a value for
10830     // the next iteration of a loop, delete the phi.  This occurs with unused
10831     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10832     // common case here is good because the only other things that catch this
10833     // are induction variable analysis (sometimes) and ADCE, which is only run
10834     // late.
10835     if (PHIUser->hasOneUse() &&
10836         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10837         PHIUser->use_back() == &PN) {
10838       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10839     }
10840   }
10841
10842   // We sometimes end up with phi cycles that non-obviously end up being the
10843   // same value, for example:
10844   //   z = some value; x = phi (y, z); y = phi (x, z)
10845   // where the phi nodes don't necessarily need to be in the same block.  Do a
10846   // quick check to see if the PHI node only contains a single non-phi value, if
10847   // so, scan to see if the phi cycle is actually equal to that value.
10848   {
10849     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10850     // Scan for the first non-phi operand.
10851     while (InValNo != NumOperandVals && 
10852            isa<PHINode>(PN.getIncomingValue(InValNo)))
10853       ++InValNo;
10854
10855     if (InValNo != NumOperandVals) {
10856       Value *NonPhiInVal = PN.getOperand(InValNo);
10857       
10858       // Scan the rest of the operands to see if there are any conflicts, if so
10859       // there is no need to recursively scan other phis.
10860       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10861         Value *OpVal = PN.getIncomingValue(InValNo);
10862         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10863           break;
10864       }
10865       
10866       // If we scanned over all operands, then we have one unique value plus
10867       // phi values.  Scan PHI nodes to see if they all merge in each other or
10868       // the value.
10869       if (InValNo == NumOperandVals) {
10870         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10871         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10872           return ReplaceInstUsesWith(PN, NonPhiInVal);
10873       }
10874     }
10875   }
10876   return 0;
10877 }
10878
10879 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10880   Value *PtrOp = GEP.getOperand(0);
10881   // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
10882   if (GEP.getNumOperands() == 1)
10883     return ReplaceInstUsesWith(GEP, PtrOp);
10884
10885   if (isa<UndefValue>(GEP.getOperand(0)))
10886     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10887
10888   bool HasZeroPointerIndex = false;
10889   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10890     HasZeroPointerIndex = C->isNullValue();
10891
10892   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10893     return ReplaceInstUsesWith(GEP, PtrOp);
10894
10895   // Eliminate unneeded casts for indices.
10896   if (TD) {
10897     bool MadeChange = false;
10898     unsigned PtrSize = TD->getPointerSizeInBits();
10899     
10900     gep_type_iterator GTI = gep_type_begin(GEP);
10901     for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10902          I != E; ++I, ++GTI) {
10903       if (!isa<SequentialType>(*GTI)) continue;
10904       
10905       // If we are using a wider index than needed for this platform, shrink it
10906       // to what we need.  If narrower, sign-extend it to what we need.  This
10907       // explicit cast can make subsequent optimizations more obvious.
10908       unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
10909       if (OpBits == PtrSize)
10910         continue;
10911       
10912       *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
10913       MadeChange = true;
10914     }
10915     if (MadeChange) return &GEP;
10916   }
10917
10918   // Combine Indices - If the source pointer to this getelementptr instruction
10919   // is a getelementptr instruction, combine the indices of the two
10920   // getelementptr instructions into a single instruction.
10921   //
10922   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
10923     // Note that if our source is a gep chain itself that we wait for that
10924     // chain to be resolved before we perform this transformation.  This
10925     // avoids us creating a TON of code in some cases.
10926     //
10927     if (GetElementPtrInst *SrcGEP =
10928           dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10929       if (SrcGEP->getNumOperands() == 2)
10930         return 0;   // Wait until our source is folded to completion.
10931
10932     SmallVector<Value*, 8> Indices;
10933
10934     // Find out whether the last index in the source GEP is a sequential idx.
10935     bool EndsWithSequential = false;
10936     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10937          I != E; ++I)
10938       EndsWithSequential = !isa<StructType>(*I);
10939
10940     // Can we combine the two pointer arithmetics offsets?
10941     if (EndsWithSequential) {
10942       // Replace: gep (gep %P, long B), long A, ...
10943       // With:    T = long A+B; gep %P, T, ...
10944       //
10945       Value *Sum;
10946       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10947       Value *GO1 = GEP.getOperand(1);
10948       if (SO1 == Constant::getNullValue(SO1->getType())) {
10949         Sum = GO1;
10950       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10951         Sum = SO1;
10952       } else {
10953         // If they aren't the same type, then the input hasn't been processed
10954         // by the loop above yet (which canonicalizes sequential index types to
10955         // intptr_t).  Just avoid transforming this until the input has been
10956         // normalized.
10957         if (SO1->getType() != GO1->getType())
10958           return 0;
10959         Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10960       }
10961
10962       // Update the GEP in place if possible.
10963       if (Src->getNumOperands() == 2) {
10964         GEP.setOperand(0, Src->getOperand(0));
10965         GEP.setOperand(1, Sum);
10966         return &GEP;
10967       }
10968       Indices.append(Src->op_begin()+1, Src->op_end()-1);
10969       Indices.push_back(Sum);
10970       Indices.append(GEP.op_begin()+2, GEP.op_end());
10971     } else if (isa<Constant>(*GEP.idx_begin()) &&
10972                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10973                Src->getNumOperands() != 1) {
10974       // Otherwise we can do the fold if the first index of the GEP is a zero
10975       Indices.append(Src->op_begin()+1, Src->op_end());
10976       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
10977     }
10978
10979     if (!Indices.empty())
10980       return (cast<GEPOperator>(&GEP)->isInBounds() &&
10981               Src->isInBounds()) ?
10982         GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
10983                                           Indices.end(), GEP.getName()) :
10984         GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
10985                                   Indices.end(), GEP.getName());
10986   }
10987   
10988   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
10989   if (Value *X = getBitCastOperand(PtrOp)) {
10990     assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
10991
10992     // If the input bitcast is actually "bitcast(bitcast(x))", then we don't 
10993     // want to change the gep until the bitcasts are eliminated.
10994     if (getBitCastOperand(X)) {
10995       Worklist.AddValue(PtrOp);
10996       return 0;
10997     }
10998     
10999     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11000     // into     : GEP [10 x i8]* X, i32 0, ...
11001     //
11002     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11003     //           into     : GEP i8* X, ...
11004     // 
11005     // This occurs when the program declares an array extern like "int X[];"
11006     if (HasZeroPointerIndex) {
11007       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11008       const PointerType *XTy = cast<PointerType>(X->getType());
11009       if (const ArrayType *CATy =
11010           dyn_cast<ArrayType>(CPTy->getElementType())) {
11011         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11012         if (CATy->getElementType() == XTy->getElementType()) {
11013           // -> GEP i8* X, ...
11014           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11015           return cast<GEPOperator>(&GEP)->isInBounds() ?
11016             GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11017                                               GEP.getName()) :
11018             GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11019                                       GEP.getName());
11020         }
11021         
11022         if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
11023           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11024           if (CATy->getElementType() == XATy->getElementType()) {
11025             // -> GEP [10 x i8]* X, i32 0, ...
11026             // At this point, we know that the cast source type is a pointer
11027             // to an array of the same type as the destination pointer
11028             // array.  Because the array type is never stepped over (there
11029             // is a leading zero) we can fold the cast into this GEP.
11030             GEP.setOperand(0, X);
11031             return &GEP;
11032           }
11033         }
11034       }
11035     } else if (GEP.getNumOperands() == 2) {
11036       // Transform things like:
11037       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11038       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11039       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11040       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11041       if (TD && isa<ArrayType>(SrcElTy) &&
11042           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11043           TD->getTypeAllocSize(ResElTy)) {
11044         Value *Idx[2];
11045         Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11046         Idx[1] = GEP.getOperand(1);
11047         Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11048           Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11049           Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11050         // V and GEP are both pointer types --> BitCast
11051         return new BitCastInst(NewGEP, GEP.getType());
11052       }
11053       
11054       // Transform things like:
11055       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11056       //   (where tmp = 8*tmp2) into:
11057       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11058       
11059       if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
11060         uint64_t ArrayEltSize =
11061             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11062         
11063         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11064         // allow either a mul, shift, or constant here.
11065         Value *NewIdx = 0;
11066         ConstantInt *Scale = 0;
11067         if (ArrayEltSize == 1) {
11068           NewIdx = GEP.getOperand(1);
11069           Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11070         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11071           NewIdx = ConstantInt::get(CI->getType(), 1);
11072           Scale = CI;
11073         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11074           if (Inst->getOpcode() == Instruction::Shl &&
11075               isa<ConstantInt>(Inst->getOperand(1))) {
11076             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11077             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11078             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11079                                      1ULL << ShAmtVal);
11080             NewIdx = Inst->getOperand(0);
11081           } else if (Inst->getOpcode() == Instruction::Mul &&
11082                      isa<ConstantInt>(Inst->getOperand(1))) {
11083             Scale = cast<ConstantInt>(Inst->getOperand(1));
11084             NewIdx = Inst->getOperand(0);
11085           }
11086         }
11087         
11088         // If the index will be to exactly the right offset with the scale taken
11089         // out, perform the transformation. Note, we don't know whether Scale is
11090         // signed or not. We'll use unsigned version of division/modulo
11091         // operation after making sure Scale doesn't have the sign bit set.
11092         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11093             Scale->getZExtValue() % ArrayEltSize == 0) {
11094           Scale = ConstantInt::get(Scale->getType(),
11095                                    Scale->getZExtValue() / ArrayEltSize);
11096           if (Scale->getZExtValue() != 1) {
11097             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11098                                                        false /*ZExt*/);
11099             NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
11100           }
11101
11102           // Insert the new GEP instruction.
11103           Value *Idx[2];
11104           Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11105           Idx[1] = NewIdx;
11106           Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11107             Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11108             Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11109           // The NewGEP must be pointer typed, so must the old one -> BitCast
11110           return new BitCastInst(NewGEP, GEP.getType());
11111         }
11112       }
11113     }
11114   }
11115   
11116   /// See if we can simplify:
11117   ///   X = bitcast A* to B*
11118   ///   Y = gep X, <...constant indices...>
11119   /// into a gep of the original struct.  This is important for SROA and alias
11120   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11121   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11122     if (TD &&
11123         !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11124       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11125       // a constant back from EmitGEPOffset.
11126       ConstantInt *OffsetV =
11127                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11128       int64_t Offset = OffsetV->getSExtValue();
11129       
11130       // If this GEP instruction doesn't move the pointer, just replace the GEP
11131       // with a bitcast of the real input to the dest type.
11132       if (Offset == 0) {
11133         // If the bitcast is of an allocation, and the allocation will be
11134         // converted to match the type of the cast, don't touch this.
11135         if (isa<AllocationInst>(BCI->getOperand(0)) ||
11136             isMalloc(BCI->getOperand(0))) {
11137           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11138           if (Instruction *I = visitBitCast(*BCI)) {
11139             if (I != BCI) {
11140               I->takeName(BCI);
11141               BCI->getParent()->getInstList().insert(BCI, I);
11142               ReplaceInstUsesWith(*BCI, I);
11143             }
11144             return &GEP;
11145           }
11146         }
11147         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11148       }
11149       
11150       // Otherwise, if the offset is non-zero, we need to find out if there is a
11151       // field at Offset in 'A's type.  If so, we can pull the cast through the
11152       // GEP.
11153       SmallVector<Value*, 8> NewIndices;
11154       const Type *InTy =
11155         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11156       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11157         Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11158           Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11159                                      NewIndices.end()) :
11160           Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11161                              NewIndices.end());
11162         
11163         if (NGEP->getType() == GEP.getType())
11164           return ReplaceInstUsesWith(GEP, NGEP);
11165         NGEP->takeName(&GEP);
11166         return new BitCastInst(NGEP, GEP.getType());
11167       }
11168     }
11169   }    
11170     
11171   return 0;
11172 }
11173
11174 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11175   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11176   if (AI.isArrayAllocation()) {  // Check C != 1
11177     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11178       const Type *NewTy = 
11179         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11180       AllocationInst *New = 0;
11181
11182       // Create and insert the replacement instruction...
11183       if (isa<MallocInst>(AI))
11184         New = Builder->CreateMalloc(NewTy, 0, AI.getName());
11185       else {
11186         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11187         New = Builder->CreateAlloca(NewTy, 0, AI.getName());
11188       }
11189       New->setAlignment(AI.getAlignment());
11190
11191       // Scan to the end of the allocation instructions, to skip over a block of
11192       // allocas if possible...also skip interleaved debug info
11193       //
11194       BasicBlock::iterator It = New;
11195       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11196
11197       // Now that I is pointing to the first non-allocation-inst in the block,
11198       // insert our getelementptr instruction...
11199       //
11200       Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
11201       Value *Idx[2];
11202       Idx[0] = NullIdx;
11203       Idx[1] = NullIdx;
11204       Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11205                                                    New->getName()+".sub", It);
11206
11207       // Now make everything use the getelementptr instead of the original
11208       // allocation.
11209       return ReplaceInstUsesWith(AI, V);
11210     } else if (isa<UndefValue>(AI.getArraySize())) {
11211       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11212     }
11213   }
11214
11215   if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11216     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11217     // Note that we only do this for alloca's, because malloc should allocate
11218     // and return a unique pointer, even for a zero byte allocation.
11219     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11220       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11221
11222     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11223     if (AI.getAlignment() == 0)
11224       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11225   }
11226
11227   return 0;
11228 }
11229
11230 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11231   Value *Op = FI.getOperand(0);
11232
11233   // free undef -> unreachable.
11234   if (isa<UndefValue>(Op)) {
11235     // Insert a new store to null because we cannot modify the CFG here.
11236     new StoreInst(ConstantInt::getTrue(*Context),
11237            UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
11238     return EraseInstFromFunction(FI);
11239   }
11240   
11241   // If we have 'free null' delete the instruction.  This can happen in stl code
11242   // when lots of inlining happens.
11243   if (isa<ConstantPointerNull>(Op))
11244     return EraseInstFromFunction(FI);
11245   
11246   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11247   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11248     FI.setOperand(0, CI->getOperand(0));
11249     return &FI;
11250   }
11251   
11252   // Change free (gep X, 0,0,0,0) into free(X)
11253   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11254     if (GEPI->hasAllZeroIndices()) {
11255       Worklist.Add(GEPI);
11256       FI.setOperand(0, GEPI->getOperand(0));
11257       return &FI;
11258     }
11259   }
11260   
11261   // Change free(malloc) into nothing, if the malloc has a single use.
11262   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11263     if (MI->hasOneUse()) {
11264       EraseInstFromFunction(FI);
11265       return EraseInstFromFunction(*MI);
11266     }
11267   if (isMalloc(Op)) {
11268     if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11269       if (Op->hasOneUse() && CI->hasOneUse()) {
11270         EraseInstFromFunction(FI);
11271         EraseInstFromFunction(*CI);
11272         return EraseInstFromFunction(*cast<Instruction>(Op));
11273       }
11274     } else {
11275       // Op is a call to malloc
11276       if (Op->hasOneUse()) {
11277         EraseInstFromFunction(FI);
11278         return EraseInstFromFunction(*cast<Instruction>(Op));
11279       }
11280     }
11281   }
11282
11283   return 0;
11284 }
11285
11286
11287 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11288 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11289                                         const TargetData *TD) {
11290   User *CI = cast<User>(LI.getOperand(0));
11291   Value *CastOp = CI->getOperand(0);
11292   LLVMContext *Context = IC.getContext();
11293
11294   if (TD) {
11295     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11296       // Instead of loading constant c string, use corresponding integer value
11297       // directly if string length is small enough.
11298       std::string Str;
11299       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11300         unsigned len = Str.length();
11301         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11302         unsigned numBits = Ty->getPrimitiveSizeInBits();
11303         // Replace LI with immediate integer store.
11304         if ((numBits >> 3) == len + 1) {
11305           APInt StrVal(numBits, 0);
11306           APInt SingleChar(numBits, 0);
11307           if (TD->isLittleEndian()) {
11308             for (signed i = len-1; i >= 0; i--) {
11309               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11310               StrVal = (StrVal << 8) | SingleChar;
11311             }
11312           } else {
11313             for (unsigned i = 0; i < len; i++) {
11314               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11315               StrVal = (StrVal << 8) | SingleChar;
11316             }
11317             // Append NULL at the end.
11318             SingleChar = 0;
11319             StrVal = (StrVal << 8) | SingleChar;
11320           }
11321           Value *NL = ConstantInt::get(*Context, StrVal);
11322           return IC.ReplaceInstUsesWith(LI, NL);
11323         }
11324       }
11325     }
11326   }
11327
11328   const PointerType *DestTy = cast<PointerType>(CI->getType());
11329   const Type *DestPTy = DestTy->getElementType();
11330   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11331
11332     // If the address spaces don't match, don't eliminate the cast.
11333     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11334       return 0;
11335
11336     const Type *SrcPTy = SrcTy->getElementType();
11337
11338     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11339          isa<VectorType>(DestPTy)) {
11340       // If the source is an array, the code below will not succeed.  Check to
11341       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11342       // constants.
11343       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11344         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11345           if (ASrcTy->getNumElements() != 0) {
11346             Value *Idxs[2];
11347             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
11348             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11349             SrcTy = cast<PointerType>(CastOp->getType());
11350             SrcPTy = SrcTy->getElementType();
11351           }
11352
11353       if (IC.getTargetData() &&
11354           (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11355             isa<VectorType>(SrcPTy)) &&
11356           // Do not allow turning this into a load of an integer, which is then
11357           // casted to a pointer, this pessimizes pointer analysis a lot.
11358           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11359           IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11360                IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11361
11362         // Okay, we are casting from one integer or pointer type to another of
11363         // the same size.  Instead of casting the pointer before the load, cast
11364         // the result of the loaded value.
11365         Value *NewLoad = 
11366           IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
11367         // Now cast the result of the load.
11368         return new BitCastInst(NewLoad, LI.getType());
11369       }
11370     }
11371   }
11372   return 0;
11373 }
11374
11375 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11376   Value *Op = LI.getOperand(0);
11377
11378   // Attempt to improve the alignment.
11379   if (TD) {
11380     unsigned KnownAlign =
11381       GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11382     if (KnownAlign >
11383         (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11384                                   LI.getAlignment()))
11385       LI.setAlignment(KnownAlign);
11386   }
11387
11388   // load (cast X) --> cast (load X) iff safe.
11389   if (isa<CastInst>(Op))
11390     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11391       return Res;
11392
11393   // None of the following transforms are legal for volatile loads.
11394   if (LI.isVolatile()) return 0;
11395   
11396   // Do really simple store-to-load forwarding and load CSE, to catch cases
11397   // where there are several consequtive memory accesses to the same location,
11398   // separated by a few arithmetic operations.
11399   BasicBlock::iterator BBI = &LI;
11400   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11401     return ReplaceInstUsesWith(LI, AvailableVal);
11402
11403   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11404     const Value *GEPI0 = GEPI->getOperand(0);
11405     // TODO: Consider a target hook for valid address spaces for this xform.
11406     if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
11407       // Insert a new store to null instruction before the load to indicate
11408       // that this code is not reachable.  We do this instead of inserting
11409       // an unreachable instruction directly because we cannot modify the
11410       // CFG.
11411       new StoreInst(UndefValue::get(LI.getType()),
11412                     Constant::getNullValue(Op->getType()), &LI);
11413       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11414     }
11415   } 
11416
11417   if (Constant *C = dyn_cast<Constant>(Op)) {
11418     // load null/undef -> undef
11419     // TODO: Consider a target hook for valid address spaces for this xform.
11420     if (isa<UndefValue>(C) ||
11421         (C->isNullValue() && LI.getPointerAddressSpace() == 0)) {
11422       // Insert a new store to null instruction before the load to indicate that
11423       // this code is not reachable.  We do this instead of inserting an
11424       // unreachable instruction directly because we cannot modify the CFG.
11425       new StoreInst(UndefValue::get(LI.getType()),
11426                     Constant::getNullValue(Op->getType()), &LI);
11427       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11428     }
11429
11430     // Instcombine load (constant global) into the value loaded.
11431     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11432       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11433         return ReplaceInstUsesWith(LI, GV->getInitializer());
11434
11435     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11436     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11437       if (CE->getOpcode() == Instruction::GetElementPtr) {
11438         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11439           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11440             if (Constant *V = 
11441                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE, 
11442                                                       *Context))
11443               return ReplaceInstUsesWith(LI, V);
11444         if (CE->getOperand(0)->isNullValue()) {
11445           // Insert a new store to null instruction before the load to indicate
11446           // that this code is not reachable.  We do this instead of inserting
11447           // an unreachable instruction directly because we cannot modify the
11448           // CFG.
11449           new StoreInst(UndefValue::get(LI.getType()),
11450                         Constant::getNullValue(Op->getType()), &LI);
11451           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11452         }
11453
11454       } else if (CE->isCast()) {
11455         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11456           return Res;
11457       }
11458     }
11459   }
11460     
11461   // If this load comes from anywhere in a constant global, and if the global
11462   // is all undef or zero, we know what it loads.
11463   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11464     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11465       if (GV->getInitializer()->isNullValue())
11466         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11467       else if (isa<UndefValue>(GV->getInitializer()))
11468         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11469     }
11470   }
11471
11472   if (Op->hasOneUse()) {
11473     // Change select and PHI nodes to select values instead of addresses: this
11474     // helps alias analysis out a lot, allows many others simplifications, and
11475     // exposes redundancy in the code.
11476     //
11477     // Note that we cannot do the transformation unless we know that the
11478     // introduced loads cannot trap!  Something like this is valid as long as
11479     // the condition is always false: load (select bool %C, int* null, int* %G),
11480     // but it would not be valid if we transformed it to load from null
11481     // unconditionally.
11482     //
11483     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11484       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11485       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11486           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11487         Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11488                                         SI->getOperand(1)->getName()+".val");
11489         Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11490                                         SI->getOperand(2)->getName()+".val");
11491         return SelectInst::Create(SI->getCondition(), V1, V2);
11492       }
11493
11494       // load (select (cond, null, P)) -> load P
11495       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11496         if (C->isNullValue()) {
11497           LI.setOperand(0, SI->getOperand(2));
11498           return &LI;
11499         }
11500
11501       // load (select (cond, P, null)) -> load P
11502       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11503         if (C->isNullValue()) {
11504           LI.setOperand(0, SI->getOperand(1));
11505           return &LI;
11506         }
11507     }
11508   }
11509   return 0;
11510 }
11511
11512 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11513 /// when possible.  This makes it generally easy to do alias analysis and/or
11514 /// SROA/mem2reg of the memory object.
11515 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11516   User *CI = cast<User>(SI.getOperand(1));
11517   Value *CastOp = CI->getOperand(0);
11518
11519   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11520   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11521   if (SrcTy == 0) return 0;
11522   
11523   const Type *SrcPTy = SrcTy->getElementType();
11524
11525   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11526     return 0;
11527   
11528   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11529   /// to its first element.  This allows us to handle things like:
11530   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11531   /// on 32-bit hosts.
11532   SmallVector<Value*, 4> NewGEPIndices;
11533   
11534   // If the source is an array, the code below will not succeed.  Check to
11535   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11536   // constants.
11537   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11538     // Index through pointer.
11539     Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
11540     NewGEPIndices.push_back(Zero);
11541     
11542     while (1) {
11543       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11544         if (!STy->getNumElements()) /* Struct can be empty {} */
11545           break;
11546         NewGEPIndices.push_back(Zero);
11547         SrcPTy = STy->getElementType(0);
11548       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11549         NewGEPIndices.push_back(Zero);
11550         SrcPTy = ATy->getElementType();
11551       } else {
11552         break;
11553       }
11554     }
11555     
11556     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11557   }
11558
11559   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11560     return 0;
11561   
11562   // If the pointers point into different address spaces or if they point to
11563   // values with different sizes, we can't do the transformation.
11564   if (!IC.getTargetData() ||
11565       SrcTy->getAddressSpace() != 
11566         cast<PointerType>(CI->getType())->getAddressSpace() ||
11567       IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11568       IC.getTargetData()->getTypeSizeInBits(DestPTy))
11569     return 0;
11570
11571   // Okay, we are casting from one integer or pointer type to another of
11572   // the same size.  Instead of casting the pointer before 
11573   // the store, cast the value to be stored.
11574   Value *NewCast;
11575   Value *SIOp0 = SI.getOperand(0);
11576   Instruction::CastOps opcode = Instruction::BitCast;
11577   const Type* CastSrcTy = SIOp0->getType();
11578   const Type* CastDstTy = SrcPTy;
11579   if (isa<PointerType>(CastDstTy)) {
11580     if (CastSrcTy->isInteger())
11581       opcode = Instruction::IntToPtr;
11582   } else if (isa<IntegerType>(CastDstTy)) {
11583     if (isa<PointerType>(SIOp0->getType()))
11584       opcode = Instruction::PtrToInt;
11585   }
11586   
11587   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11588   // emit a GEP to index into its first field.
11589   if (!NewGEPIndices.empty())
11590     CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11591                                            NewGEPIndices.end());
11592   
11593   NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11594                                    SIOp0->getName()+".c");
11595   return new StoreInst(NewCast, CastOp);
11596 }
11597
11598 /// equivalentAddressValues - Test if A and B will obviously have the same
11599 /// value. This includes recognizing that %t0 and %t1 will have the same
11600 /// value in code like this:
11601 ///   %t0 = getelementptr \@a, 0, 3
11602 ///   store i32 0, i32* %t0
11603 ///   %t1 = getelementptr \@a, 0, 3
11604 ///   %t2 = load i32* %t1
11605 ///
11606 static bool equivalentAddressValues(Value *A, Value *B) {
11607   // Test if the values are trivially equivalent.
11608   if (A == B) return true;
11609   
11610   // Test if the values come form identical arithmetic instructions.
11611   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11612   // its only used to compare two uses within the same basic block, which
11613   // means that they'll always either have the same value or one of them
11614   // will have an undefined value.
11615   if (isa<BinaryOperator>(A) ||
11616       isa<CastInst>(A) ||
11617       isa<PHINode>(A) ||
11618       isa<GetElementPtrInst>(A))
11619     if (Instruction *BI = dyn_cast<Instruction>(B))
11620       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
11621         return true;
11622   
11623   // Otherwise they may not be equivalent.
11624   return false;
11625 }
11626
11627 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11628 // return the llvm.dbg.declare.
11629 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11630   if (!V->hasNUses(2))
11631     return 0;
11632   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11633        UI != E; ++UI) {
11634     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11635       return DI;
11636     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11637       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11638         return DI;
11639       }
11640   }
11641   return 0;
11642 }
11643
11644 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11645   Value *Val = SI.getOperand(0);
11646   Value *Ptr = SI.getOperand(1);
11647
11648   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11649     EraseInstFromFunction(SI);
11650     ++NumCombined;
11651     return 0;
11652   }
11653   
11654   // If the RHS is an alloca with a single use, zapify the store, making the
11655   // alloca dead.
11656   // If the RHS is an alloca with a two uses, the other one being a 
11657   // llvm.dbg.declare, zapify the store and the declare, making the
11658   // alloca dead.  We must do this to prevent declare's from affecting
11659   // codegen.
11660   if (!SI.isVolatile()) {
11661     if (Ptr->hasOneUse()) {
11662       if (isa<AllocaInst>(Ptr)) {
11663         EraseInstFromFunction(SI);
11664         ++NumCombined;
11665         return 0;
11666       }
11667       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11668         if (isa<AllocaInst>(GEP->getOperand(0))) {
11669           if (GEP->getOperand(0)->hasOneUse()) {
11670             EraseInstFromFunction(SI);
11671             ++NumCombined;
11672             return 0;
11673           }
11674           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11675             EraseInstFromFunction(*DI);
11676             EraseInstFromFunction(SI);
11677             ++NumCombined;
11678             return 0;
11679           }
11680         }
11681       }
11682     }
11683     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11684       EraseInstFromFunction(*DI);
11685       EraseInstFromFunction(SI);
11686       ++NumCombined;
11687       return 0;
11688     }
11689   }
11690
11691   // Attempt to improve the alignment.
11692   if (TD) {
11693     unsigned KnownAlign =
11694       GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11695     if (KnownAlign >
11696         (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11697                                   SI.getAlignment()))
11698       SI.setAlignment(KnownAlign);
11699   }
11700
11701   // Do really simple DSE, to catch cases where there are several consecutive
11702   // stores to the same location, separated by a few arithmetic operations. This
11703   // situation often occurs with bitfield accesses.
11704   BasicBlock::iterator BBI = &SI;
11705   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11706        --ScanInsts) {
11707     --BBI;
11708     // Don't count debug info directives, lest they affect codegen,
11709     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11710     // It is necessary for correctness to skip those that feed into a
11711     // llvm.dbg.declare, as these are not present when debugging is off.
11712     if (isa<DbgInfoIntrinsic>(BBI) ||
11713         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11714       ScanInsts++;
11715       continue;
11716     }    
11717     
11718     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11719       // Prev store isn't volatile, and stores to the same location?
11720       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11721                                                           SI.getOperand(1))) {
11722         ++NumDeadStore;
11723         ++BBI;
11724         EraseInstFromFunction(*PrevSI);
11725         continue;
11726       }
11727       break;
11728     }
11729     
11730     // If this is a load, we have to stop.  However, if the loaded value is from
11731     // the pointer we're loading and is producing the pointer we're storing,
11732     // then *this* store is dead (X = load P; store X -> P).
11733     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11734       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11735           !SI.isVolatile()) {
11736         EraseInstFromFunction(SI);
11737         ++NumCombined;
11738         return 0;
11739       }
11740       // Otherwise, this is a load from some other location.  Stores before it
11741       // may not be dead.
11742       break;
11743     }
11744     
11745     // Don't skip over loads or things that can modify memory.
11746     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11747       break;
11748   }
11749   
11750   
11751   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11752
11753   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11754   if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
11755     if (!isa<UndefValue>(Val)) {
11756       SI.setOperand(0, UndefValue::get(Val->getType()));
11757       if (Instruction *U = dyn_cast<Instruction>(Val))
11758         Worklist.Add(U);  // Dropped a use.
11759       ++NumCombined;
11760     }
11761     return 0;  // Do not modify these!
11762   }
11763
11764   // store undef, Ptr -> noop
11765   if (isa<UndefValue>(Val)) {
11766     EraseInstFromFunction(SI);
11767     ++NumCombined;
11768     return 0;
11769   }
11770
11771   // If the pointer destination is a cast, see if we can fold the cast into the
11772   // source instead.
11773   if (isa<CastInst>(Ptr))
11774     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11775       return Res;
11776   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11777     if (CE->isCast())
11778       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11779         return Res;
11780
11781   
11782   // If this store is the last instruction in the basic block (possibly
11783   // excepting debug info instructions and the pointer bitcasts that feed
11784   // into them), and if the block ends with an unconditional branch, try
11785   // to move it to the successor block.
11786   BBI = &SI; 
11787   do {
11788     ++BBI;
11789   } while (isa<DbgInfoIntrinsic>(BBI) ||
11790            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11791   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11792     if (BI->isUnconditional())
11793       if (SimplifyStoreAtEndOfBlock(SI))
11794         return 0;  // xform done!
11795   
11796   return 0;
11797 }
11798
11799 /// SimplifyStoreAtEndOfBlock - Turn things like:
11800 ///   if () { *P = v1; } else { *P = v2 }
11801 /// into a phi node with a store in the successor.
11802 ///
11803 /// Simplify things like:
11804 ///   *P = v1; if () { *P = v2; }
11805 /// into a phi node with a store in the successor.
11806 ///
11807 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11808   BasicBlock *StoreBB = SI.getParent();
11809   
11810   // Check to see if the successor block has exactly two incoming edges.  If
11811   // so, see if the other predecessor contains a store to the same location.
11812   // if so, insert a PHI node (if needed) and move the stores down.
11813   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11814   
11815   // Determine whether Dest has exactly two predecessors and, if so, compute
11816   // the other predecessor.
11817   pred_iterator PI = pred_begin(DestBB);
11818   BasicBlock *OtherBB = 0;
11819   if (*PI != StoreBB)
11820     OtherBB = *PI;
11821   ++PI;
11822   if (PI == pred_end(DestBB))
11823     return false;
11824   
11825   if (*PI != StoreBB) {
11826     if (OtherBB)
11827       return false;
11828     OtherBB = *PI;
11829   }
11830   if (++PI != pred_end(DestBB))
11831     return false;
11832
11833   // Bail out if all the relevant blocks aren't distinct (this can happen,
11834   // for example, if SI is in an infinite loop)
11835   if (StoreBB == DestBB || OtherBB == DestBB)
11836     return false;
11837
11838   // Verify that the other block ends in a branch and is not otherwise empty.
11839   BasicBlock::iterator BBI = OtherBB->getTerminator();
11840   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11841   if (!OtherBr || BBI == OtherBB->begin())
11842     return false;
11843   
11844   // If the other block ends in an unconditional branch, check for the 'if then
11845   // else' case.  there is an instruction before the branch.
11846   StoreInst *OtherStore = 0;
11847   if (OtherBr->isUnconditional()) {
11848     --BBI;
11849     // Skip over debugging info.
11850     while (isa<DbgInfoIntrinsic>(BBI) ||
11851            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11852       if (BBI==OtherBB->begin())
11853         return false;
11854       --BBI;
11855     }
11856     // If this isn't a store, or isn't a store to the same location, bail out.
11857     OtherStore = dyn_cast<StoreInst>(BBI);
11858     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11859       return false;
11860   } else {
11861     // Otherwise, the other block ended with a conditional branch. If one of the
11862     // destinations is StoreBB, then we have the if/then case.
11863     if (OtherBr->getSuccessor(0) != StoreBB && 
11864         OtherBr->getSuccessor(1) != StoreBB)
11865       return false;
11866     
11867     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11868     // if/then triangle.  See if there is a store to the same ptr as SI that
11869     // lives in OtherBB.
11870     for (;; --BBI) {
11871       // Check to see if we find the matching store.
11872       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11873         if (OtherStore->getOperand(1) != SI.getOperand(1))
11874           return false;
11875         break;
11876       }
11877       // If we find something that may be using or overwriting the stored
11878       // value, or if we run out of instructions, we can't do the xform.
11879       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11880           BBI == OtherBB->begin())
11881         return false;
11882     }
11883     
11884     // In order to eliminate the store in OtherBr, we have to
11885     // make sure nothing reads or overwrites the stored value in
11886     // StoreBB.
11887     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11888       // FIXME: This should really be AA driven.
11889       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11890         return false;
11891     }
11892   }
11893   
11894   // Insert a PHI node now if we need it.
11895   Value *MergedVal = OtherStore->getOperand(0);
11896   if (MergedVal != SI.getOperand(0)) {
11897     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11898     PN->reserveOperandSpace(2);
11899     PN->addIncoming(SI.getOperand(0), SI.getParent());
11900     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11901     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11902   }
11903   
11904   // Advance to a place where it is safe to insert the new store and
11905   // insert it.
11906   BBI = DestBB->getFirstNonPHI();
11907   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11908                                     OtherStore->isVolatile()), *BBI);
11909   
11910   // Nuke the old stores.
11911   EraseInstFromFunction(SI);
11912   EraseInstFromFunction(*OtherStore);
11913   ++NumCombined;
11914   return true;
11915 }
11916
11917
11918 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11919   // Change br (not X), label True, label False to: br X, label False, True
11920   Value *X = 0;
11921   BasicBlock *TrueDest;
11922   BasicBlock *FalseDest;
11923   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11924       !isa<Constant>(X)) {
11925     // Swap Destinations and condition...
11926     BI.setCondition(X);
11927     BI.setSuccessor(0, FalseDest);
11928     BI.setSuccessor(1, TrueDest);
11929     return &BI;
11930   }
11931
11932   // Cannonicalize fcmp_one -> fcmp_oeq
11933   FCmpInst::Predicate FPred; Value *Y;
11934   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11935                              TrueDest, FalseDest)) &&
11936       BI.getCondition()->hasOneUse())
11937     if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11938         FPred == FCmpInst::FCMP_OGE) {
11939       FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11940       Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11941       
11942       // Swap Destinations and condition.
11943       BI.setSuccessor(0, FalseDest);
11944       BI.setSuccessor(1, TrueDest);
11945       Worklist.Add(Cond);
11946       return &BI;
11947     }
11948
11949   // Cannonicalize icmp_ne -> icmp_eq
11950   ICmpInst::Predicate IPred;
11951   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11952                       TrueDest, FalseDest)) &&
11953       BI.getCondition()->hasOneUse())
11954     if (IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
11955         IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11956         IPred == ICmpInst::ICMP_SGE) {
11957       ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11958       Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11959       // Swap Destinations and condition.
11960       BI.setSuccessor(0, FalseDest);
11961       BI.setSuccessor(1, TrueDest);
11962       Worklist.Add(Cond);
11963       return &BI;
11964     }
11965
11966   return 0;
11967 }
11968
11969 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11970   Value *Cond = SI.getCondition();
11971   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11972     if (I->getOpcode() == Instruction::Add)
11973       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11974         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11975         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11976           SI.setOperand(i,
11977                    ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11978                                                 AddRHS));
11979         SI.setOperand(0, I->getOperand(0));
11980         Worklist.Add(I);
11981         return &SI;
11982       }
11983   }
11984   return 0;
11985 }
11986
11987 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
11988   Value *Agg = EV.getAggregateOperand();
11989
11990   if (!EV.hasIndices())
11991     return ReplaceInstUsesWith(EV, Agg);
11992
11993   if (Constant *C = dyn_cast<Constant>(Agg)) {
11994     if (isa<UndefValue>(C))
11995       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11996       
11997     if (isa<ConstantAggregateZero>(C))
11998       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11999
12000     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12001       // Extract the element indexed by the first index out of the constant
12002       Value *V = C->getOperand(*EV.idx_begin());
12003       if (EV.getNumIndices() > 1)
12004         // Extract the remaining indices out of the constant indexed by the
12005         // first index
12006         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12007       else
12008         return ReplaceInstUsesWith(EV, V);
12009     }
12010     return 0; // Can't handle other constants
12011   } 
12012   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12013     // We're extracting from an insertvalue instruction, compare the indices
12014     const unsigned *exti, *exte, *insi, *inse;
12015     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12016          exte = EV.idx_end(), inse = IV->idx_end();
12017          exti != exte && insi != inse;
12018          ++exti, ++insi) {
12019       if (*insi != *exti)
12020         // The insert and extract both reference distinctly different elements.
12021         // This means the extract is not influenced by the insert, and we can
12022         // replace the aggregate operand of the extract with the aggregate
12023         // operand of the insert. i.e., replace
12024         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12025         // %E = extractvalue { i32, { i32 } } %I, 0
12026         // with
12027         // %E = extractvalue { i32, { i32 } } %A, 0
12028         return ExtractValueInst::Create(IV->getAggregateOperand(),
12029                                         EV.idx_begin(), EV.idx_end());
12030     }
12031     if (exti == exte && insi == inse)
12032       // Both iterators are at the end: Index lists are identical. Replace
12033       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12034       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12035       // with "i32 42"
12036       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12037     if (exti == exte) {
12038       // The extract list is a prefix of the insert list. i.e. replace
12039       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12040       // %E = extractvalue { i32, { i32 } } %I, 1
12041       // with
12042       // %X = extractvalue { i32, { i32 } } %A, 1
12043       // %E = insertvalue { i32 } %X, i32 42, 0
12044       // by switching the order of the insert and extract (though the
12045       // insertvalue should be left in, since it may have other uses).
12046       Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12047                                                  EV.idx_begin(), EV.idx_end());
12048       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12049                                      insi, inse);
12050     }
12051     if (insi == inse)
12052       // The insert list is a prefix of the extract list
12053       // We can simply remove the common indices from the extract and make it
12054       // operate on the inserted value instead of the insertvalue result.
12055       // i.e., replace
12056       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12057       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12058       // with
12059       // %E extractvalue { i32 } { i32 42 }, 0
12060       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12061                                       exti, exte);
12062   }
12063   // Can't simplify extracts from other values. Note that nested extracts are
12064   // already simplified implicitely by the above (extract ( extract (insert) )
12065   // will be translated into extract ( insert ( extract ) ) first and then just
12066   // the value inserted, if appropriate).
12067   return 0;
12068 }
12069
12070 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12071 /// is to leave as a vector operation.
12072 static bool CheapToScalarize(Value *V, bool isConstant) {
12073   if (isa<ConstantAggregateZero>(V)) 
12074     return true;
12075   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12076     if (isConstant) return true;
12077     // If all elts are the same, we can extract.
12078     Constant *Op0 = C->getOperand(0);
12079     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12080       if (C->getOperand(i) != Op0)
12081         return false;
12082     return true;
12083   }
12084   Instruction *I = dyn_cast<Instruction>(V);
12085   if (!I) return false;
12086   
12087   // Insert element gets simplified to the inserted element or is deleted if
12088   // this is constant idx extract element and its a constant idx insertelt.
12089   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12090       isa<ConstantInt>(I->getOperand(2)))
12091     return true;
12092   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12093     return true;
12094   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12095     if (BO->hasOneUse() &&
12096         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12097          CheapToScalarize(BO->getOperand(1), isConstant)))
12098       return true;
12099   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12100     if (CI->hasOneUse() &&
12101         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12102          CheapToScalarize(CI->getOperand(1), isConstant)))
12103       return true;
12104   
12105   return false;
12106 }
12107
12108 /// Read and decode a shufflevector mask.
12109 ///
12110 /// It turns undef elements into values that are larger than the number of
12111 /// elements in the input.
12112 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12113   unsigned NElts = SVI->getType()->getNumElements();
12114   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12115     return std::vector<unsigned>(NElts, 0);
12116   if (isa<UndefValue>(SVI->getOperand(2)))
12117     return std::vector<unsigned>(NElts, 2*NElts);
12118
12119   std::vector<unsigned> Result;
12120   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12121   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12122     if (isa<UndefValue>(*i))
12123       Result.push_back(NElts*2);  // undef -> 8
12124     else
12125       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12126   return Result;
12127 }
12128
12129 /// FindScalarElement - Given a vector and an element number, see if the scalar
12130 /// value is already around as a register, for example if it were inserted then
12131 /// extracted from the vector.
12132 static Value *FindScalarElement(Value *V, unsigned EltNo,
12133                                 LLVMContext *Context) {
12134   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12135   const VectorType *PTy = cast<VectorType>(V->getType());
12136   unsigned Width = PTy->getNumElements();
12137   if (EltNo >= Width)  // Out of range access.
12138     return UndefValue::get(PTy->getElementType());
12139   
12140   if (isa<UndefValue>(V))
12141     return UndefValue::get(PTy->getElementType());
12142   else if (isa<ConstantAggregateZero>(V))
12143     return Constant::getNullValue(PTy->getElementType());
12144   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12145     return CP->getOperand(EltNo);
12146   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12147     // If this is an insert to a variable element, we don't know what it is.
12148     if (!isa<ConstantInt>(III->getOperand(2))) 
12149       return 0;
12150     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12151     
12152     // If this is an insert to the element we are looking for, return the
12153     // inserted value.
12154     if (EltNo == IIElt) 
12155       return III->getOperand(1);
12156     
12157     // Otherwise, the insertelement doesn't modify the value, recurse on its
12158     // vector input.
12159     return FindScalarElement(III->getOperand(0), EltNo, Context);
12160   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12161     unsigned LHSWidth =
12162       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12163     unsigned InEl = getShuffleMask(SVI)[EltNo];
12164     if (InEl < LHSWidth)
12165       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12166     else if (InEl < LHSWidth*2)
12167       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12168     else
12169       return UndefValue::get(PTy->getElementType());
12170   }
12171   
12172   // Otherwise, we don't know.
12173   return 0;
12174 }
12175
12176 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12177   // If vector val is undef, replace extract with scalar undef.
12178   if (isa<UndefValue>(EI.getOperand(0)))
12179     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12180
12181   // If vector val is constant 0, replace extract with scalar 0.
12182   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12183     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12184   
12185   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12186     // If vector val is constant with all elements the same, replace EI with
12187     // that element. When the elements are not identical, we cannot replace yet
12188     // (we do that below, but only when the index is constant).
12189     Constant *op0 = C->getOperand(0);
12190     for (unsigned i = 1; i != C->getNumOperands(); ++i)
12191       if (C->getOperand(i) != op0) {
12192         op0 = 0; 
12193         break;
12194       }
12195     if (op0)
12196       return ReplaceInstUsesWith(EI, op0);
12197   }
12198   
12199   // If extracting a specified index from the vector, see if we can recursively
12200   // find a previously computed scalar that was inserted into the vector.
12201   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12202     unsigned IndexVal = IdxC->getZExtValue();
12203     unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
12204       
12205     // If this is extracting an invalid index, turn this into undef, to avoid
12206     // crashing the code below.
12207     if (IndexVal >= VectorWidth)
12208       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12209     
12210     // This instruction only demands the single element from the input vector.
12211     // If the input vector has a single use, simplify it based on this use
12212     // property.
12213     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12214       APInt UndefElts(VectorWidth, 0);
12215       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12216       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12217                                                 DemandedMask, UndefElts)) {
12218         EI.setOperand(0, V);
12219         return &EI;
12220       }
12221     }
12222     
12223     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12224       return ReplaceInstUsesWith(EI, Elt);
12225     
12226     // If the this extractelement is directly using a bitcast from a vector of
12227     // the same number of elements, see if we can find the source element from
12228     // it.  In this case, we will end up needing to bitcast the scalars.
12229     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12230       if (const VectorType *VT = 
12231               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12232         if (VT->getNumElements() == VectorWidth)
12233           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12234                                              IndexVal, Context))
12235             return new BitCastInst(Elt, EI.getType());
12236     }
12237   }
12238   
12239   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12240     // Push extractelement into predecessor operation if legal and
12241     // profitable to do so
12242     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12243       if (I->hasOneUse() &&
12244           CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12245         Value *newEI0 =
12246           Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12247                                         EI.getName()+".lhs");
12248         Value *newEI1 =
12249           Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12250                                         EI.getName()+".rhs");
12251         return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12252       }
12253     } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12254       // Extracting the inserted element?
12255       if (IE->getOperand(2) == EI.getOperand(1))
12256         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12257       // If the inserted and extracted elements are constants, they must not
12258       // be the same value, extract from the pre-inserted value instead.
12259       if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
12260         Worklist.AddValue(EI.getOperand(0));
12261         EI.setOperand(0, IE->getOperand(0));
12262         return &EI;
12263       }
12264     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12265       // If this is extracting an element from a shufflevector, figure out where
12266       // it came from and extract from the appropriate input element instead.
12267       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12268         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12269         Value *Src;
12270         unsigned LHSWidth =
12271           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12272
12273         if (SrcIdx < LHSWidth)
12274           Src = SVI->getOperand(0);
12275         else if (SrcIdx < LHSWidth*2) {
12276           SrcIdx -= LHSWidth;
12277           Src = SVI->getOperand(1);
12278         } else {
12279           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12280         }
12281         return ExtractElementInst::Create(Src,
12282                          ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12283                                           false));
12284       }
12285     }
12286     // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12287   }
12288   return 0;
12289 }
12290
12291 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12292 /// elements from either LHS or RHS, return the shuffle mask and true. 
12293 /// Otherwise, return false.
12294 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12295                                          std::vector<Constant*> &Mask,
12296                                          LLVMContext *Context) {
12297   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12298          "Invalid CollectSingleShuffleElements");
12299   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12300
12301   if (isa<UndefValue>(V)) {
12302     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12303     return true;
12304   } else if (V == LHS) {
12305     for (unsigned i = 0; i != NumElts; ++i)
12306       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12307     return true;
12308   } else if (V == RHS) {
12309     for (unsigned i = 0; i != NumElts; ++i)
12310       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
12311     return true;
12312   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12313     // If this is an insert of an extract from some other vector, include it.
12314     Value *VecOp    = IEI->getOperand(0);
12315     Value *ScalarOp = IEI->getOperand(1);
12316     Value *IdxOp    = IEI->getOperand(2);
12317     
12318     if (!isa<ConstantInt>(IdxOp))
12319       return false;
12320     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12321     
12322     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12323       // Okay, we can handle this if the vector we are insertinting into is
12324       // transitively ok.
12325       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12326         // If so, update the mask to reflect the inserted undef.
12327         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
12328         return true;
12329       }      
12330     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12331       if (isa<ConstantInt>(EI->getOperand(1)) &&
12332           EI->getOperand(0)->getType() == V->getType()) {
12333         unsigned ExtractedIdx =
12334           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12335         
12336         // This must be extracting from either LHS or RHS.
12337         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12338           // Okay, we can handle this if the vector we are insertinting into is
12339           // transitively ok.
12340           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12341             // If so, update the mask to reflect the inserted value.
12342             if (EI->getOperand(0) == LHS) {
12343               Mask[InsertedIdx % NumElts] = 
12344                  ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12345             } else {
12346               assert(EI->getOperand(0) == RHS);
12347               Mask[InsertedIdx % NumElts] = 
12348                 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
12349               
12350             }
12351             return true;
12352           }
12353         }
12354       }
12355     }
12356   }
12357   // TODO: Handle shufflevector here!
12358   
12359   return false;
12360 }
12361
12362 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12363 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12364 /// that computes V and the LHS value of the shuffle.
12365 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12366                                      Value *&RHS, LLVMContext *Context) {
12367   assert(isa<VectorType>(V->getType()) && 
12368          (RHS == 0 || V->getType() == RHS->getType()) &&
12369          "Invalid shuffle!");
12370   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12371
12372   if (isa<UndefValue>(V)) {
12373     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12374     return V;
12375   } else if (isa<ConstantAggregateZero>(V)) {
12376     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
12377     return V;
12378   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12379     // If this is an insert of an extract from some other vector, include it.
12380     Value *VecOp    = IEI->getOperand(0);
12381     Value *ScalarOp = IEI->getOperand(1);
12382     Value *IdxOp    = IEI->getOperand(2);
12383     
12384     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12385       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12386           EI->getOperand(0)->getType() == V->getType()) {
12387         unsigned ExtractedIdx =
12388           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12389         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12390         
12391         // Either the extracted from or inserted into vector must be RHSVec,
12392         // otherwise we'd end up with a shuffle of three inputs.
12393         if (EI->getOperand(0) == RHS || RHS == 0) {
12394           RHS = EI->getOperand(0);
12395           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12396           Mask[InsertedIdx % NumElts] = 
12397             ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
12398           return V;
12399         }
12400         
12401         if (VecOp == RHS) {
12402           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12403                                             RHS, Context);
12404           // Everything but the extracted element is replaced with the RHS.
12405           for (unsigned i = 0; i != NumElts; ++i) {
12406             if (i != InsertedIdx)
12407               Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
12408           }
12409           return V;
12410         }
12411         
12412         // If this insertelement is a chain that comes from exactly these two
12413         // vectors, return the vector and the effective shuffle.
12414         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12415                                          Context))
12416           return EI->getOperand(0);
12417         
12418       }
12419     }
12420   }
12421   // TODO: Handle shufflevector here!
12422   
12423   // Otherwise, can't do anything fancy.  Return an identity vector.
12424   for (unsigned i = 0; i != NumElts; ++i)
12425     Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12426   return V;
12427 }
12428
12429 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12430   Value *VecOp    = IE.getOperand(0);
12431   Value *ScalarOp = IE.getOperand(1);
12432   Value *IdxOp    = IE.getOperand(2);
12433   
12434   // Inserting an undef or into an undefined place, remove this.
12435   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12436     ReplaceInstUsesWith(IE, VecOp);
12437   
12438   // If the inserted element was extracted from some other vector, and if the 
12439   // indexes are constant, try to turn this into a shufflevector operation.
12440   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12441     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12442         EI->getOperand(0)->getType() == IE.getType()) {
12443       unsigned NumVectorElts = IE.getType()->getNumElements();
12444       unsigned ExtractedIdx =
12445         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12446       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12447       
12448       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12449         return ReplaceInstUsesWith(IE, VecOp);
12450       
12451       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12452         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12453       
12454       // If we are extracting a value from a vector, then inserting it right
12455       // back into the same place, just use the input vector.
12456       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12457         return ReplaceInstUsesWith(IE, VecOp);      
12458       
12459       // We could theoretically do this for ANY input.  However, doing so could
12460       // turn chains of insertelement instructions into a chain of shufflevector
12461       // instructions, and right now we do not merge shufflevectors.  As such,
12462       // only do this in a situation where it is clear that there is benefit.
12463       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12464         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12465         // the values of VecOp, except then one read from EIOp0.
12466         // Build a new shuffle mask.
12467         std::vector<Constant*> Mask;
12468         if (isa<UndefValue>(VecOp))
12469           Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
12470         else {
12471           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12472           Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
12473                                                        NumVectorElts));
12474         } 
12475         Mask[InsertedIdx] = 
12476                            ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12477         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12478                                      ConstantVector::get(Mask));
12479       }
12480       
12481       // If this insertelement isn't used by some other insertelement, turn it
12482       // (and any insertelements it points to), into one big shuffle.
12483       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12484         std::vector<Constant*> Mask;
12485         Value *RHS = 0;
12486         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12487         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12488         // We now have a shuffle of LHS, RHS, Mask.
12489         return new ShuffleVectorInst(LHS, RHS,
12490                                      ConstantVector::get(Mask));
12491       }
12492     }
12493   }
12494
12495   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12496   APInt UndefElts(VWidth, 0);
12497   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12498   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12499     return &IE;
12500
12501   return 0;
12502 }
12503
12504
12505 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12506   Value *LHS = SVI.getOperand(0);
12507   Value *RHS = SVI.getOperand(1);
12508   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12509
12510   bool MadeChange = false;
12511
12512   // Undefined shuffle mask -> undefined value.
12513   if (isa<UndefValue>(SVI.getOperand(2)))
12514     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12515
12516   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12517
12518   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12519     return 0;
12520
12521   APInt UndefElts(VWidth, 0);
12522   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12523   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12524     LHS = SVI.getOperand(0);
12525     RHS = SVI.getOperand(1);
12526     MadeChange = true;
12527   }
12528   
12529   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12530   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12531   if (LHS == RHS || isa<UndefValue>(LHS)) {
12532     if (isa<UndefValue>(LHS) && LHS == RHS) {
12533       // shuffle(undef,undef,mask) -> undef.
12534       return ReplaceInstUsesWith(SVI, LHS);
12535     }
12536     
12537     // Remap any references to RHS to use LHS.
12538     std::vector<Constant*> Elts;
12539     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12540       if (Mask[i] >= 2*e)
12541         Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12542       else {
12543         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12544             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12545           Mask[i] = 2*e;     // Turn into undef.
12546           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12547         } else {
12548           Mask[i] = Mask[i] % e;  // Force to LHS.
12549           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
12550         }
12551       }
12552     }
12553     SVI.setOperand(0, SVI.getOperand(1));
12554     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12555     SVI.setOperand(2, ConstantVector::get(Elts));
12556     LHS = SVI.getOperand(0);
12557     RHS = SVI.getOperand(1);
12558     MadeChange = true;
12559   }
12560   
12561   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12562   bool isLHSID = true, isRHSID = true;
12563     
12564   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12565     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12566     // Is this an identity shuffle of the LHS value?
12567     isLHSID &= (Mask[i] == i);
12568       
12569     // Is this an identity shuffle of the RHS value?
12570     isRHSID &= (Mask[i]-e == i);
12571   }
12572
12573   // Eliminate identity shuffles.
12574   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12575   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12576   
12577   // If the LHS is a shufflevector itself, see if we can combine it with this
12578   // one without producing an unusual shuffle.  Here we are really conservative:
12579   // we are absolutely afraid of producing a shuffle mask not in the input
12580   // program, because the code gen may not be smart enough to turn a merged
12581   // shuffle into two specific shuffles: it may produce worse code.  As such,
12582   // we only merge two shuffles if the result is one of the two input shuffle
12583   // masks.  In this case, merging the shuffles just removes one instruction,
12584   // which we know is safe.  This is good for things like turning:
12585   // (splat(splat)) -> splat.
12586   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12587     if (isa<UndefValue>(RHS)) {
12588       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12589
12590       std::vector<unsigned> NewMask;
12591       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12592         if (Mask[i] >= 2*e)
12593           NewMask.push_back(2*e);
12594         else
12595           NewMask.push_back(LHSMask[Mask[i]]);
12596       
12597       // If the result mask is equal to the src shuffle or this shuffle mask, do
12598       // the replacement.
12599       if (NewMask == LHSMask || NewMask == Mask) {
12600         unsigned LHSInNElts =
12601           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12602         std::vector<Constant*> Elts;
12603         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12604           if (NewMask[i] >= LHSInNElts*2) {
12605             Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12606           } else {
12607             Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
12608           }
12609         }
12610         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12611                                      LHSSVI->getOperand(1),
12612                                      ConstantVector::get(Elts));
12613       }
12614     }
12615   }
12616
12617   return MadeChange ? &SVI : 0;
12618 }
12619
12620
12621
12622
12623 /// TryToSinkInstruction - Try to move the specified instruction from its
12624 /// current block into the beginning of DestBlock, which can only happen if it's
12625 /// safe to move the instruction past all of the instructions between it and the
12626 /// end of its block.
12627 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12628   assert(I->hasOneUse() && "Invariants didn't hold!");
12629
12630   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12631   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12632     return false;
12633
12634   // Do not sink alloca instructions out of the entry block.
12635   if (isa<AllocaInst>(I) && I->getParent() ==
12636         &DestBlock->getParent()->getEntryBlock())
12637     return false;
12638
12639   // We can only sink load instructions if there is nothing between the load and
12640   // the end of block that could change the value.
12641   if (I->mayReadFromMemory()) {
12642     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12643          Scan != E; ++Scan)
12644       if (Scan->mayWriteToMemory())
12645         return false;
12646   }
12647
12648   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12649
12650   CopyPrecedingStopPoint(I, InsertPos);
12651   I->moveBefore(InsertPos);
12652   ++NumSunkInst;
12653   return true;
12654 }
12655
12656
12657 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12658 /// all reachable code to the worklist.
12659 ///
12660 /// This has a couple of tricks to make the code faster and more powerful.  In
12661 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12662 /// them to the worklist (this significantly speeds up instcombine on code where
12663 /// many instructions are dead or constant).  Additionally, if we find a branch
12664 /// whose condition is a known constant, we only visit the reachable successors.
12665 ///
12666 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12667                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12668                                        InstCombiner &IC,
12669                                        const TargetData *TD) {
12670   SmallVector<BasicBlock*, 256> Worklist;
12671   Worklist.push_back(BB);
12672
12673   while (!Worklist.empty()) {
12674     BB = Worklist.back();
12675     Worklist.pop_back();
12676     
12677     // We have now visited this block!  If we've already been here, ignore it.
12678     if (!Visited.insert(BB)) continue;
12679
12680     DbgInfoIntrinsic *DBI_Prev = NULL;
12681     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12682       Instruction *Inst = BBI++;
12683       
12684       // DCE instruction if trivially dead.
12685       if (isInstructionTriviallyDead(Inst)) {
12686         ++NumDeadInst;
12687         DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
12688         Inst->eraseFromParent();
12689         continue;
12690       }
12691       
12692       // ConstantProp instruction if trivially constant.
12693       if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12694         DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12695                      << *Inst << '\n');
12696         Inst->replaceAllUsesWith(C);
12697         ++NumConstProp;
12698         Inst->eraseFromParent();
12699         continue;
12700       }
12701      
12702       // If there are two consecutive llvm.dbg.stoppoint calls then
12703       // it is likely that the optimizer deleted code in between these
12704       // two intrinsics. 
12705       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12706       if (DBI_Next) {
12707         if (DBI_Prev
12708             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12709             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12710           IC.Worklist.Remove(DBI_Prev);
12711           DBI_Prev->eraseFromParent();
12712         }
12713         DBI_Prev = DBI_Next;
12714       } else {
12715         DBI_Prev = 0;
12716       }
12717
12718       IC.Worklist.Add(Inst);
12719     }
12720
12721     // Recursively visit successors.  If this is a branch or switch on a
12722     // constant, only visit the reachable successor.
12723     TerminatorInst *TI = BB->getTerminator();
12724     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12725       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12726         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12727         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12728         Worklist.push_back(ReachableBB);
12729         continue;
12730       }
12731     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12732       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12733         // See if this is an explicit destination.
12734         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12735           if (SI->getCaseValue(i) == Cond) {
12736             BasicBlock *ReachableBB = SI->getSuccessor(i);
12737             Worklist.push_back(ReachableBB);
12738             continue;
12739           }
12740         
12741         // Otherwise it is the default destination.
12742         Worklist.push_back(SI->getSuccessor(0));
12743         continue;
12744       }
12745     }
12746     
12747     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12748       Worklist.push_back(TI->getSuccessor(i));
12749   }
12750 }
12751
12752 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12753   MadeIRChange = false;
12754   TD = getAnalysisIfAvailable<TargetData>();
12755   
12756   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12757         << F.getNameStr() << "\n");
12758
12759   {
12760     // Do a depth-first traversal of the function, populate the worklist with
12761     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12762     // track of which blocks we visit.
12763     SmallPtrSet<BasicBlock*, 64> Visited;
12764     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12765
12766     // Do a quick scan over the function.  If we find any blocks that are
12767     // unreachable, remove any instructions inside of them.  This prevents
12768     // the instcombine code from having to deal with some bad special cases.
12769     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12770       if (!Visited.count(BB)) {
12771         Instruction *Term = BB->getTerminator();
12772         while (Term != BB->begin()) {   // Remove instrs bottom-up
12773           BasicBlock::iterator I = Term; --I;
12774
12775           DEBUG(errs() << "IC: DCE: " << *I << '\n');
12776           // A debug intrinsic shouldn't force another iteration if we weren't
12777           // going to do one without it.
12778           if (!isa<DbgInfoIntrinsic>(I)) {
12779             ++NumDeadInst;
12780             MadeIRChange = true;
12781           }
12782           if (!I->use_empty())
12783             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12784           I->eraseFromParent();
12785         }
12786       }
12787   }
12788
12789   while (!Worklist.isEmpty()) {
12790     Instruction *I = Worklist.RemoveOne();
12791     if (I == 0) continue;  // skip null values.
12792
12793     // Check to see if we can DCE the instruction.
12794     if (isInstructionTriviallyDead(I)) {
12795       DEBUG(errs() << "IC: DCE: " << *I << '\n');
12796       EraseInstFromFunction(*I);
12797       ++NumDeadInst;
12798       MadeIRChange = true;
12799       continue;
12800     }
12801
12802     // Instruction isn't dead, see if we can constant propagate it.
12803     if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12804       DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
12805
12806       // Add operands to the worklist.
12807       ReplaceInstUsesWith(*I, C);
12808       ++NumConstProp;
12809       EraseInstFromFunction(*I);
12810       MadeIRChange = true;
12811       continue;
12812     }
12813
12814     if (TD) {
12815       // See if we can constant fold its operands.
12816       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12817         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12818           if (Constant *NewC = ConstantFoldConstantExpression(CE,   
12819                                   F.getContext(), TD))
12820             if (NewC != CE) {
12821               i->set(NewC);
12822               MadeIRChange = true;
12823             }
12824     }
12825
12826     // See if we can trivially sink this instruction to a successor basic block.
12827     if (I->hasOneUse()) {
12828       BasicBlock *BB = I->getParent();
12829       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12830       if (UserParent != BB) {
12831         bool UserIsSuccessor = false;
12832         // See if the user is one of our successors.
12833         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12834           if (*SI == UserParent) {
12835             UserIsSuccessor = true;
12836             break;
12837           }
12838
12839         // If the user is one of our immediate successors, and if that successor
12840         // only has us as a predecessors (we'd have to split the critical edge
12841         // otherwise), we can keep going.
12842         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12843             next(pred_begin(UserParent)) == pred_end(UserParent))
12844           // Okay, the CFG is simple enough, try to sink this instruction.
12845           MadeIRChange |= TryToSinkInstruction(I, UserParent);
12846       }
12847     }
12848
12849     // Now that we have an instruction, try combining it to simplify it.
12850     Builder->SetInsertPoint(I->getParent(), I);
12851     
12852 #ifndef NDEBUG
12853     std::string OrigI;
12854 #endif
12855     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
12856     
12857     if (Instruction *Result = visit(*I)) {
12858       ++NumCombined;
12859       // Should we replace the old instruction with a new one?
12860       if (Result != I) {
12861         DEBUG(errs() << "IC: Old = " << *I << '\n'
12862                      << "    New = " << *Result << '\n');
12863
12864         // Everything uses the new instruction now.
12865         I->replaceAllUsesWith(Result);
12866
12867         // Push the new instruction and any users onto the worklist.
12868         Worklist.Add(Result);
12869         Worklist.AddUsersToWorkList(*Result);
12870
12871         // Move the name to the new instruction first.
12872         Result->takeName(I);
12873
12874         // Insert the new instruction into the basic block...
12875         BasicBlock *InstParent = I->getParent();
12876         BasicBlock::iterator InsertPos = I;
12877
12878         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12879           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12880             ++InsertPos;
12881
12882         InstParent->getInstList().insert(InsertPos, Result);
12883
12884         EraseInstFromFunction(*I);
12885       } else {
12886 #ifndef NDEBUG
12887         DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12888                      << "    New = " << *I << '\n');
12889 #endif
12890
12891         // If the instruction was modified, it's possible that it is now dead.
12892         // if so, remove it.
12893         if (isInstructionTriviallyDead(I)) {
12894           EraseInstFromFunction(*I);
12895         } else {
12896           Worklist.Add(I);
12897           Worklist.AddUsersToWorkList(*I);
12898         }
12899       }
12900       MadeIRChange = true;
12901     }
12902   }
12903
12904   Worklist.Zap();
12905   return MadeIRChange;
12906 }
12907
12908
12909 bool InstCombiner::runOnFunction(Function &F) {
12910   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12911   Context = &F.getContext();
12912   
12913   
12914   /// Builder - This is an IRBuilder that automatically inserts new
12915   /// instructions into the worklist when they are created.
12916   IRBuilder<true, ConstantFolder, InstCombineIRInserter> 
12917     TheBuilder(F.getContext(), ConstantFolder(F.getContext()),
12918                InstCombineIRInserter(Worklist));
12919   Builder = &TheBuilder;
12920   
12921   bool EverMadeChange = false;
12922
12923   // Iterate while there is work to do.
12924   unsigned Iteration = 0;
12925   while (DoOneIteration(F, Iteration++))
12926     EverMadeChange = true;
12927   
12928   Builder = 0;
12929   return EverMadeChange;
12930 }
12931
12932 FunctionPass *llvm::createInstructionCombiningPass() {
12933   return new InstCombiner();
12934 }