eliminate InsertBitCastBefore, just use the builder instead.
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions.  This pass does not modify the CFG.  This pass is where
12 // algebraic simplification happens.
13 //
14 // This pass combines things like:
15 //    %Y = add i32 %X, 1
16 //    %Z = add i32 %Y, 1
17 // into:
18 //    %Z = add i32 %X, 2
19 //
20 // This is a simple worklist driven algorithm.
21 //
22 // This pass guarantees that the following canonicalizations are performed on
23 // the program:
24 //    1. If a binary operator has a constant operand, it is moved to the RHS
25 //    2. Bitwise operators with constant operands are always grouped so that
26 //       shifts are performed first, then or's, then and's, then xor's.
27 //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All cmp instructions on boolean values are replaced with logical ops
29 //    5. add X, X is represented as (X*2) => (X << 1)
30 //    6. Multiplies with a power-of-two constant argument are transformed into
31 //       shifts.
32 //   ... etc.
33 //
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/LLVMContext.h"
40 #include "llvm/Pass.h"
41 #include "llvm/DerivedTypes.h"
42 #include "llvm/GlobalVariable.h"
43 #include "llvm/Operator.h"
44 #include "llvm/Analysis/ConstantFolding.h"
45 #include "llvm/Analysis/ValueTracking.h"
46 #include "llvm/Target/TargetData.h"
47 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
48 #include "llvm/Transforms/Utils/Local.h"
49 #include "llvm/Support/CallSite.h"
50 #include "llvm/Support/ConstantRange.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/GetElementPtrTypeIterator.h"
54 #include "llvm/Support/InstVisitor.h"
55 #include "llvm/Support/IRBuilder.h"
56 #include "llvm/Support/MathExtras.h"
57 #include "llvm/Support/PatternMatch.h"
58 #include "llvm/Support/Compiler.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include "llvm/ADT/DenseMap.h"
61 #include "llvm/ADT/SmallVector.h"
62 #include "llvm/ADT/SmallPtrSet.h"
63 #include "llvm/ADT/Statistic.h"
64 #include "llvm/ADT/STLExtras.h"
65 #include <algorithm>
66 #include <climits>
67 using namespace llvm;
68 using namespace llvm::PatternMatch;
69
70 STATISTIC(NumCombined , "Number of insts combined");
71 STATISTIC(NumConstProp, "Number of constant folds");
72 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
73 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
74 STATISTIC(NumSunkInst , "Number of instructions sunk");
75
76 namespace {
77   /// InstCombineWorklist - This is the worklist management logic for
78   /// InstCombine.
79   class InstCombineWorklist {
80     SmallVector<Instruction*, 256> Worklist;
81     DenseMap<Instruction*, unsigned> WorklistMap;
82     
83     void operator=(const InstCombineWorklist&RHS);   // DO NOT IMPLEMENT
84     InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
85   public:
86     InstCombineWorklist() {}
87     
88     bool isEmpty() const { return Worklist.empty(); }
89     
90     /// Add - Add the specified instruction to the worklist if it isn't already
91     /// in it.
92     void Add(Instruction *I) {
93       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
94         Worklist.push_back(I);
95     }
96     
97     void AddValue(Value *V) {
98       if (Instruction *I = dyn_cast<Instruction>(V))
99         Add(I);
100     }
101     
102     // Remove - remove I from the worklist if it exists.
103     void Remove(Instruction *I) {
104       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
105       if (It == WorklistMap.end()) return; // Not in worklist.
106       
107       // Don't bother moving everything down, just null out the slot.
108       Worklist[It->second] = 0;
109       
110       WorklistMap.erase(It);
111     }
112     
113     Instruction *RemoveOne() {
114       Instruction *I = Worklist.back();
115       Worklist.pop_back();
116       WorklistMap.erase(I);
117       return I;
118     }
119
120     /// AddUsersToWorkList - When an instruction is simplified, add all users of
121     /// the instruction to the work lists because they might get more simplified
122     /// now.
123     ///
124     void AddUsersToWorkList(Instruction &I) {
125       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
126            UI != UE; ++UI)
127         Add(cast<Instruction>(*UI));
128     }
129     
130     
131     /// Zap - check that the worklist is empty and nuke the backing store for
132     /// the map if it is large.
133     void Zap() {
134       assert(WorklistMap.empty() && "Worklist empty, but map not?");
135       
136       // Do an explicit clear, this shrinks the map if needed.
137       WorklistMap.clear();
138     }
139   };
140 } // end anonymous namespace.
141
142
143 namespace {
144   /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
145   /// just like the normal insertion helper, but also adds any new instructions
146   /// to the instcombine worklist.
147   class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
148     InstCombineWorklist &Worklist;
149   public:
150     InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
151     
152     void InsertHelper(Instruction *I, const Twine &Name,
153                       BasicBlock *BB, BasicBlock::iterator InsertPt) const {
154       IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
155       Worklist.Add(I);
156     }
157   };
158 } // end anonymous namespace
159
160
161 namespace {
162   class VISIBILITY_HIDDEN InstCombiner
163     : public FunctionPass,
164       public InstVisitor<InstCombiner, Instruction*> {
165     TargetData *TD;
166     bool MustPreserveLCSSA;
167   public:
168     /// Worklist - All of the instructions that need to be simplified.
169     InstCombineWorklist Worklist;
170
171     /// Builder - This is an IRBuilder that automatically inserts new
172     /// instructions into the worklist when they are created.
173     typedef IRBuilder<true, ConstantFolder, InstCombineIRInserter> BuilderTy;
174     BuilderTy *Builder;
175         
176     static char ID; // Pass identification, replacement for typeid
177     InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
178
179     LLVMContext *Context;
180     LLVMContext *getContext() const { return Context; }
181
182   public:
183     virtual bool runOnFunction(Function &F);
184     
185     bool DoOneIteration(Function &F, unsigned ItNum);
186
187     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
188       AU.addPreservedID(LCSSAID);
189       AU.setPreservesCFG();
190     }
191
192     TargetData *getTargetData() const { return TD; }
193
194     // Visitation implementation - Implement instruction combining for different
195     // instruction types.  The semantics are as follows:
196     // Return Value:
197     //    null        - No change was made
198     //     I          - Change was made, I is still valid, I may be dead though
199     //   otherwise    - Change was made, replace I with returned instruction
200     //
201     Instruction *visitAdd(BinaryOperator &I);
202     Instruction *visitFAdd(BinaryOperator &I);
203     Instruction *visitSub(BinaryOperator &I);
204     Instruction *visitFSub(BinaryOperator &I);
205     Instruction *visitMul(BinaryOperator &I);
206     Instruction *visitFMul(BinaryOperator &I);
207     Instruction *visitURem(BinaryOperator &I);
208     Instruction *visitSRem(BinaryOperator &I);
209     Instruction *visitFRem(BinaryOperator &I);
210     bool SimplifyDivRemOfSelect(BinaryOperator &I);
211     Instruction *commonRemTransforms(BinaryOperator &I);
212     Instruction *commonIRemTransforms(BinaryOperator &I);
213     Instruction *commonDivTransforms(BinaryOperator &I);
214     Instruction *commonIDivTransforms(BinaryOperator &I);
215     Instruction *visitUDiv(BinaryOperator &I);
216     Instruction *visitSDiv(BinaryOperator &I);
217     Instruction *visitFDiv(BinaryOperator &I);
218     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
219     Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
220     Instruction *visitAnd(BinaryOperator &I);
221     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
222     Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
223     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
224                                      Value *A, Value *B, Value *C);
225     Instruction *visitOr (BinaryOperator &I);
226     Instruction *visitXor(BinaryOperator &I);
227     Instruction *visitShl(BinaryOperator &I);
228     Instruction *visitAShr(BinaryOperator &I);
229     Instruction *visitLShr(BinaryOperator &I);
230     Instruction *commonShiftTransforms(BinaryOperator &I);
231     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
232                                       Constant *RHSC);
233     Instruction *visitFCmpInst(FCmpInst &I);
234     Instruction *visitICmpInst(ICmpInst &I);
235     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
236     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
237                                                 Instruction *LHS,
238                                                 ConstantInt *RHS);
239     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
240                                 ConstantInt *DivRHS);
241
242     Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
243                              ICmpInst::Predicate Cond, Instruction &I);
244     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
245                                      BinaryOperator &I);
246     Instruction *commonCastTransforms(CastInst &CI);
247     Instruction *commonIntCastTransforms(CastInst &CI);
248     Instruction *commonPointerCastTransforms(CastInst &CI);
249     Instruction *visitTrunc(TruncInst &CI);
250     Instruction *visitZExt(ZExtInst &CI);
251     Instruction *visitSExt(SExtInst &CI);
252     Instruction *visitFPTrunc(FPTruncInst &CI);
253     Instruction *visitFPExt(CastInst &CI);
254     Instruction *visitFPToUI(FPToUIInst &FI);
255     Instruction *visitFPToSI(FPToSIInst &FI);
256     Instruction *visitUIToFP(CastInst &CI);
257     Instruction *visitSIToFP(CastInst &CI);
258     Instruction *visitPtrToInt(PtrToIntInst &CI);
259     Instruction *visitIntToPtr(IntToPtrInst &CI);
260     Instruction *visitBitCast(BitCastInst &CI);
261     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
262                                 Instruction *FI);
263     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
264     Instruction *visitSelectInst(SelectInst &SI);
265     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
266     Instruction *visitCallInst(CallInst &CI);
267     Instruction *visitInvokeInst(InvokeInst &II);
268     Instruction *visitPHINode(PHINode &PN);
269     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
270     Instruction *visitAllocationInst(AllocationInst &AI);
271     Instruction *visitFreeInst(FreeInst &FI);
272     Instruction *visitLoadInst(LoadInst &LI);
273     Instruction *visitStoreInst(StoreInst &SI);
274     Instruction *visitBranchInst(BranchInst &BI);
275     Instruction *visitSwitchInst(SwitchInst &SI);
276     Instruction *visitInsertElementInst(InsertElementInst &IE);
277     Instruction *visitExtractElementInst(ExtractElementInst &EI);
278     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
279     Instruction *visitExtractValueInst(ExtractValueInst &EV);
280
281     // visitInstruction - Specify what to return for unhandled instructions...
282     Instruction *visitInstruction(Instruction &I) { return 0; }
283
284   private:
285     Instruction *visitCallSite(CallSite CS);
286     bool transformConstExprCastCall(CallSite CS);
287     Instruction *transformCallThroughTrampoline(CallSite CS);
288     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
289                                    bool DoXform = true);
290     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
291     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
292
293
294   public:
295     // InsertNewInstBefore - insert an instruction New before instruction Old
296     // in the program.  Add the new instruction to the worklist.
297     //
298     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
299       assert(New && New->getParent() == 0 &&
300              "New instruction already inserted into a basic block!");
301       BasicBlock *BB = Old.getParent();
302       BB->getInstList().insert(&Old, New);  // Insert inst
303       Worklist.Add(New);
304       return New;
305     }
306
307     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
308     /// This also adds the cast to the worklist.  Finally, this returns the
309     /// cast.
310     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
311                             Instruction &Pos) {
312       if (V->getType() == Ty) return V;
313
314       if (Constant *CV = dyn_cast<Constant>(V))
315         return ConstantExpr::getCast(opc, CV, Ty);
316       
317       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
318       Worklist.Add(C);
319       return C;
320     }
321         
322     // ReplaceInstUsesWith - This method is to be used when an instruction is
323     // found to be dead, replacable with another preexisting expression.  Here
324     // we add all uses of I to the worklist, replace all uses of I with the new
325     // value, then return I, so that the inst combiner will know that I was
326     // modified.
327     //
328     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
329       Worklist.AddUsersToWorkList(I);   // Add all modified instrs to worklist.
330       
331       // If we are replacing the instruction with itself, this must be in a
332       // segment of unreachable code, so just clobber the instruction.
333       if (&I == V) 
334         V = UndefValue::get(I.getType());
335         
336       I.replaceAllUsesWith(V);
337       return &I;
338     }
339
340     // EraseInstFromFunction - When dealing with an instruction that has side
341     // effects or produces a void value, we can't rely on DCE to delete the
342     // instruction.  Instead, visit methods should return the value returned by
343     // this function.
344     Instruction *EraseInstFromFunction(Instruction &I) {
345       assert(I.use_empty() && "Cannot erase instruction that is used!");
346       // Make sure that we reprocess all operands now that we reduced their
347       // use counts.
348       if (I.getNumOperands() < 8) {
349         for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
350           if (Instruction *Op = dyn_cast<Instruction>(*i))
351             Worklist.Add(Op);
352       }
353       Worklist.Remove(&I);
354       I.eraseFromParent();
355       return 0;  // Don't do anything with FI
356     }
357         
358     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
359                            APInt &KnownOne, unsigned Depth = 0) const {
360       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
361     }
362     
363     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
364                            unsigned Depth = 0) const {
365       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
366     }
367     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
368       return llvm::ComputeNumSignBits(Op, TD, Depth);
369     }
370
371   private:
372
373     /// SimplifyCommutative - This performs a few simplifications for 
374     /// commutative operators.
375     bool SimplifyCommutative(BinaryOperator &I);
376
377     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
378     /// most-complex to least-complex order.
379     bool SimplifyCompare(CmpInst &I);
380
381     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
382     /// based on the demanded bits.
383     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
384                                    APInt& KnownZero, APInt& KnownOne,
385                                    unsigned Depth);
386     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
387                               APInt& KnownZero, APInt& KnownOne,
388                               unsigned Depth=0);
389         
390     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
391     /// SimplifyDemandedBits knows about.  See if the instruction has any
392     /// properties that allow us to simplify its operands.
393     bool SimplifyDemandedInstructionBits(Instruction &Inst);
394         
395     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
396                                       APInt& UndefElts, unsigned Depth = 0);
397       
398     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
399     // PHI node as operand #0, see if we can fold the instruction into the PHI
400     // (which is only possible if all operands to the PHI are constants).
401     Instruction *FoldOpIntoPhi(Instruction &I);
402
403     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
404     // operator and they all are only used by the PHI, PHI together their
405     // inputs, and do the operation once, to the result of the PHI.
406     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
407     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
408     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
409
410     
411     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
412                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
413     
414     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
415                               bool isSub, Instruction &I);
416     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
417                                  bool isSigned, bool Inside, Instruction &IB);
418     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
419     Instruction *MatchBSwap(BinaryOperator &I);
420     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
421     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
422     Instruction *SimplifyMemSet(MemSetInst *MI);
423
424
425     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
426
427     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
428                                     unsigned CastOpc, int &NumCastsRemoved);
429     unsigned GetOrEnforceKnownAlignment(Value *V,
430                                         unsigned PrefAlign = 0);
431
432   };
433 } // end anonymous namespace
434
435 char InstCombiner::ID = 0;
436 static RegisterPass<InstCombiner>
437 X("instcombine", "Combine redundant instructions");
438
439 // getComplexity:  Assign a complexity or rank value to LLVM Values...
440 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
441 static unsigned getComplexity(Value *V) {
442   if (isa<Instruction>(V)) {
443     if (BinaryOperator::isNeg(V) ||
444         BinaryOperator::isFNeg(V) ||
445         BinaryOperator::isNot(V))
446       return 3;
447     return 4;
448   }
449   if (isa<Argument>(V)) return 3;
450   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
451 }
452
453 // isOnlyUse - Return true if this instruction will be deleted if we stop using
454 // it.
455 static bool isOnlyUse(Value *V) {
456   return V->hasOneUse() || isa<Constant>(V);
457 }
458
459 // getPromotedType - Return the specified type promoted as it would be to pass
460 // though a va_arg area...
461 static const Type *getPromotedType(const Type *Ty) {
462   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
463     if (ITy->getBitWidth() < 32)
464       return Type::getInt32Ty(Ty->getContext());
465   }
466   return Ty;
467 }
468
469 /// getBitCastOperand - If the specified operand is a CastInst, a constant
470 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
471 /// operand value, otherwise return null.
472 static Value *getBitCastOperand(Value *V) {
473   if (Operator *O = dyn_cast<Operator>(V)) {
474     if (O->getOpcode() == Instruction::BitCast)
475       return O->getOperand(0);
476     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
477       if (GEP->hasAllZeroIndices())
478         return GEP->getPointerOperand();
479   }
480   return 0;
481 }
482
483 /// This function is a wrapper around CastInst::isEliminableCastPair. It
484 /// simply extracts arguments and returns what that function returns.
485 static Instruction::CastOps 
486 isEliminableCastPair(
487   const CastInst *CI, ///< The first cast instruction
488   unsigned opcode,       ///< The opcode of the second cast instruction
489   const Type *DstTy,     ///< The target type for the second cast instruction
490   TargetData *TD         ///< The target data for pointer size
491 ) {
492
493   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
494   const Type *MidTy = CI->getType();                  // B from above
495
496   // Get the opcodes of the two Cast instructions
497   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
498   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
499
500   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
501                                                 DstTy,
502                                   TD ? TD->getIntPtrType(CI->getContext()) : 0);
503   
504   // We don't want to form an inttoptr or ptrtoint that converts to an integer
505   // type that differs from the pointer size.
506   if ((Res == Instruction::IntToPtr &&
507           (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
508       (Res == Instruction::PtrToInt &&
509           (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
510     Res = 0;
511   
512   return Instruction::CastOps(Res);
513 }
514
515 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
516 /// in any code being generated.  It does not require codegen if V is simple
517 /// enough or if the cast can be folded into other casts.
518 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
519                               const Type *Ty, TargetData *TD) {
520   if (V->getType() == Ty || isa<Constant>(V)) return false;
521   
522   // If this is another cast that can be eliminated, it isn't codegen either.
523   if (const CastInst *CI = dyn_cast<CastInst>(V))
524     if (isEliminableCastPair(CI, opcode, Ty, TD))
525       return false;
526   return true;
527 }
528
529 // SimplifyCommutative - This performs a few simplifications for commutative
530 // operators:
531 //
532 //  1. Order operands such that they are listed from right (least complex) to
533 //     left (most complex).  This puts constants before unary operators before
534 //     binary operators.
535 //
536 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
537 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
538 //
539 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
540   bool Changed = false;
541   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
542     Changed = !I.swapOperands();
543
544   if (!I.isAssociative()) return Changed;
545   Instruction::BinaryOps Opcode = I.getOpcode();
546   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
547     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
548       if (isa<Constant>(I.getOperand(1))) {
549         Constant *Folded = ConstantExpr::get(I.getOpcode(),
550                                              cast<Constant>(I.getOperand(1)),
551                                              cast<Constant>(Op->getOperand(1)));
552         I.setOperand(0, Op->getOperand(0));
553         I.setOperand(1, Folded);
554         return true;
555       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
556         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
557             isOnlyUse(Op) && isOnlyUse(Op1)) {
558           Constant *C1 = cast<Constant>(Op->getOperand(1));
559           Constant *C2 = cast<Constant>(Op1->getOperand(1));
560
561           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
562           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
563           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
564                                                     Op1->getOperand(0),
565                                                     Op1->getName(), &I);
566           Worklist.Add(New);
567           I.setOperand(0, New);
568           I.setOperand(1, Folded);
569           return true;
570         }
571     }
572   return Changed;
573 }
574
575 /// SimplifyCompare - For a CmpInst this function just orders the operands
576 /// so that theyare listed from right (least complex) to left (most complex).
577 /// This puts constants before unary operators before binary operators.
578 bool InstCombiner::SimplifyCompare(CmpInst &I) {
579   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
580     return false;
581   I.swapOperands();
582   // Compare instructions are not associative so there's nothing else we can do.
583   return true;
584 }
585
586 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
587 // if the LHS is a constant zero (which is the 'negate' form).
588 //
589 static inline Value *dyn_castNegVal(Value *V) {
590   if (BinaryOperator::isNeg(V))
591     return BinaryOperator::getNegArgument(V);
592
593   // Constants can be considered to be negated values if they can be folded.
594   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
595     return ConstantExpr::getNeg(C);
596
597   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
598     if (C->getType()->getElementType()->isInteger())
599       return ConstantExpr::getNeg(C);
600
601   return 0;
602 }
603
604 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
605 // instruction if the LHS is a constant negative zero (which is the 'negate'
606 // form).
607 //
608 static inline Value *dyn_castFNegVal(Value *V) {
609   if (BinaryOperator::isFNeg(V))
610     return BinaryOperator::getFNegArgument(V);
611
612   // Constants can be considered to be negated values if they can be folded.
613   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
614     return ConstantExpr::getFNeg(C);
615
616   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
617     if (C->getType()->getElementType()->isFloatingPoint())
618       return ConstantExpr::getFNeg(C);
619
620   return 0;
621 }
622
623 static inline Value *dyn_castNotVal(Value *V) {
624   if (BinaryOperator::isNot(V))
625     return BinaryOperator::getNotArgument(V);
626
627   // Constants can be considered to be not'ed values...
628   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
629     return ConstantInt::get(C->getType(), ~C->getValue());
630   return 0;
631 }
632
633 // dyn_castFoldableMul - If this value is a multiply that can be folded into
634 // other computations (because it has a constant operand), return the
635 // non-constant operand of the multiply, and set CST to point to the multiplier.
636 // Otherwise, return null.
637 //
638 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
639   if (V->hasOneUse() && V->getType()->isInteger())
640     if (Instruction *I = dyn_cast<Instruction>(V)) {
641       if (I->getOpcode() == Instruction::Mul)
642         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
643           return I->getOperand(0);
644       if (I->getOpcode() == Instruction::Shl)
645         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
646           // The multiplier is really 1 << CST.
647           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
648           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
649           CST = ConstantInt::get(V->getType()->getContext(),
650                                  APInt(BitWidth, 1).shl(CSTVal));
651           return I->getOperand(0);
652         }
653     }
654   return 0;
655 }
656
657 /// AddOne - Add one to a ConstantInt
658 static Constant *AddOne(Constant *C) {
659   return ConstantExpr::getAdd(C, 
660     ConstantInt::get(C->getType(), 1));
661 }
662 /// SubOne - Subtract one from a ConstantInt
663 static Constant *SubOne(ConstantInt *C) {
664   return ConstantExpr::getSub(C, 
665     ConstantInt::get(C->getType(), 1));
666 }
667 /// MultiplyOverflows - True if the multiply can not be expressed in an int
668 /// this size.
669 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
670   uint32_t W = C1->getBitWidth();
671   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
672   if (sign) {
673     LHSExt.sext(W * 2);
674     RHSExt.sext(W * 2);
675   } else {
676     LHSExt.zext(W * 2);
677     RHSExt.zext(W * 2);
678   }
679
680   APInt MulExt = LHSExt * RHSExt;
681
682   if (sign) {
683     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
684     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
685     return MulExt.slt(Min) || MulExt.sgt(Max);
686   } else 
687     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
688 }
689
690
691 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
692 /// specified instruction is a constant integer.  If so, check to see if there
693 /// are any bits set in the constant that are not demanded.  If so, shrink the
694 /// constant and return true.
695 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
696                                    APInt Demanded) {
697   assert(I && "No instruction?");
698   assert(OpNo < I->getNumOperands() && "Operand index too large");
699
700   // If the operand is not a constant integer, nothing to do.
701   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
702   if (!OpC) return false;
703
704   // If there are no bits set that aren't demanded, nothing to do.
705   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
706   if ((~Demanded & OpC->getValue()) == 0)
707     return false;
708
709   // This instruction is producing bits that are not demanded. Shrink the RHS.
710   Demanded &= OpC->getValue();
711   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
712   return true;
713 }
714
715 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
716 // set of known zero and one bits, compute the maximum and minimum values that
717 // could have the specified known zero and known one bits, returning them in
718 // min/max.
719 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
720                                                    const APInt& KnownOne,
721                                                    APInt& Min, APInt& Max) {
722   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
723          KnownZero.getBitWidth() == Min.getBitWidth() &&
724          KnownZero.getBitWidth() == Max.getBitWidth() &&
725          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
726   APInt UnknownBits = ~(KnownZero|KnownOne);
727
728   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
729   // bit if it is unknown.
730   Min = KnownOne;
731   Max = KnownOne|UnknownBits;
732   
733   if (UnknownBits.isNegative()) { // Sign bit is unknown
734     Min.set(Min.getBitWidth()-1);
735     Max.clear(Max.getBitWidth()-1);
736   }
737 }
738
739 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
740 // a set of known zero and one bits, compute the maximum and minimum values that
741 // could have the specified known zero and known one bits, returning them in
742 // min/max.
743 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
744                                                      const APInt &KnownOne,
745                                                      APInt &Min, APInt &Max) {
746   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
747          KnownZero.getBitWidth() == Min.getBitWidth() &&
748          KnownZero.getBitWidth() == Max.getBitWidth() &&
749          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
750   APInt UnknownBits = ~(KnownZero|KnownOne);
751   
752   // The minimum value is when the unknown bits are all zeros.
753   Min = KnownOne;
754   // The maximum value is when the unknown bits are all ones.
755   Max = KnownOne|UnknownBits;
756 }
757
758 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
759 /// SimplifyDemandedBits knows about.  See if the instruction has any
760 /// properties that allow us to simplify its operands.
761 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
762   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
763   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
764   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
765   
766   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
767                                      KnownZero, KnownOne, 0);
768   if (V == 0) return false;
769   if (V == &Inst) return true;
770   ReplaceInstUsesWith(Inst, V);
771   return true;
772 }
773
774 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
775 /// specified instruction operand if possible, updating it in place.  It returns
776 /// true if it made any change and false otherwise.
777 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
778                                         APInt &KnownZero, APInt &KnownOne,
779                                         unsigned Depth) {
780   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
781                                           KnownZero, KnownOne, Depth);
782   if (NewVal == 0) return false;
783   U.set(NewVal);
784   return true;
785 }
786
787
788 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
789 /// value based on the demanded bits.  When this function is called, it is known
790 /// that only the bits set in DemandedMask of the result of V are ever used
791 /// downstream. Consequently, depending on the mask and V, it may be possible
792 /// to replace V with a constant or one of its operands. In such cases, this
793 /// function does the replacement and returns true. In all other cases, it
794 /// returns false after analyzing the expression and setting KnownOne and known
795 /// to be one in the expression.  KnownZero contains all the bits that are known
796 /// to be zero in the expression. These are provided to potentially allow the
797 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
798 /// the expression. KnownOne and KnownZero always follow the invariant that 
799 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
800 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
801 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
802 /// and KnownOne must all be the same.
803 ///
804 /// This returns null if it did not change anything and it permits no
805 /// simplification.  This returns V itself if it did some simplification of V's
806 /// operands based on the information about what bits are demanded. This returns
807 /// some other non-null value if it found out that V is equal to another value
808 /// in the context where the specified bits are demanded, but not for all users.
809 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
810                                              APInt &KnownZero, APInt &KnownOne,
811                                              unsigned Depth) {
812   assert(V != 0 && "Null pointer of Value???");
813   assert(Depth <= 6 && "Limit Search Depth");
814   uint32_t BitWidth = DemandedMask.getBitWidth();
815   const Type *VTy = V->getType();
816   assert((TD || !isa<PointerType>(VTy)) &&
817          "SimplifyDemandedBits needs to know bit widths!");
818   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
819          (!VTy->isIntOrIntVector() ||
820           VTy->getScalarSizeInBits() == BitWidth) &&
821          KnownZero.getBitWidth() == BitWidth &&
822          KnownOne.getBitWidth() == BitWidth &&
823          "Value *V, DemandedMask, KnownZero and KnownOne "
824          "must have same BitWidth");
825   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
826     // We know all of the bits for a constant!
827     KnownOne = CI->getValue() & DemandedMask;
828     KnownZero = ~KnownOne & DemandedMask;
829     return 0;
830   }
831   if (isa<ConstantPointerNull>(V)) {
832     // We know all of the bits for a constant!
833     KnownOne.clear();
834     KnownZero = DemandedMask;
835     return 0;
836   }
837
838   KnownZero.clear();
839   KnownOne.clear();
840   if (DemandedMask == 0) {   // Not demanding any bits from V.
841     if (isa<UndefValue>(V))
842       return 0;
843     return UndefValue::get(VTy);
844   }
845   
846   if (Depth == 6)        // Limit search depth.
847     return 0;
848   
849   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
850   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
851
852   Instruction *I = dyn_cast<Instruction>(V);
853   if (!I) {
854     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
855     return 0;        // Only analyze instructions.
856   }
857
858   // If there are multiple uses of this value and we aren't at the root, then
859   // we can't do any simplifications of the operands, because DemandedMask
860   // only reflects the bits demanded by *one* of the users.
861   if (Depth != 0 && !I->hasOneUse()) {
862     // Despite the fact that we can't simplify this instruction in all User's
863     // context, we can at least compute the knownzero/knownone bits, and we can
864     // do simplifications that apply to *just* the one user if we know that
865     // this instruction has a simpler value in that context.
866     if (I->getOpcode() == Instruction::And) {
867       // If either the LHS or the RHS are Zero, the result is zero.
868       ComputeMaskedBits(I->getOperand(1), DemandedMask,
869                         RHSKnownZero, RHSKnownOne, Depth+1);
870       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
871                         LHSKnownZero, LHSKnownOne, Depth+1);
872       
873       // If all of the demanded bits are known 1 on one side, return the other.
874       // These bits cannot contribute to the result of the 'and' in this
875       // context.
876       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
877           (DemandedMask & ~LHSKnownZero))
878         return I->getOperand(0);
879       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
880           (DemandedMask & ~RHSKnownZero))
881         return I->getOperand(1);
882       
883       // If all of the demanded bits in the inputs are known zeros, return zero.
884       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
885         return Constant::getNullValue(VTy);
886       
887     } else if (I->getOpcode() == Instruction::Or) {
888       // We can simplify (X|Y) -> X or Y in the user's context if we know that
889       // only bits from X or Y are demanded.
890       
891       // If either the LHS or the RHS are One, the result is One.
892       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
893                         RHSKnownZero, RHSKnownOne, Depth+1);
894       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
895                         LHSKnownZero, LHSKnownOne, Depth+1);
896       
897       // If all of the demanded bits are known zero on one side, return the
898       // other.  These bits cannot contribute to the result of the 'or' in this
899       // context.
900       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
901           (DemandedMask & ~LHSKnownOne))
902         return I->getOperand(0);
903       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
904           (DemandedMask & ~RHSKnownOne))
905         return I->getOperand(1);
906       
907       // If all of the potentially set bits on one side are known to be set on
908       // the other side, just use the 'other' side.
909       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
910           (DemandedMask & (~RHSKnownZero)))
911         return I->getOperand(0);
912       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
913           (DemandedMask & (~LHSKnownZero)))
914         return I->getOperand(1);
915     }
916     
917     // Compute the KnownZero/KnownOne bits to simplify things downstream.
918     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
919     return 0;
920   }
921   
922   // If this is the root being simplified, allow it to have multiple uses,
923   // just set the DemandedMask to all bits so that we can try to simplify the
924   // operands.  This allows visitTruncInst (for example) to simplify the
925   // operand of a trunc without duplicating all the logic below.
926   if (Depth == 0 && !V->hasOneUse())
927     DemandedMask = APInt::getAllOnesValue(BitWidth);
928   
929   switch (I->getOpcode()) {
930   default:
931     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
932     break;
933   case Instruction::And:
934     // If either the LHS or the RHS are Zero, the result is zero.
935     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
936                              RHSKnownZero, RHSKnownOne, Depth+1) ||
937         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
938                              LHSKnownZero, LHSKnownOne, Depth+1))
939       return I;
940     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
941     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
942
943     // If all of the demanded bits are known 1 on one side, return the other.
944     // These bits cannot contribute to the result of the 'and'.
945     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
946         (DemandedMask & ~LHSKnownZero))
947       return I->getOperand(0);
948     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
949         (DemandedMask & ~RHSKnownZero))
950       return I->getOperand(1);
951     
952     // If all of the demanded bits in the inputs are known zeros, return zero.
953     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
954       return Constant::getNullValue(VTy);
955       
956     // If the RHS is a constant, see if we can simplify it.
957     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
958       return I;
959       
960     // Output known-1 bits are only known if set in both the LHS & RHS.
961     RHSKnownOne &= LHSKnownOne;
962     // Output known-0 are known to be clear if zero in either the LHS | RHS.
963     RHSKnownZero |= LHSKnownZero;
964     break;
965   case Instruction::Or:
966     // If either the LHS or the RHS are One, the result is One.
967     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
968                              RHSKnownZero, RHSKnownOne, Depth+1) ||
969         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
970                              LHSKnownZero, LHSKnownOne, Depth+1))
971       return I;
972     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
973     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
974     
975     // If all of the demanded bits are known zero on one side, return the other.
976     // These bits cannot contribute to the result of the 'or'.
977     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
978         (DemandedMask & ~LHSKnownOne))
979       return I->getOperand(0);
980     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
981         (DemandedMask & ~RHSKnownOne))
982       return I->getOperand(1);
983
984     // If all of the potentially set bits on one side are known to be set on
985     // the other side, just use the 'other' side.
986     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
987         (DemandedMask & (~RHSKnownZero)))
988       return I->getOperand(0);
989     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
990         (DemandedMask & (~LHSKnownZero)))
991       return I->getOperand(1);
992         
993     // If the RHS is a constant, see if we can simplify it.
994     if (ShrinkDemandedConstant(I, 1, DemandedMask))
995       return I;
996           
997     // Output known-0 bits are only known if clear in both the LHS & RHS.
998     RHSKnownZero &= LHSKnownZero;
999     // Output known-1 are known to be set if set in either the LHS | RHS.
1000     RHSKnownOne |= LHSKnownOne;
1001     break;
1002   case Instruction::Xor: {
1003     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1004                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1005         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1006                              LHSKnownZero, LHSKnownOne, Depth+1))
1007       return I;
1008     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1009     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1010     
1011     // If all of the demanded bits are known zero on one side, return the other.
1012     // These bits cannot contribute to the result of the 'xor'.
1013     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1014       return I->getOperand(0);
1015     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1016       return I->getOperand(1);
1017     
1018     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1019     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1020                          (RHSKnownOne & LHSKnownOne);
1021     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1022     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1023                         (RHSKnownOne & LHSKnownZero);
1024     
1025     // If all of the demanded bits are known to be zero on one side or the
1026     // other, turn this into an *inclusive* or.
1027     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1028     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0)
1029       return Builder->CreateOr(I->getOperand(0), I->getOperand(1),I->getName());
1030     
1031     // If all of the demanded bits on one side are known, and all of the set
1032     // bits on that side are also known to be set on the other side, turn this
1033     // into an AND, as we know the bits will be cleared.
1034     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1035     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1036       // all known
1037       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1038         Constant *AndC = Constant::getIntegerValue(VTy,
1039                                                    ~RHSKnownOne & DemandedMask);
1040         Instruction *And = 
1041           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1042         return InsertNewInstBefore(And, *I);
1043       }
1044     }
1045     
1046     // If the RHS is a constant, see if we can simplify it.
1047     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1048     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1049       return I;
1050     
1051     RHSKnownZero = KnownZeroOut;
1052     RHSKnownOne  = KnownOneOut;
1053     break;
1054   }
1055   case Instruction::Select:
1056     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1057                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1058         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1059                              LHSKnownZero, LHSKnownOne, Depth+1))
1060       return I;
1061     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1062     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1063     
1064     // If the operands are constants, see if we can simplify them.
1065     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1066         ShrinkDemandedConstant(I, 2, DemandedMask))
1067       return I;
1068     
1069     // Only known if known in both the LHS and RHS.
1070     RHSKnownOne &= LHSKnownOne;
1071     RHSKnownZero &= LHSKnownZero;
1072     break;
1073   case Instruction::Trunc: {
1074     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1075     DemandedMask.zext(truncBf);
1076     RHSKnownZero.zext(truncBf);
1077     RHSKnownOne.zext(truncBf);
1078     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1079                              RHSKnownZero, RHSKnownOne, Depth+1))
1080       return I;
1081     DemandedMask.trunc(BitWidth);
1082     RHSKnownZero.trunc(BitWidth);
1083     RHSKnownOne.trunc(BitWidth);
1084     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1085     break;
1086   }
1087   case Instruction::BitCast:
1088     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1089       return false;  // vector->int or fp->int?
1090
1091     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1092       if (const VectorType *SrcVTy =
1093             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1094         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1095           // Don't touch a bitcast between vectors of different element counts.
1096           return false;
1097       } else
1098         // Don't touch a scalar-to-vector bitcast.
1099         return false;
1100     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1101       // Don't touch a vector-to-scalar bitcast.
1102       return false;
1103
1104     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1105                              RHSKnownZero, RHSKnownOne, Depth+1))
1106       return I;
1107     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1108     break;
1109   case Instruction::ZExt: {
1110     // Compute the bits in the result that are not present in the input.
1111     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1112     
1113     DemandedMask.trunc(SrcBitWidth);
1114     RHSKnownZero.trunc(SrcBitWidth);
1115     RHSKnownOne.trunc(SrcBitWidth);
1116     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1117                              RHSKnownZero, RHSKnownOne, Depth+1))
1118       return I;
1119     DemandedMask.zext(BitWidth);
1120     RHSKnownZero.zext(BitWidth);
1121     RHSKnownOne.zext(BitWidth);
1122     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1123     // The top bits are known to be zero.
1124     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1125     break;
1126   }
1127   case Instruction::SExt: {
1128     // Compute the bits in the result that are not present in the input.
1129     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1130     
1131     APInt InputDemandedBits = DemandedMask & 
1132                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1133
1134     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1135     // If any of the sign extended bits are demanded, we know that the sign
1136     // bit is demanded.
1137     if ((NewBits & DemandedMask) != 0)
1138       InputDemandedBits.set(SrcBitWidth-1);
1139       
1140     InputDemandedBits.trunc(SrcBitWidth);
1141     RHSKnownZero.trunc(SrcBitWidth);
1142     RHSKnownOne.trunc(SrcBitWidth);
1143     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1144                              RHSKnownZero, RHSKnownOne, Depth+1))
1145       return I;
1146     InputDemandedBits.zext(BitWidth);
1147     RHSKnownZero.zext(BitWidth);
1148     RHSKnownOne.zext(BitWidth);
1149     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1150       
1151     // If the sign bit of the input is known set or clear, then we know the
1152     // top bits of the result.
1153
1154     // If the input sign bit is known zero, or if the NewBits are not demanded
1155     // convert this into a zero extension.
1156     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1157       // Convert to ZExt cast
1158       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1159       return InsertNewInstBefore(NewCast, *I);
1160     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1161       RHSKnownOne |= NewBits;
1162     }
1163     break;
1164   }
1165   case Instruction::Add: {
1166     // Figure out what the input bits are.  If the top bits of the and result
1167     // are not demanded, then the add doesn't demand them from its input
1168     // either.
1169     unsigned NLZ = DemandedMask.countLeadingZeros();
1170       
1171     // If there is a constant on the RHS, there are a variety of xformations
1172     // we can do.
1173     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1174       // If null, this should be simplified elsewhere.  Some of the xforms here
1175       // won't work if the RHS is zero.
1176       if (RHS->isZero())
1177         break;
1178       
1179       // If the top bit of the output is demanded, demand everything from the
1180       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1181       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1182
1183       // Find information about known zero/one bits in the input.
1184       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1185                                LHSKnownZero, LHSKnownOne, Depth+1))
1186         return I;
1187
1188       // If the RHS of the add has bits set that can't affect the input, reduce
1189       // the constant.
1190       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1191         return I;
1192       
1193       // Avoid excess work.
1194       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1195         break;
1196       
1197       // Turn it into OR if input bits are zero.
1198       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1199         Instruction *Or =
1200           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1201                                    I->getName());
1202         return InsertNewInstBefore(Or, *I);
1203       }
1204       
1205       // We can say something about the output known-zero and known-one bits,
1206       // depending on potential carries from the input constant and the
1207       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1208       // bits set and the RHS constant is 0x01001, then we know we have a known
1209       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1210       
1211       // To compute this, we first compute the potential carry bits.  These are
1212       // the bits which may be modified.  I'm not aware of a better way to do
1213       // this scan.
1214       const APInt &RHSVal = RHS->getValue();
1215       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1216       
1217       // Now that we know which bits have carries, compute the known-1/0 sets.
1218       
1219       // Bits are known one if they are known zero in one operand and one in the
1220       // other, and there is no input carry.
1221       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1222                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1223       
1224       // Bits are known zero if they are known zero in both operands and there
1225       // is no input carry.
1226       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1227     } else {
1228       // If the high-bits of this ADD are not demanded, then it does not demand
1229       // the high bits of its LHS or RHS.
1230       if (DemandedMask[BitWidth-1] == 0) {
1231         // Right fill the mask of bits for this ADD to demand the most
1232         // significant bit and all those below it.
1233         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1234         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1235                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1236             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1237                                  LHSKnownZero, LHSKnownOne, Depth+1))
1238           return I;
1239       }
1240     }
1241     break;
1242   }
1243   case Instruction::Sub:
1244     // If the high-bits of this SUB are not demanded, then it does not demand
1245     // the high bits of its LHS or RHS.
1246     if (DemandedMask[BitWidth-1] == 0) {
1247       // Right fill the mask of bits for this SUB to demand the most
1248       // significant bit and all those below it.
1249       uint32_t NLZ = DemandedMask.countLeadingZeros();
1250       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1251       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1252                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1253           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1254                                LHSKnownZero, LHSKnownOne, Depth+1))
1255         return I;
1256     }
1257     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1258     // the known zeros and ones.
1259     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1260     break;
1261   case Instruction::Shl:
1262     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1263       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1264       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1265       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1266                                RHSKnownZero, RHSKnownOne, Depth+1))
1267         return I;
1268       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1269       RHSKnownZero <<= ShiftAmt;
1270       RHSKnownOne  <<= ShiftAmt;
1271       // low bits known zero.
1272       if (ShiftAmt)
1273         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1274     }
1275     break;
1276   case Instruction::LShr:
1277     // For a logical shift right
1278     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1279       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1280       
1281       // Unsigned shift right.
1282       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1283       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1284                                RHSKnownZero, RHSKnownOne, Depth+1))
1285         return I;
1286       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1287       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1288       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1289       if (ShiftAmt) {
1290         // Compute the new bits that are at the top now.
1291         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1292         RHSKnownZero |= HighBits;  // high bits known zero.
1293       }
1294     }
1295     break;
1296   case Instruction::AShr:
1297     // If this is an arithmetic shift right and only the low-bit is set, we can
1298     // always convert this into a logical shr, even if the shift amount is
1299     // variable.  The low bit of the shift cannot be an input sign bit unless
1300     // the shift amount is >= the size of the datatype, which is undefined.
1301     if (DemandedMask == 1) {
1302       // Perform the logical shift right.
1303       Instruction *NewVal = BinaryOperator::CreateLShr(
1304                         I->getOperand(0), I->getOperand(1), I->getName());
1305       return InsertNewInstBefore(NewVal, *I);
1306     }    
1307
1308     // If the sign bit is the only bit demanded by this ashr, then there is no
1309     // need to do it, the shift doesn't change the high bit.
1310     if (DemandedMask.isSignBit())
1311       return I->getOperand(0);
1312     
1313     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1314       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1315       
1316       // Signed shift right.
1317       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1318       // If any of the "high bits" are demanded, we should set the sign bit as
1319       // demanded.
1320       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1321         DemandedMaskIn.set(BitWidth-1);
1322       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1323                                RHSKnownZero, RHSKnownOne, Depth+1))
1324         return I;
1325       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1326       // Compute the new bits that are at the top now.
1327       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1328       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1329       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1330         
1331       // Handle the sign bits.
1332       APInt SignBit(APInt::getSignBit(BitWidth));
1333       // Adjust to where it is now in the mask.
1334       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1335         
1336       // If the input sign bit is known to be zero, or if none of the top bits
1337       // are demanded, turn this into an unsigned shift right.
1338       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1339           (HighBits & ~DemandedMask) == HighBits) {
1340         // Perform the logical shift right.
1341         Instruction *NewVal = BinaryOperator::CreateLShr(
1342                           I->getOperand(0), SA, I->getName());
1343         return InsertNewInstBefore(NewVal, *I);
1344       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1345         RHSKnownOne |= HighBits;
1346       }
1347     }
1348     break;
1349   case Instruction::SRem:
1350     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1351       APInt RA = Rem->getValue().abs();
1352       if (RA.isPowerOf2()) {
1353         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1354           return I->getOperand(0);
1355
1356         APInt LowBits = RA - 1;
1357         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1358         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1359                                  LHSKnownZero, LHSKnownOne, Depth+1))
1360           return I;
1361
1362         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1363           LHSKnownZero |= ~LowBits;
1364
1365         KnownZero |= LHSKnownZero & DemandedMask;
1366
1367         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1368       }
1369     }
1370     break;
1371   case Instruction::URem: {
1372     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1373     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1374     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1375                              KnownZero2, KnownOne2, Depth+1) ||
1376         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1377                              KnownZero2, KnownOne2, Depth+1))
1378       return I;
1379
1380     unsigned Leaders = KnownZero2.countLeadingOnes();
1381     Leaders = std::max(Leaders,
1382                        KnownZero2.countLeadingOnes());
1383     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1384     break;
1385   }
1386   case Instruction::Call:
1387     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1388       switch (II->getIntrinsicID()) {
1389       default: break;
1390       case Intrinsic::bswap: {
1391         // If the only bits demanded come from one byte of the bswap result,
1392         // just shift the input byte into position to eliminate the bswap.
1393         unsigned NLZ = DemandedMask.countLeadingZeros();
1394         unsigned NTZ = DemandedMask.countTrailingZeros();
1395           
1396         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1397         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1398         // have 14 leading zeros, round to 8.
1399         NLZ &= ~7;
1400         NTZ &= ~7;
1401         // If we need exactly one byte, we can do this transformation.
1402         if (BitWidth-NLZ-NTZ == 8) {
1403           unsigned ResultBit = NTZ;
1404           unsigned InputBit = BitWidth-NTZ-8;
1405           
1406           // Replace this with either a left or right shift to get the byte into
1407           // the right place.
1408           Instruction *NewVal;
1409           if (InputBit > ResultBit)
1410             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1411                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1412           else
1413             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1414                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1415           NewVal->takeName(I);
1416           return InsertNewInstBefore(NewVal, *I);
1417         }
1418           
1419         // TODO: Could compute known zero/one bits based on the input.
1420         break;
1421       }
1422       }
1423     }
1424     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1425     break;
1426   }
1427   
1428   // If the client is only demanding bits that we know, return the known
1429   // constant.
1430   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1431     return Constant::getIntegerValue(VTy, RHSKnownOne);
1432   return false;
1433 }
1434
1435
1436 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1437 /// any number of elements. DemandedElts contains the set of elements that are
1438 /// actually used by the caller.  This method analyzes which elements of the
1439 /// operand are undef and returns that information in UndefElts.
1440 ///
1441 /// If the information about demanded elements can be used to simplify the
1442 /// operation, the operation is simplified, then the resultant value is
1443 /// returned.  This returns null if no change was made.
1444 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1445                                                 APInt& UndefElts,
1446                                                 unsigned Depth) {
1447   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1448   APInt EltMask(APInt::getAllOnesValue(VWidth));
1449   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1450
1451   if (isa<UndefValue>(V)) {
1452     // If the entire vector is undefined, just return this info.
1453     UndefElts = EltMask;
1454     return 0;
1455   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1456     UndefElts = EltMask;
1457     return UndefValue::get(V->getType());
1458   }
1459
1460   UndefElts = 0;
1461   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1462     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1463     Constant *Undef = UndefValue::get(EltTy);
1464
1465     std::vector<Constant*> Elts;
1466     for (unsigned i = 0; i != VWidth; ++i)
1467       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1468         Elts.push_back(Undef);
1469         UndefElts.set(i);
1470       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1471         Elts.push_back(Undef);
1472         UndefElts.set(i);
1473       } else {                               // Otherwise, defined.
1474         Elts.push_back(CP->getOperand(i));
1475       }
1476
1477     // If we changed the constant, return it.
1478     Constant *NewCP = ConstantVector::get(Elts);
1479     return NewCP != CP ? NewCP : 0;
1480   } else if (isa<ConstantAggregateZero>(V)) {
1481     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1482     // set to undef.
1483     
1484     // Check if this is identity. If so, return 0 since we are not simplifying
1485     // anything.
1486     if (DemandedElts == ((1ULL << VWidth) -1))
1487       return 0;
1488     
1489     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1490     Constant *Zero = Constant::getNullValue(EltTy);
1491     Constant *Undef = UndefValue::get(EltTy);
1492     std::vector<Constant*> Elts;
1493     for (unsigned i = 0; i != VWidth; ++i) {
1494       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1495       Elts.push_back(Elt);
1496     }
1497     UndefElts = DemandedElts ^ EltMask;
1498     return ConstantVector::get(Elts);
1499   }
1500   
1501   // Limit search depth.
1502   if (Depth == 10)
1503     return 0;
1504
1505   // If multiple users are using the root value, procede with
1506   // simplification conservatively assuming that all elements
1507   // are needed.
1508   if (!V->hasOneUse()) {
1509     // Quit if we find multiple users of a non-root value though.
1510     // They'll be handled when it's their turn to be visited by
1511     // the main instcombine process.
1512     if (Depth != 0)
1513       // TODO: Just compute the UndefElts information recursively.
1514       return 0;
1515
1516     // Conservatively assume that all elements are needed.
1517     DemandedElts = EltMask;
1518   }
1519   
1520   Instruction *I = dyn_cast<Instruction>(V);
1521   if (!I) return 0;        // Only analyze instructions.
1522   
1523   bool MadeChange = false;
1524   APInt UndefElts2(VWidth, 0);
1525   Value *TmpV;
1526   switch (I->getOpcode()) {
1527   default: break;
1528     
1529   case Instruction::InsertElement: {
1530     // If this is a variable index, we don't know which element it overwrites.
1531     // demand exactly the same input as we produce.
1532     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1533     if (Idx == 0) {
1534       // Note that we can't propagate undef elt info, because we don't know
1535       // which elt is getting updated.
1536       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1537                                         UndefElts2, Depth+1);
1538       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1539       break;
1540     }
1541     
1542     // If this is inserting an element that isn't demanded, remove this
1543     // insertelement.
1544     unsigned IdxNo = Idx->getZExtValue();
1545     if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1546       Worklist.Add(I);
1547       return I->getOperand(0);
1548     }
1549     
1550     // Otherwise, the element inserted overwrites whatever was there, so the
1551     // input demanded set is simpler than the output set.
1552     APInt DemandedElts2 = DemandedElts;
1553     DemandedElts2.clear(IdxNo);
1554     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1555                                       UndefElts, Depth+1);
1556     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1557
1558     // The inserted element is defined.
1559     UndefElts.clear(IdxNo);
1560     break;
1561   }
1562   case Instruction::ShuffleVector: {
1563     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1564     uint64_t LHSVWidth =
1565       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1566     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1567     for (unsigned i = 0; i < VWidth; i++) {
1568       if (DemandedElts[i]) {
1569         unsigned MaskVal = Shuffle->getMaskValue(i);
1570         if (MaskVal != -1u) {
1571           assert(MaskVal < LHSVWidth * 2 &&
1572                  "shufflevector mask index out of range!");
1573           if (MaskVal < LHSVWidth)
1574             LeftDemanded.set(MaskVal);
1575           else
1576             RightDemanded.set(MaskVal - LHSVWidth);
1577         }
1578       }
1579     }
1580
1581     APInt UndefElts4(LHSVWidth, 0);
1582     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1583                                       UndefElts4, Depth+1);
1584     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1585
1586     APInt UndefElts3(LHSVWidth, 0);
1587     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1588                                       UndefElts3, Depth+1);
1589     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1590
1591     bool NewUndefElts = false;
1592     for (unsigned i = 0; i < VWidth; i++) {
1593       unsigned MaskVal = Shuffle->getMaskValue(i);
1594       if (MaskVal == -1u) {
1595         UndefElts.set(i);
1596       } else if (MaskVal < LHSVWidth) {
1597         if (UndefElts4[MaskVal]) {
1598           NewUndefElts = true;
1599           UndefElts.set(i);
1600         }
1601       } else {
1602         if (UndefElts3[MaskVal - LHSVWidth]) {
1603           NewUndefElts = true;
1604           UndefElts.set(i);
1605         }
1606       }
1607     }
1608
1609     if (NewUndefElts) {
1610       // Add additional discovered undefs.
1611       std::vector<Constant*> Elts;
1612       for (unsigned i = 0; i < VWidth; ++i) {
1613         if (UndefElts[i])
1614           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
1615         else
1616           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
1617                                           Shuffle->getMaskValue(i)));
1618       }
1619       I->setOperand(2, ConstantVector::get(Elts));
1620       MadeChange = true;
1621     }
1622     break;
1623   }
1624   case Instruction::BitCast: {
1625     // Vector->vector casts only.
1626     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1627     if (!VTy) break;
1628     unsigned InVWidth = VTy->getNumElements();
1629     APInt InputDemandedElts(InVWidth, 0);
1630     unsigned Ratio;
1631
1632     if (VWidth == InVWidth) {
1633       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1634       // elements as are demanded of us.
1635       Ratio = 1;
1636       InputDemandedElts = DemandedElts;
1637     } else if (VWidth > InVWidth) {
1638       // Untested so far.
1639       break;
1640       
1641       // If there are more elements in the result than there are in the source,
1642       // then an input element is live if any of the corresponding output
1643       // elements are live.
1644       Ratio = VWidth/InVWidth;
1645       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1646         if (DemandedElts[OutIdx])
1647           InputDemandedElts.set(OutIdx/Ratio);
1648       }
1649     } else {
1650       // Untested so far.
1651       break;
1652       
1653       // If there are more elements in the source than there are in the result,
1654       // then an input element is live if the corresponding output element is
1655       // live.
1656       Ratio = InVWidth/VWidth;
1657       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1658         if (DemandedElts[InIdx/Ratio])
1659           InputDemandedElts.set(InIdx);
1660     }
1661     
1662     // div/rem demand all inputs, because they don't want divide by zero.
1663     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1664                                       UndefElts2, Depth+1);
1665     if (TmpV) {
1666       I->setOperand(0, TmpV);
1667       MadeChange = true;
1668     }
1669     
1670     UndefElts = UndefElts2;
1671     if (VWidth > InVWidth) {
1672       llvm_unreachable("Unimp");
1673       // If there are more elements in the result than there are in the source,
1674       // then an output element is undef if the corresponding input element is
1675       // undef.
1676       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1677         if (UndefElts2[OutIdx/Ratio])
1678           UndefElts.set(OutIdx);
1679     } else if (VWidth < InVWidth) {
1680       llvm_unreachable("Unimp");
1681       // If there are more elements in the source than there are in the result,
1682       // then a result element is undef if all of the corresponding input
1683       // elements are undef.
1684       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1685       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1686         if (!UndefElts2[InIdx])            // Not undef?
1687           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1688     }
1689     break;
1690   }
1691   case Instruction::And:
1692   case Instruction::Or:
1693   case Instruction::Xor:
1694   case Instruction::Add:
1695   case Instruction::Sub:
1696   case Instruction::Mul:
1697     // div/rem demand all inputs, because they don't want divide by zero.
1698     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1699                                       UndefElts, Depth+1);
1700     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1701     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1702                                       UndefElts2, Depth+1);
1703     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1704       
1705     // Output elements are undefined if both are undefined.  Consider things
1706     // like undef&0.  The result is known zero, not undef.
1707     UndefElts &= UndefElts2;
1708     break;
1709     
1710   case Instruction::Call: {
1711     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1712     if (!II) break;
1713     switch (II->getIntrinsicID()) {
1714     default: break;
1715       
1716     // Binary vector operations that work column-wise.  A dest element is a
1717     // function of the corresponding input elements from the two inputs.
1718     case Intrinsic::x86_sse_sub_ss:
1719     case Intrinsic::x86_sse_mul_ss:
1720     case Intrinsic::x86_sse_min_ss:
1721     case Intrinsic::x86_sse_max_ss:
1722     case Intrinsic::x86_sse2_sub_sd:
1723     case Intrinsic::x86_sse2_mul_sd:
1724     case Intrinsic::x86_sse2_min_sd:
1725     case Intrinsic::x86_sse2_max_sd:
1726       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1727                                         UndefElts, Depth+1);
1728       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1729       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1730                                         UndefElts2, Depth+1);
1731       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1732
1733       // If only the low elt is demanded and this is a scalarizable intrinsic,
1734       // scalarize it now.
1735       if (DemandedElts == 1) {
1736         switch (II->getIntrinsicID()) {
1737         default: break;
1738         case Intrinsic::x86_sse_sub_ss:
1739         case Intrinsic::x86_sse_mul_ss:
1740         case Intrinsic::x86_sse2_sub_sd:
1741         case Intrinsic::x86_sse2_mul_sd:
1742           // TODO: Lower MIN/MAX/ABS/etc
1743           Value *LHS = II->getOperand(1);
1744           Value *RHS = II->getOperand(2);
1745           // Extract the element as scalars.
1746           LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS, 
1747             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1748           RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1749             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1750           
1751           switch (II->getIntrinsicID()) {
1752           default: llvm_unreachable("Case stmts out of sync!");
1753           case Intrinsic::x86_sse_sub_ss:
1754           case Intrinsic::x86_sse2_sub_sd:
1755             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1756                                                         II->getName()), *II);
1757             break;
1758           case Intrinsic::x86_sse_mul_ss:
1759           case Intrinsic::x86_sse2_mul_sd:
1760             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1761                                                          II->getName()), *II);
1762             break;
1763           }
1764           
1765           Instruction *New =
1766             InsertElementInst::Create(
1767               UndefValue::get(II->getType()), TmpV,
1768               ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
1769           InsertNewInstBefore(New, *II);
1770           return New;
1771         }            
1772       }
1773         
1774       // Output elements are undefined if both are undefined.  Consider things
1775       // like undef&0.  The result is known zero, not undef.
1776       UndefElts &= UndefElts2;
1777       break;
1778     }
1779     break;
1780   }
1781   }
1782   return MadeChange ? I : 0;
1783 }
1784
1785
1786 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1787 /// function is designed to check a chain of associative operators for a
1788 /// potential to apply a certain optimization.  Since the optimization may be
1789 /// applicable if the expression was reassociated, this checks the chain, then
1790 /// reassociates the expression as necessary to expose the optimization
1791 /// opportunity.  This makes use of a special Functor, which must define
1792 /// 'shouldApply' and 'apply' methods.
1793 ///
1794 template<typename Functor>
1795 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1796   unsigned Opcode = Root.getOpcode();
1797   Value *LHS = Root.getOperand(0);
1798
1799   // Quick check, see if the immediate LHS matches...
1800   if (F.shouldApply(LHS))
1801     return F.apply(Root);
1802
1803   // Otherwise, if the LHS is not of the same opcode as the root, return.
1804   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1805   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1806     // Should we apply this transform to the RHS?
1807     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1808
1809     // If not to the RHS, check to see if we should apply to the LHS...
1810     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1811       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1812       ShouldApply = true;
1813     }
1814
1815     // If the functor wants to apply the optimization to the RHS of LHSI,
1816     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1817     if (ShouldApply) {
1818       // Now all of the instructions are in the current basic block, go ahead
1819       // and perform the reassociation.
1820       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1821
1822       // First move the selected RHS to the LHS of the root...
1823       Root.setOperand(0, LHSI->getOperand(1));
1824
1825       // Make what used to be the LHS of the root be the user of the root...
1826       Value *ExtraOperand = TmpLHSI->getOperand(1);
1827       if (&Root == TmpLHSI) {
1828         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1829         return 0;
1830       }
1831       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1832       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1833       BasicBlock::iterator ARI = &Root; ++ARI;
1834       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1835       ARI = Root;
1836
1837       // Now propagate the ExtraOperand down the chain of instructions until we
1838       // get to LHSI.
1839       while (TmpLHSI != LHSI) {
1840         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1841         // Move the instruction to immediately before the chain we are
1842         // constructing to avoid breaking dominance properties.
1843         NextLHSI->moveBefore(ARI);
1844         ARI = NextLHSI;
1845
1846         Value *NextOp = NextLHSI->getOperand(1);
1847         NextLHSI->setOperand(1, ExtraOperand);
1848         TmpLHSI = NextLHSI;
1849         ExtraOperand = NextOp;
1850       }
1851
1852       // Now that the instructions are reassociated, have the functor perform
1853       // the transformation...
1854       return F.apply(Root);
1855     }
1856
1857     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1858   }
1859   return 0;
1860 }
1861
1862 namespace {
1863
1864 // AddRHS - Implements: X + X --> X << 1
1865 struct AddRHS {
1866   Value *RHS;
1867   explicit AddRHS(Value *rhs) : RHS(rhs) {}
1868   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1869   Instruction *apply(BinaryOperator &Add) const {
1870     return BinaryOperator::CreateShl(Add.getOperand(0),
1871                                      ConstantInt::get(Add.getType(), 1));
1872   }
1873 };
1874
1875 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1876 //                 iff C1&C2 == 0
1877 struct AddMaskingAnd {
1878   Constant *C2;
1879   explicit AddMaskingAnd(Constant *c) : C2(c) {}
1880   bool shouldApply(Value *LHS) const {
1881     ConstantInt *C1;
1882     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1883            ConstantExpr::getAnd(C1, C2)->isNullValue();
1884   }
1885   Instruction *apply(BinaryOperator &Add) const {
1886     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1887   }
1888 };
1889
1890 }
1891
1892 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1893                                              InstCombiner *IC) {
1894   if (CastInst *CI = dyn_cast<CastInst>(&I))
1895     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1896
1897   // Figure out if the constant is the left or the right argument.
1898   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1899   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1900
1901   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1902     if (ConstIsRHS)
1903       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1904     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1905   }
1906
1907   Value *Op0 = SO, *Op1 = ConstOperand;
1908   if (!ConstIsRHS)
1909     std::swap(Op0, Op1);
1910   
1911   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1912     return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1913                                     SO->getName()+".op");
1914   if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1915     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1916                                    SO->getName()+".cmp");
1917   if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1918     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1919                                    SO->getName()+".cmp");
1920   llvm_unreachable("Unknown binary instruction type!");
1921 }
1922
1923 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1924 // constant as the other operand, try to fold the binary operator into the
1925 // select arguments.  This also works for Cast instructions, which obviously do
1926 // not have a second operand.
1927 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1928                                      InstCombiner *IC) {
1929   // Don't modify shared select instructions
1930   if (!SI->hasOneUse()) return 0;
1931   Value *TV = SI->getOperand(1);
1932   Value *FV = SI->getOperand(2);
1933
1934   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1935     // Bool selects with constant operands can be folded to logical ops.
1936     if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
1937
1938     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1939     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1940
1941     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1942                               SelectFalseVal);
1943   }
1944   return 0;
1945 }
1946
1947
1948 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1949 /// node as operand #0, see if we can fold the instruction into the PHI (which
1950 /// is only possible if all operands to the PHI are constants).
1951 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1952   PHINode *PN = cast<PHINode>(I.getOperand(0));
1953   unsigned NumPHIValues = PN->getNumIncomingValues();
1954   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1955
1956   // Check to see if all of the operands of the PHI are constants.  If there is
1957   // one non-constant value, remember the BB it is.  If there is more than one
1958   // or if *it* is a PHI, bail out.
1959   BasicBlock *NonConstBB = 0;
1960   for (unsigned i = 0; i != NumPHIValues; ++i)
1961     if (!isa<Constant>(PN->getIncomingValue(i))) {
1962       if (NonConstBB) return 0;  // More than one non-const value.
1963       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1964       NonConstBB = PN->getIncomingBlock(i);
1965       
1966       // If the incoming non-constant value is in I's block, we have an infinite
1967       // loop.
1968       if (NonConstBB == I.getParent())
1969         return 0;
1970     }
1971   
1972   // If there is exactly one non-constant value, we can insert a copy of the
1973   // operation in that block.  However, if this is a critical edge, we would be
1974   // inserting the computation one some other paths (e.g. inside a loop).  Only
1975   // do this if the pred block is unconditionally branching into the phi block.
1976   if (NonConstBB) {
1977     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1978     if (!BI || !BI->isUnconditional()) return 0;
1979   }
1980
1981   // Okay, we can do the transformation: create the new PHI node.
1982   PHINode *NewPN = PHINode::Create(I.getType(), "");
1983   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1984   InsertNewInstBefore(NewPN, *PN);
1985   NewPN->takeName(PN);
1986
1987   // Next, add all of the operands to the PHI.
1988   if (I.getNumOperands() == 2) {
1989     Constant *C = cast<Constant>(I.getOperand(1));
1990     for (unsigned i = 0; i != NumPHIValues; ++i) {
1991       Value *InV = 0;
1992       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1993         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1994           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1995         else
1996           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1997       } else {
1998         assert(PN->getIncomingBlock(i) == NonConstBB);
1999         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2000           InV = BinaryOperator::Create(BO->getOpcode(),
2001                                        PN->getIncomingValue(i), C, "phitmp",
2002                                        NonConstBB->getTerminator());
2003         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2004           InV = CmpInst::Create(CI->getOpcode(),
2005                                 CI->getPredicate(),
2006                                 PN->getIncomingValue(i), C, "phitmp",
2007                                 NonConstBB->getTerminator());
2008         else
2009           llvm_unreachable("Unknown binop!");
2010         
2011         Worklist.Add(cast<Instruction>(InV));
2012       }
2013       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2014     }
2015   } else { 
2016     CastInst *CI = cast<CastInst>(&I);
2017     const Type *RetTy = CI->getType();
2018     for (unsigned i = 0; i != NumPHIValues; ++i) {
2019       Value *InV;
2020       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2021         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2022       } else {
2023         assert(PN->getIncomingBlock(i) == NonConstBB);
2024         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2025                                I.getType(), "phitmp", 
2026                                NonConstBB->getTerminator());
2027         Worklist.Add(cast<Instruction>(InV));
2028       }
2029       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2030     }
2031   }
2032   return ReplaceInstUsesWith(I, NewPN);
2033 }
2034
2035
2036 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2037 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2038 /// This basically requires proving that the add in the original type would not
2039 /// overflow to change the sign bit or have a carry out.
2040 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2041   // There are different heuristics we can use for this.  Here are some simple
2042   // ones.
2043   
2044   // Add has the property that adding any two 2's complement numbers can only 
2045   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2046   // have at least two sign bits, we know that the addition of the two values will
2047   // sign extend fine.
2048   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2049     return true;
2050   
2051   
2052   // If one of the operands only has one non-zero bit, and if the other operand
2053   // has a known-zero bit in a more significant place than it (not including the
2054   // sign bit) the ripple may go up to and fill the zero, but won't change the
2055   // sign.  For example, (X & ~4) + 1.
2056   
2057   // TODO: Implement.
2058   
2059   return false;
2060 }
2061
2062
2063 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2064   bool Changed = SimplifyCommutative(I);
2065   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2066
2067   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2068     // X + undef -> undef
2069     if (isa<UndefValue>(RHS))
2070       return ReplaceInstUsesWith(I, RHS);
2071
2072     // X + 0 --> X
2073     if (RHSC->isNullValue())
2074       return ReplaceInstUsesWith(I, LHS);
2075
2076     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2077       // X + (signbit) --> X ^ signbit
2078       const APInt& Val = CI->getValue();
2079       uint32_t BitWidth = Val.getBitWidth();
2080       if (Val == APInt::getSignBit(BitWidth))
2081         return BinaryOperator::CreateXor(LHS, RHS);
2082       
2083       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2084       // (X & 254)+1 -> (X&254)|1
2085       if (SimplifyDemandedInstructionBits(I))
2086         return &I;
2087
2088       // zext(bool) + C -> bool ? C + 1 : C
2089       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2090         if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2091           return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2092     }
2093
2094     if (isa<PHINode>(LHS))
2095       if (Instruction *NV = FoldOpIntoPhi(I))
2096         return NV;
2097     
2098     ConstantInt *XorRHS = 0;
2099     Value *XorLHS = 0;
2100     if (isa<ConstantInt>(RHSC) &&
2101         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2102       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2103       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2104       
2105       uint32_t Size = TySizeBits / 2;
2106       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2107       APInt CFF80Val(-C0080Val);
2108       do {
2109         if (TySizeBits > Size) {
2110           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2111           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2112           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2113               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2114             // This is a sign extend if the top bits are known zero.
2115             if (!MaskedValueIsZero(XorLHS, 
2116                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2117               Size = 0;  // Not a sign ext, but can't be any others either.
2118             break;
2119           }
2120         }
2121         Size >>= 1;
2122         C0080Val = APIntOps::lshr(C0080Val, Size);
2123         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2124       } while (Size >= 1);
2125       
2126       // FIXME: This shouldn't be necessary. When the backends can handle types
2127       // with funny bit widths then this switch statement should be removed. It
2128       // is just here to get the size of the "middle" type back up to something
2129       // that the back ends can handle.
2130       const Type *MiddleType = 0;
2131       switch (Size) {
2132         default: break;
2133         case 32: MiddleType = Type::getInt32Ty(*Context); break;
2134         case 16: MiddleType = Type::getInt16Ty(*Context); break;
2135         case  8: MiddleType = Type::getInt8Ty(*Context); break;
2136       }
2137       if (MiddleType) {
2138         Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
2139         return new SExtInst(NewTrunc, I.getType(), I.getName());
2140       }
2141     }
2142   }
2143
2144   if (I.getType() == Type::getInt1Ty(*Context))
2145     return BinaryOperator::CreateXor(LHS, RHS);
2146
2147   // X + X --> X << 1
2148   if (I.getType()->isInteger()) {
2149     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2150       return Result;
2151
2152     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2153       if (RHSI->getOpcode() == Instruction::Sub)
2154         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2155           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2156     }
2157     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2158       if (LHSI->getOpcode() == Instruction::Sub)
2159         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2160           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2161     }
2162   }
2163
2164   // -A + B  -->  B - A
2165   // -A + -B  -->  -(A + B)
2166   if (Value *LHSV = dyn_castNegVal(LHS)) {
2167     if (LHS->getType()->isIntOrIntVector()) {
2168       if (Value *RHSV = dyn_castNegVal(RHS)) {
2169         Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
2170         return BinaryOperator::CreateNeg(NewAdd);
2171       }
2172     }
2173     
2174     return BinaryOperator::CreateSub(RHS, LHSV);
2175   }
2176
2177   // A + -B  -->  A - B
2178   if (!isa<Constant>(RHS))
2179     if (Value *V = dyn_castNegVal(RHS))
2180       return BinaryOperator::CreateSub(LHS, V);
2181
2182
2183   ConstantInt *C2;
2184   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2185     if (X == RHS)   // X*C + X --> X * (C+1)
2186       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2187
2188     // X*C1 + X*C2 --> X * (C1+C2)
2189     ConstantInt *C1;
2190     if (X == dyn_castFoldableMul(RHS, C1))
2191       return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2192   }
2193
2194   // X + X*C --> X * (C+1)
2195   if (dyn_castFoldableMul(RHS, C2) == LHS)
2196     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2197
2198   // X + ~X --> -1   since   ~X = -X-1
2199   if (dyn_castNotVal(LHS) == RHS ||
2200       dyn_castNotVal(RHS) == LHS)
2201     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2202   
2203
2204   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2205   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2206     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2207       return R;
2208   
2209   // A+B --> A|B iff A and B have no bits set in common.
2210   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2211     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2212     APInt LHSKnownOne(IT->getBitWidth(), 0);
2213     APInt LHSKnownZero(IT->getBitWidth(), 0);
2214     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2215     if (LHSKnownZero != 0) {
2216       APInt RHSKnownOne(IT->getBitWidth(), 0);
2217       APInt RHSKnownZero(IT->getBitWidth(), 0);
2218       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2219       
2220       // No bits in common -> bitwise or.
2221       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2222         return BinaryOperator::CreateOr(LHS, RHS);
2223     }
2224   }
2225
2226   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2227   if (I.getType()->isIntOrIntVector()) {
2228     Value *W, *X, *Y, *Z;
2229     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2230         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2231       if (W != Y) {
2232         if (W == Z) {
2233           std::swap(Y, Z);
2234         } else if (Y == X) {
2235           std::swap(W, X);
2236         } else if (X == Z) {
2237           std::swap(Y, Z);
2238           std::swap(W, X);
2239         }
2240       }
2241
2242       if (W == Y) {
2243         Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
2244         return BinaryOperator::CreateMul(W, NewAdd);
2245       }
2246     }
2247   }
2248
2249   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2250     Value *X = 0;
2251     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2252       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2253
2254     // (X & FF00) + xx00  -> (X+xx00) & FF00
2255     if (LHS->hasOneUse() &&
2256         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2257       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2258       if (Anded == CRHS) {
2259         // See if all bits from the first bit set in the Add RHS up are included
2260         // in the mask.  First, get the rightmost bit.
2261         const APInt& AddRHSV = CRHS->getValue();
2262
2263         // Form a mask of all bits from the lowest bit added through the top.
2264         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2265
2266         // See if the and mask includes all of these bits.
2267         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2268
2269         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2270           // Okay, the xform is safe.  Insert the new add pronto.
2271           Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
2272           return BinaryOperator::CreateAnd(NewAdd, C2);
2273         }
2274       }
2275     }
2276
2277     // Try to fold constant add into select arguments.
2278     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2279       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2280         return R;
2281   }
2282
2283   // add (select X 0 (sub n A)) A  -->  select X A n
2284   {
2285     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2286     Value *A = RHS;
2287     if (!SI) {
2288       SI = dyn_cast<SelectInst>(RHS);
2289       A = LHS;
2290     }
2291     if (SI && SI->hasOneUse()) {
2292       Value *TV = SI->getTrueValue();
2293       Value *FV = SI->getFalseValue();
2294       Value *N;
2295
2296       // Can we fold the add into the argument of the select?
2297       // We check both true and false select arguments for a matching subtract.
2298       if (match(FV, m_Zero()) &&
2299           match(TV, m_Sub(m_Value(N), m_Specific(A))))
2300         // Fold the add into the true select value.
2301         return SelectInst::Create(SI->getCondition(), N, A);
2302       if (match(TV, m_Zero()) &&
2303           match(FV, m_Sub(m_Value(N), m_Specific(A))))
2304         // Fold the add into the false select value.
2305         return SelectInst::Create(SI->getCondition(), A, N);
2306     }
2307   }
2308
2309   // Check for (add (sext x), y), see if we can merge this into an
2310   // integer add followed by a sext.
2311   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2312     // (add (sext x), cst) --> (sext (add x, cst'))
2313     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2314       Constant *CI = 
2315         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2316       if (LHSConv->hasOneUse() &&
2317           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2318           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2319         // Insert the new, smaller add.
2320         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0), 
2321                                            CI, "addconv");
2322         return new SExtInst(NewAdd, I.getType());
2323       }
2324     }
2325     
2326     // (add (sext x), (sext y)) --> (sext (add int x, y))
2327     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2328       // Only do this if x/y have the same type, if at last one of them has a
2329       // single use (so we don't increase the number of sexts), and if the
2330       // integer add will not overflow.
2331       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2332           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2333           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2334                                    RHSConv->getOperand(0))) {
2335         // Insert the new integer add.
2336         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0), 
2337                                            RHSConv->getOperand(0), "addconv");
2338         return new SExtInst(NewAdd, I.getType());
2339       }
2340     }
2341   }
2342
2343   return Changed ? &I : 0;
2344 }
2345
2346 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2347   bool Changed = SimplifyCommutative(I);
2348   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2349
2350   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2351     // X + 0 --> X
2352     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2353       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2354                               (I.getType())->getValueAPF()))
2355         return ReplaceInstUsesWith(I, LHS);
2356     }
2357
2358     if (isa<PHINode>(LHS))
2359       if (Instruction *NV = FoldOpIntoPhi(I))
2360         return NV;
2361   }
2362
2363   // -A + B  -->  B - A
2364   // -A + -B  -->  -(A + B)
2365   if (Value *LHSV = dyn_castFNegVal(LHS))
2366     return BinaryOperator::CreateFSub(RHS, LHSV);
2367
2368   // A + -B  -->  A - B
2369   if (!isa<Constant>(RHS))
2370     if (Value *V = dyn_castFNegVal(RHS))
2371       return BinaryOperator::CreateFSub(LHS, V);
2372
2373   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2374   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2375     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2376       return ReplaceInstUsesWith(I, LHS);
2377
2378   // Check for (add double (sitofp x), y), see if we can merge this into an
2379   // integer add followed by a promotion.
2380   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2381     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2382     // ... if the constant fits in the integer value.  This is useful for things
2383     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2384     // requires a constant pool load, and generally allows the add to be better
2385     // instcombined.
2386     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2387       Constant *CI = 
2388       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2389       if (LHSConv->hasOneUse() &&
2390           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2391           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2392         // Insert the new integer add.
2393         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2394                                            CI, "addconv");
2395         return new SIToFPInst(NewAdd, I.getType());
2396       }
2397     }
2398     
2399     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2400     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2401       // Only do this if x/y have the same type, if at last one of them has a
2402       // single use (so we don't increase the number of int->fp conversions),
2403       // and if the integer add will not overflow.
2404       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2405           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2406           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2407                                    RHSConv->getOperand(0))) {
2408         // Insert the new integer add.
2409         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0), 
2410                                            RHSConv->getOperand(0), "addconv");
2411         return new SIToFPInst(NewAdd, I.getType());
2412       }
2413     }
2414   }
2415   
2416   return Changed ? &I : 0;
2417 }
2418
2419 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2420   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2421
2422   if (Op0 == Op1)                        // sub X, X  -> 0
2423     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2424
2425   // If this is a 'B = x-(-A)', change to B = x+A...
2426   if (Value *V = dyn_castNegVal(Op1))
2427     return BinaryOperator::CreateAdd(Op0, V);
2428
2429   if (isa<UndefValue>(Op0))
2430     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2431   if (isa<UndefValue>(Op1))
2432     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2433
2434   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2435     // Replace (-1 - A) with (~A)...
2436     if (C->isAllOnesValue())
2437       return BinaryOperator::CreateNot(Op1);
2438
2439     // C - ~X == X + (1+C)
2440     Value *X = 0;
2441     if (match(Op1, m_Not(m_Value(X))))
2442       return BinaryOperator::CreateAdd(X, AddOne(C));
2443
2444     // -(X >>u 31) -> (X >>s 31)
2445     // -(X >>s 31) -> (X >>u 31)
2446     if (C->isZero()) {
2447       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2448         if (SI->getOpcode() == Instruction::LShr) {
2449           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2450             // Check to see if we are shifting out everything but the sign bit.
2451             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2452                 SI->getType()->getPrimitiveSizeInBits()-1) {
2453               // Ok, the transformation is safe.  Insert AShr.
2454               return BinaryOperator::Create(Instruction::AShr, 
2455                                           SI->getOperand(0), CU, SI->getName());
2456             }
2457           }
2458         }
2459         else if (SI->getOpcode() == Instruction::AShr) {
2460           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2461             // Check to see if we are shifting out everything but the sign bit.
2462             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2463                 SI->getType()->getPrimitiveSizeInBits()-1) {
2464               // Ok, the transformation is safe.  Insert LShr. 
2465               return BinaryOperator::CreateLShr(
2466                                           SI->getOperand(0), CU, SI->getName());
2467             }
2468           }
2469         }
2470       }
2471     }
2472
2473     // Try to fold constant sub into select arguments.
2474     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2475       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2476         return R;
2477
2478     // C - zext(bool) -> bool ? C - 1 : C
2479     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2480       if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2481         return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2482   }
2483
2484   if (I.getType() == Type::getInt1Ty(*Context))
2485     return BinaryOperator::CreateXor(Op0, Op1);
2486
2487   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2488     if (Op1I->getOpcode() == Instruction::Add) {
2489       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2490         return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2491                                          I.getName());
2492       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2493         return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2494                                          I.getName());
2495       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2496         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2497           // C1-(X+C2) --> (C1-C2)-X
2498           return BinaryOperator::CreateSub(
2499             ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2500       }
2501     }
2502
2503     if (Op1I->hasOneUse()) {
2504       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2505       // is not used by anyone else...
2506       //
2507       if (Op1I->getOpcode() == Instruction::Sub) {
2508         // Swap the two operands of the subexpr...
2509         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2510         Op1I->setOperand(0, IIOp1);
2511         Op1I->setOperand(1, IIOp0);
2512
2513         // Create the new top level add instruction...
2514         return BinaryOperator::CreateAdd(Op0, Op1);
2515       }
2516
2517       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2518       //
2519       if (Op1I->getOpcode() == Instruction::And &&
2520           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2521         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2522
2523         Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
2524         return BinaryOperator::CreateAnd(Op0, NewNot);
2525       }
2526
2527       // 0 - (X sdiv C)  -> (X sdiv -C)
2528       if (Op1I->getOpcode() == Instruction::SDiv)
2529         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2530           if (CSI->isZero())
2531             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2532               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2533                                           ConstantExpr::getNeg(DivRHS));
2534
2535       // X - X*C --> X * (1-C)
2536       ConstantInt *C2 = 0;
2537       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2538         Constant *CP1 = 
2539           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2540                                              C2);
2541         return BinaryOperator::CreateMul(Op0, CP1);
2542       }
2543     }
2544   }
2545
2546   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2547     if (Op0I->getOpcode() == Instruction::Add) {
2548       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2549         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2550       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2551         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2552     } else if (Op0I->getOpcode() == Instruction::Sub) {
2553       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2554         return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2555                                          I.getName());
2556     }
2557   }
2558
2559   ConstantInt *C1;
2560   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2561     if (X == Op1)  // X*C - X --> X * (C-1)
2562       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2563
2564     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2565     if (X == dyn_castFoldableMul(Op1, C2))
2566       return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2567   }
2568   return 0;
2569 }
2570
2571 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2572   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2573
2574   // If this is a 'B = x-(-A)', change to B = x+A...
2575   if (Value *V = dyn_castFNegVal(Op1))
2576     return BinaryOperator::CreateFAdd(Op0, V);
2577
2578   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2579     if (Op1I->getOpcode() == Instruction::FAdd) {
2580       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2581         return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
2582                                           I.getName());
2583       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2584         return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
2585                                           I.getName());
2586     }
2587   }
2588
2589   return 0;
2590 }
2591
2592 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2593 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2594 /// TrueIfSigned if the result of the comparison is true when the input value is
2595 /// signed.
2596 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2597                            bool &TrueIfSigned) {
2598   switch (pred) {
2599   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2600     TrueIfSigned = true;
2601     return RHS->isZero();
2602   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2603     TrueIfSigned = true;
2604     return RHS->isAllOnesValue();
2605   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2606     TrueIfSigned = false;
2607     return RHS->isAllOnesValue();
2608   case ICmpInst::ICMP_UGT:
2609     // True if LHS u> RHS and RHS == high-bit-mask - 1
2610     TrueIfSigned = true;
2611     return RHS->getValue() ==
2612       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2613   case ICmpInst::ICMP_UGE: 
2614     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2615     TrueIfSigned = true;
2616     return RHS->getValue().isSignBit();
2617   default:
2618     return false;
2619   }
2620 }
2621
2622 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2623   bool Changed = SimplifyCommutative(I);
2624   Value *Op0 = I.getOperand(0);
2625
2626   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2627     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2628
2629   // Simplify mul instructions with a constant RHS...
2630   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2631     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2632
2633       // ((X << C1)*C2) == (X * (C2 << C1))
2634       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2635         if (SI->getOpcode() == Instruction::Shl)
2636           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2637             return BinaryOperator::CreateMul(SI->getOperand(0),
2638                                         ConstantExpr::getShl(CI, ShOp));
2639
2640       if (CI->isZero())
2641         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2642       if (CI->equalsInt(1))                  // X * 1  == X
2643         return ReplaceInstUsesWith(I, Op0);
2644       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2645         return BinaryOperator::CreateNeg(Op0, I.getName());
2646
2647       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2648       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2649         return BinaryOperator::CreateShl(Op0,
2650                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2651       }
2652     } else if (isa<VectorType>(Op1->getType())) {
2653       if (Op1->isNullValue())
2654         return ReplaceInstUsesWith(I, Op1);
2655
2656       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2657         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2658           return BinaryOperator::CreateNeg(Op0, I.getName());
2659
2660         // As above, vector X*splat(1.0) -> X in all defined cases.
2661         if (Constant *Splat = Op1V->getSplatValue()) {
2662           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2663             if (CI->equalsInt(1))
2664               return ReplaceInstUsesWith(I, Op0);
2665         }
2666       }
2667     }
2668     
2669     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2670       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2671           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2672         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2673         Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1, "tmp");
2674         Value *C1C2 = Builder->CreateMul(Op1, Op0I->getOperand(1));
2675         return BinaryOperator::CreateAdd(Add, C1C2);
2676         
2677       }
2678
2679     // Try to fold constant mul into select arguments.
2680     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2681       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2682         return R;
2683
2684     if (isa<PHINode>(Op0))
2685       if (Instruction *NV = FoldOpIntoPhi(I))
2686         return NV;
2687   }
2688
2689   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2690     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2691       return BinaryOperator::CreateMul(Op0v, Op1v);
2692
2693   // (X / Y) *  Y = X - (X % Y)
2694   // (X / Y) * -Y = (X % Y) - X
2695   {
2696     Value *Op1 = I.getOperand(1);
2697     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2698     if (!BO ||
2699         (BO->getOpcode() != Instruction::UDiv && 
2700          BO->getOpcode() != Instruction::SDiv)) {
2701       Op1 = Op0;
2702       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2703     }
2704     Value *Neg = dyn_castNegVal(Op1);
2705     if (BO && BO->hasOneUse() &&
2706         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2707         (BO->getOpcode() == Instruction::UDiv ||
2708          BO->getOpcode() == Instruction::SDiv)) {
2709       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2710
2711       // If the division is exact, X % Y is zero.
2712       if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2713         if (SDiv->isExact()) {
2714           if (Op1BO == Op1)
2715             return ReplaceInstUsesWith(I, Op0BO);
2716           else
2717             return BinaryOperator::CreateNeg(Op0BO);
2718         }
2719
2720       Value *Rem;
2721       if (BO->getOpcode() == Instruction::UDiv)
2722         Rem = Builder->CreateURem(Op0BO, Op1BO);
2723       else
2724         Rem = Builder->CreateSRem(Op0BO, Op1BO);
2725       Rem->takeName(BO);
2726
2727       if (Op1BO == Op1)
2728         return BinaryOperator::CreateSub(Op0BO, Rem);
2729       return BinaryOperator::CreateSub(Rem, Op0BO);
2730     }
2731   }
2732
2733   if (I.getType() == Type::getInt1Ty(*Context))
2734     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2735
2736   // If one of the operands of the multiply is a cast from a boolean value, then
2737   // we know the bool is either zero or one, so this is a 'masking' multiply.
2738   // See if we can simplify things based on how the boolean was originally
2739   // formed.
2740   CastInst *BoolCast = 0;
2741   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2742     if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2743       BoolCast = CI;
2744   if (!BoolCast)
2745     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2746       if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2747         BoolCast = CI;
2748   if (BoolCast) {
2749     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2750       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2751       const Type *SCOpTy = SCIOp0->getType();
2752       bool TIS = false;
2753       
2754       // If the icmp is true iff the sign bit of X is set, then convert this
2755       // multiply into a shift/and combination.
2756       if (isa<ConstantInt>(SCIOp1) &&
2757           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2758           TIS) {
2759         // Shift the X value right to turn it into "all signbits".
2760         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2761                                           SCOpTy->getPrimitiveSizeInBits()-1);
2762         Value *V = Builder->CreateAShr(SCIOp0, Amt,
2763                                     BoolCast->getOperand(0)->getName()+".mask");
2764
2765         // If the multiply type is not the same as the source type, sign extend
2766         // or truncate to the multiply type.
2767         if (I.getType() != V->getType()) {
2768           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2769           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2770           Instruction::CastOps opcode = 
2771             (SrcBits == DstBits ? Instruction::BitCast : 
2772              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2773           V = InsertCastBefore(opcode, V, I.getType(), I);
2774         }
2775
2776         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2777         return BinaryOperator::CreateAnd(V, OtherOp);
2778       }
2779     }
2780   }
2781
2782   return Changed ? &I : 0;
2783 }
2784
2785 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2786   bool Changed = SimplifyCommutative(I);
2787   Value *Op0 = I.getOperand(0);
2788
2789   // Simplify mul instructions with a constant RHS...
2790   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2791     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2792       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2793       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2794       if (Op1F->isExactlyValue(1.0))
2795         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2796     } else if (isa<VectorType>(Op1->getType())) {
2797       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2798         // As above, vector X*splat(1.0) -> X in all defined cases.
2799         if (Constant *Splat = Op1V->getSplatValue()) {
2800           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2801             if (F->isExactlyValue(1.0))
2802               return ReplaceInstUsesWith(I, Op0);
2803         }
2804       }
2805     }
2806
2807     // Try to fold constant mul into select arguments.
2808     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2809       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2810         return R;
2811
2812     if (isa<PHINode>(Op0))
2813       if (Instruction *NV = FoldOpIntoPhi(I))
2814         return NV;
2815   }
2816
2817   if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
2818     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
2819       return BinaryOperator::CreateFMul(Op0v, Op1v);
2820
2821   return Changed ? &I : 0;
2822 }
2823
2824 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2825 /// instruction.
2826 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2827   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2828   
2829   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2830   int NonNullOperand = -1;
2831   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2832     if (ST->isNullValue())
2833       NonNullOperand = 2;
2834   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2835   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2836     if (ST->isNullValue())
2837       NonNullOperand = 1;
2838   
2839   if (NonNullOperand == -1)
2840     return false;
2841   
2842   Value *SelectCond = SI->getOperand(0);
2843   
2844   // Change the div/rem to use 'Y' instead of the select.
2845   I.setOperand(1, SI->getOperand(NonNullOperand));
2846   
2847   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2848   // problem.  However, the select, or the condition of the select may have
2849   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2850   // propagate the known value for the select into other uses of it, and
2851   // propagate a known value of the condition into its other users.
2852   
2853   // If the select and condition only have a single use, don't bother with this,
2854   // early exit.
2855   if (SI->use_empty() && SelectCond->hasOneUse())
2856     return true;
2857   
2858   // Scan the current block backward, looking for other uses of SI.
2859   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2860   
2861   while (BBI != BBFront) {
2862     --BBI;
2863     // If we found a call to a function, we can't assume it will return, so
2864     // information from below it cannot be propagated above it.
2865     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2866       break;
2867     
2868     // Replace uses of the select or its condition with the known values.
2869     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2870          I != E; ++I) {
2871       if (*I == SI) {
2872         *I = SI->getOperand(NonNullOperand);
2873         Worklist.Add(BBI);
2874       } else if (*I == SelectCond) {
2875         *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2876                                    ConstantInt::getFalse(*Context);
2877         Worklist.Add(BBI);
2878       }
2879     }
2880     
2881     // If we past the instruction, quit looking for it.
2882     if (&*BBI == SI)
2883       SI = 0;
2884     if (&*BBI == SelectCond)
2885       SelectCond = 0;
2886     
2887     // If we ran out of things to eliminate, break out of the loop.
2888     if (SelectCond == 0 && SI == 0)
2889       break;
2890     
2891   }
2892   return true;
2893 }
2894
2895
2896 /// This function implements the transforms on div instructions that work
2897 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2898 /// used by the visitors to those instructions.
2899 /// @brief Transforms common to all three div instructions
2900 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2901   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2902
2903   // undef / X -> 0        for integer.
2904   // undef / X -> undef    for FP (the undef could be a snan).
2905   if (isa<UndefValue>(Op0)) {
2906     if (Op0->getType()->isFPOrFPVector())
2907       return ReplaceInstUsesWith(I, Op0);
2908     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2909   }
2910
2911   // X / undef -> undef
2912   if (isa<UndefValue>(Op1))
2913     return ReplaceInstUsesWith(I, Op1);
2914
2915   return 0;
2916 }
2917
2918 /// This function implements the transforms common to both integer division
2919 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2920 /// division instructions.
2921 /// @brief Common integer divide transforms
2922 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2923   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2924
2925   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2926   if (Op0 == Op1) {
2927     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2928       Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
2929       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2930       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2931     }
2932
2933     Constant *CI = ConstantInt::get(I.getType(), 1);
2934     return ReplaceInstUsesWith(I, CI);
2935   }
2936   
2937   if (Instruction *Common = commonDivTransforms(I))
2938     return Common;
2939   
2940   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2941   // This does not apply for fdiv.
2942   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2943     return &I;
2944
2945   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2946     // div X, 1 == X
2947     if (RHS->equalsInt(1))
2948       return ReplaceInstUsesWith(I, Op0);
2949
2950     // (X / C1) / C2  -> X / (C1*C2)
2951     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2952       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2953         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2954           if (MultiplyOverflows(RHS, LHSRHS,
2955                                 I.getOpcode()==Instruction::SDiv))
2956             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2957           else 
2958             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2959                                       ConstantExpr::getMul(RHS, LHSRHS));
2960         }
2961
2962     if (!RHS->isZero()) { // avoid X udiv 0
2963       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2964         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2965           return R;
2966       if (isa<PHINode>(Op0))
2967         if (Instruction *NV = FoldOpIntoPhi(I))
2968           return NV;
2969     }
2970   }
2971
2972   // 0 / X == 0, we don't need to preserve faults!
2973   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2974     if (LHS->equalsInt(0))
2975       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2976
2977   // It can't be division by zero, hence it must be division by one.
2978   if (I.getType() == Type::getInt1Ty(*Context))
2979     return ReplaceInstUsesWith(I, Op0);
2980
2981   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2982     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2983       // div X, 1 == X
2984       if (X->isOne())
2985         return ReplaceInstUsesWith(I, Op0);
2986   }
2987
2988   return 0;
2989 }
2990
2991 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2992   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2993
2994   // Handle the integer div common cases
2995   if (Instruction *Common = commonIDivTransforms(I))
2996     return Common;
2997
2998   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2999     // X udiv C^2 -> X >> C
3000     // Check to see if this is an unsigned division with an exact power of 2,
3001     // if so, convert to a right shift.
3002     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3003       return BinaryOperator::CreateLShr(Op0, 
3004             ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3005
3006     // X udiv C, where C >= signbit
3007     if (C->getValue().isNegative()) {
3008       Value *IC = Builder->CreateICmpULT( Op0, C);
3009       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3010                                 ConstantInt::get(I.getType(), 1));
3011     }
3012   }
3013
3014   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3015   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3016     if (RHSI->getOpcode() == Instruction::Shl &&
3017         isa<ConstantInt>(RHSI->getOperand(0))) {
3018       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3019       if (C1.isPowerOf2()) {
3020         Value *N = RHSI->getOperand(1);
3021         const Type *NTy = N->getType();
3022         if (uint32_t C2 = C1.logBase2())
3023           N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
3024         return BinaryOperator::CreateLShr(Op0, N);
3025       }
3026     }
3027   }
3028   
3029   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3030   // where C1&C2 are powers of two.
3031   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3032     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3033       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3034         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3035         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3036           // Compute the shift amounts
3037           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3038           // Construct the "on true" case of the select
3039           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3040           Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
3041   
3042           // Construct the "on false" case of the select
3043           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3044           Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
3045
3046           // construct the select instruction and return it.
3047           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3048         }
3049       }
3050   return 0;
3051 }
3052
3053 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3054   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3055
3056   // Handle the integer div common cases
3057   if (Instruction *Common = commonIDivTransforms(I))
3058     return Common;
3059
3060   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3061     // sdiv X, -1 == -X
3062     if (RHS->isAllOnesValue())
3063       return BinaryOperator::CreateNeg(Op0);
3064
3065     // sdiv X, C  -->  ashr X, log2(C)
3066     if (cast<SDivOperator>(&I)->isExact() &&
3067         RHS->getValue().isNonNegative() &&
3068         RHS->getValue().isPowerOf2()) {
3069       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3070                                             RHS->getValue().exactLogBase2());
3071       return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3072     }
3073
3074     // -X/C  -->  X/-C  provided the negation doesn't overflow.
3075     if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3076       if (isa<Constant>(Sub->getOperand(0)) &&
3077           cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3078           Sub->hasNoSignedWrap())
3079         return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3080                                           ConstantExpr::getNeg(RHS));
3081   }
3082
3083   // If the sign bits of both operands are zero (i.e. we can prove they are
3084   // unsigned inputs), turn this into a udiv.
3085   if (I.getType()->isInteger()) {
3086     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3087     if (MaskedValueIsZero(Op0, Mask)) {
3088       if (MaskedValueIsZero(Op1, Mask)) {
3089         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3090         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3091       }
3092       ConstantInt *ShiftedInt;
3093       if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3094           ShiftedInt->getValue().isPowerOf2()) {
3095         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3096         // Safe because the only negative value (1 << Y) can take on is
3097         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3098         // the sign bit set.
3099         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3100       }
3101     }
3102   }
3103   
3104   return 0;
3105 }
3106
3107 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3108   return commonDivTransforms(I);
3109 }
3110
3111 /// This function implements the transforms on rem instructions that work
3112 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3113 /// is used by the visitors to those instructions.
3114 /// @brief Transforms common to all three rem instructions
3115 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3116   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3117
3118   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3119     if (I.getType()->isFPOrFPVector())
3120       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3121     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3122   }
3123   if (isa<UndefValue>(Op1))
3124     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3125
3126   // Handle cases involving: rem X, (select Cond, Y, Z)
3127   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3128     return &I;
3129
3130   return 0;
3131 }
3132
3133 /// This function implements the transforms common to both integer remainder
3134 /// instructions (urem and srem). It is called by the visitors to those integer
3135 /// remainder instructions.
3136 /// @brief Common integer remainder transforms
3137 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3138   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3139
3140   if (Instruction *common = commonRemTransforms(I))
3141     return common;
3142
3143   // 0 % X == 0 for integer, we don't need to preserve faults!
3144   if (Constant *LHS = dyn_cast<Constant>(Op0))
3145     if (LHS->isNullValue())
3146       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3147
3148   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3149     // X % 0 == undef, we don't need to preserve faults!
3150     if (RHS->equalsInt(0))
3151       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3152     
3153     if (RHS->equalsInt(1))  // X % 1 == 0
3154       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3155
3156     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3157       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3158         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3159           return R;
3160       } else if (isa<PHINode>(Op0I)) {
3161         if (Instruction *NV = FoldOpIntoPhi(I))
3162           return NV;
3163       }
3164
3165       // See if we can fold away this rem instruction.
3166       if (SimplifyDemandedInstructionBits(I))
3167         return &I;
3168     }
3169   }
3170
3171   return 0;
3172 }
3173
3174 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3175   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3176
3177   if (Instruction *common = commonIRemTransforms(I))
3178     return common;
3179   
3180   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3181     // X urem C^2 -> X and C
3182     // Check to see if this is an unsigned remainder with an exact power of 2,
3183     // if so, convert to a bitwise and.
3184     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3185       if (C->getValue().isPowerOf2())
3186         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3187   }
3188
3189   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3190     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3191     if (RHSI->getOpcode() == Instruction::Shl &&
3192         isa<ConstantInt>(RHSI->getOperand(0))) {
3193       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3194         Constant *N1 = Constant::getAllOnesValue(I.getType());
3195         Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
3196         return BinaryOperator::CreateAnd(Op0, Add);
3197       }
3198     }
3199   }
3200
3201   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3202   // where C1&C2 are powers of two.
3203   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3204     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3205       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3206         // STO == 0 and SFO == 0 handled above.
3207         if ((STO->getValue().isPowerOf2()) && 
3208             (SFO->getValue().isPowerOf2())) {
3209           Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3210                                               SI->getName()+".t");
3211           Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3212                                                SI->getName()+".f");
3213           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3214         }
3215       }
3216   }
3217   
3218   return 0;
3219 }
3220
3221 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3222   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3223
3224   // Handle the integer rem common cases
3225   if (Instruction *Common = commonIRemTransforms(I))
3226     return Common;
3227   
3228   if (Value *RHSNeg = dyn_castNegVal(Op1))
3229     if (!isa<Constant>(RHSNeg) ||
3230         (isa<ConstantInt>(RHSNeg) &&
3231          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3232       // X % -Y -> X % Y
3233       Worklist.AddValue(I.getOperand(1));
3234       I.setOperand(1, RHSNeg);
3235       return &I;
3236     }
3237
3238   // If the sign bits of both operands are zero (i.e. we can prove they are
3239   // unsigned inputs), turn this into a urem.
3240   if (I.getType()->isInteger()) {
3241     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3242     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3243       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3244       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3245     }
3246   }
3247
3248   // If it's a constant vector, flip any negative values positive.
3249   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3250     unsigned VWidth = RHSV->getNumOperands();
3251
3252     bool hasNegative = false;
3253     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3254       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3255         if (RHS->getValue().isNegative())
3256           hasNegative = true;
3257
3258     if (hasNegative) {
3259       std::vector<Constant *> Elts(VWidth);
3260       for (unsigned i = 0; i != VWidth; ++i) {
3261         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3262           if (RHS->getValue().isNegative())
3263             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3264           else
3265             Elts[i] = RHS;
3266         }
3267       }
3268
3269       Constant *NewRHSV = ConstantVector::get(Elts);
3270       if (NewRHSV != RHSV) {
3271         Worklist.AddValue(I.getOperand(1));
3272         I.setOperand(1, NewRHSV);
3273         return &I;
3274       }
3275     }
3276   }
3277
3278   return 0;
3279 }
3280
3281 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3282   return commonRemTransforms(I);
3283 }
3284
3285 // isOneBitSet - Return true if there is exactly one bit set in the specified
3286 // constant.
3287 static bool isOneBitSet(const ConstantInt *CI) {
3288   return CI->getValue().isPowerOf2();
3289 }
3290
3291 // isHighOnes - Return true if the constant is of the form 1+0+.
3292 // This is the same as lowones(~X).
3293 static bool isHighOnes(const ConstantInt *CI) {
3294   return (~CI->getValue() + 1).isPowerOf2();
3295 }
3296
3297 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3298 /// are carefully arranged to allow folding of expressions such as:
3299 ///
3300 ///      (A < B) | (A > B) --> (A != B)
3301 ///
3302 /// Note that this is only valid if the first and second predicates have the
3303 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3304 ///
3305 /// Three bits are used to represent the condition, as follows:
3306 ///   0  A > B
3307 ///   1  A == B
3308 ///   2  A < B
3309 ///
3310 /// <=>  Value  Definition
3311 /// 000     0   Always false
3312 /// 001     1   A >  B
3313 /// 010     2   A == B
3314 /// 011     3   A >= B
3315 /// 100     4   A <  B
3316 /// 101     5   A != B
3317 /// 110     6   A <= B
3318 /// 111     7   Always true
3319 ///  
3320 static unsigned getICmpCode(const ICmpInst *ICI) {
3321   switch (ICI->getPredicate()) {
3322     // False -> 0
3323   case ICmpInst::ICMP_UGT: return 1;  // 001
3324   case ICmpInst::ICMP_SGT: return 1;  // 001
3325   case ICmpInst::ICMP_EQ:  return 2;  // 010
3326   case ICmpInst::ICMP_UGE: return 3;  // 011
3327   case ICmpInst::ICMP_SGE: return 3;  // 011
3328   case ICmpInst::ICMP_ULT: return 4;  // 100
3329   case ICmpInst::ICMP_SLT: return 4;  // 100
3330   case ICmpInst::ICMP_NE:  return 5;  // 101
3331   case ICmpInst::ICMP_ULE: return 6;  // 110
3332   case ICmpInst::ICMP_SLE: return 6;  // 110
3333     // True -> 7
3334   default:
3335     llvm_unreachable("Invalid ICmp predicate!");
3336     return 0;
3337   }
3338 }
3339
3340 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3341 /// predicate into a three bit mask. It also returns whether it is an ordered
3342 /// predicate by reference.
3343 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3344   isOrdered = false;
3345   switch (CC) {
3346   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3347   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3348   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3349   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3350   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3351   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3352   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3353   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3354   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3355   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3356   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3357   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3358   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3359   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3360     // True -> 7
3361   default:
3362     // Not expecting FCMP_FALSE and FCMP_TRUE;
3363     llvm_unreachable("Unexpected FCmp predicate!");
3364     return 0;
3365   }
3366 }
3367
3368 /// getICmpValue - This is the complement of getICmpCode, which turns an
3369 /// opcode and two operands into either a constant true or false, or a brand 
3370 /// new ICmp instruction. The sign is passed in to determine which kind
3371 /// of predicate to use in the new icmp instruction.
3372 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3373                            LLVMContext *Context) {
3374   switch (code) {
3375   default: llvm_unreachable("Illegal ICmp code!");
3376   case  0: return ConstantInt::getFalse(*Context);
3377   case  1: 
3378     if (sign)
3379       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3380     else
3381       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3382   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3383   case  3: 
3384     if (sign)
3385       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3386     else
3387       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3388   case  4: 
3389     if (sign)
3390       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3391     else
3392       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3393   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3394   case  6: 
3395     if (sign)
3396       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3397     else
3398       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3399   case  7: return ConstantInt::getTrue(*Context);
3400   }
3401 }
3402
3403 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3404 /// opcode and two operands into either a FCmp instruction. isordered is passed
3405 /// in to determine which kind of predicate to use in the new fcmp instruction.
3406 static Value *getFCmpValue(bool isordered, unsigned code,
3407                            Value *LHS, Value *RHS, LLVMContext *Context) {
3408   switch (code) {
3409   default: llvm_unreachable("Illegal FCmp code!");
3410   case  0:
3411     if (isordered)
3412       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3413     else
3414       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3415   case  1: 
3416     if (isordered)
3417       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3418     else
3419       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3420   case  2: 
3421     if (isordered)
3422       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3423     else
3424       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3425   case  3: 
3426     if (isordered)
3427       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3428     else
3429       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3430   case  4: 
3431     if (isordered)
3432       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3433     else
3434       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3435   case  5: 
3436     if (isordered)
3437       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3438     else
3439       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3440   case  6: 
3441     if (isordered)
3442       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3443     else
3444       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3445   case  7: return ConstantInt::getTrue(*Context);
3446   }
3447 }
3448
3449 /// PredicatesFoldable - Return true if both predicates match sign or if at
3450 /// least one of them is an equality comparison (which is signless).
3451 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3452   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3453          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3454          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3455 }
3456
3457 namespace { 
3458 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3459 struct FoldICmpLogical {
3460   InstCombiner &IC;
3461   Value *LHS, *RHS;
3462   ICmpInst::Predicate pred;
3463   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3464     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3465       pred(ICI->getPredicate()) {}
3466   bool shouldApply(Value *V) const {
3467     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3468       if (PredicatesFoldable(pred, ICI->getPredicate()))
3469         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3470                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3471     return false;
3472   }
3473   Instruction *apply(Instruction &Log) const {
3474     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3475     if (ICI->getOperand(0) != LHS) {
3476       assert(ICI->getOperand(1) == LHS);
3477       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3478     }
3479
3480     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3481     unsigned LHSCode = getICmpCode(ICI);
3482     unsigned RHSCode = getICmpCode(RHSICI);
3483     unsigned Code;
3484     switch (Log.getOpcode()) {
3485     case Instruction::And: Code = LHSCode & RHSCode; break;
3486     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3487     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3488     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3489     }
3490
3491     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3492                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3493       
3494     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3495     if (Instruction *I = dyn_cast<Instruction>(RV))
3496       return I;
3497     // Otherwise, it's a constant boolean value...
3498     return IC.ReplaceInstUsesWith(Log, RV);
3499   }
3500 };
3501 } // end anonymous namespace
3502
3503 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3504 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3505 // guaranteed to be a binary operator.
3506 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3507                                     ConstantInt *OpRHS,
3508                                     ConstantInt *AndRHS,
3509                                     BinaryOperator &TheAnd) {
3510   Value *X = Op->getOperand(0);
3511   Constant *Together = 0;
3512   if (!Op->isShift())
3513     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3514
3515   switch (Op->getOpcode()) {
3516   case Instruction::Xor:
3517     if (Op->hasOneUse()) {
3518       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3519       Value *And = Builder->CreateAnd(X, AndRHS);
3520       And->takeName(Op);
3521       return BinaryOperator::CreateXor(And, Together);
3522     }
3523     break;
3524   case Instruction::Or:
3525     if (Together == AndRHS) // (X | C) & C --> C
3526       return ReplaceInstUsesWith(TheAnd, AndRHS);
3527
3528     if (Op->hasOneUse() && Together != OpRHS) {
3529       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3530       Value *Or = Builder->CreateOr(X, Together);
3531       Or->takeName(Op);
3532       return BinaryOperator::CreateAnd(Or, AndRHS);
3533     }
3534     break;
3535   case Instruction::Add:
3536     if (Op->hasOneUse()) {
3537       // Adding a one to a single bit bit-field should be turned into an XOR
3538       // of the bit.  First thing to check is to see if this AND is with a
3539       // single bit constant.
3540       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3541
3542       // If there is only one bit set...
3543       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3544         // Ok, at this point, we know that we are masking the result of the
3545         // ADD down to exactly one bit.  If the constant we are adding has
3546         // no bits set below this bit, then we can eliminate the ADD.
3547         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3548
3549         // Check to see if any bits below the one bit set in AndRHSV are set.
3550         if ((AddRHS & (AndRHSV-1)) == 0) {
3551           // If not, the only thing that can effect the output of the AND is
3552           // the bit specified by AndRHSV.  If that bit is set, the effect of
3553           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3554           // no effect.
3555           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3556             TheAnd.setOperand(0, X);
3557             return &TheAnd;
3558           } else {
3559             // Pull the XOR out of the AND.
3560             Value *NewAnd = Builder->CreateAnd(X, AndRHS);
3561             NewAnd->takeName(Op);
3562             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3563           }
3564         }
3565       }
3566     }
3567     break;
3568
3569   case Instruction::Shl: {
3570     // We know that the AND will not produce any of the bits shifted in, so if
3571     // the anded constant includes them, clear them now!
3572     //
3573     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3574     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3575     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3576     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3577
3578     if (CI->getValue() == ShlMask) { 
3579     // Masking out bits that the shift already masks
3580       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3581     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3582       TheAnd.setOperand(1, CI);
3583       return &TheAnd;
3584     }
3585     break;
3586   }
3587   case Instruction::LShr:
3588   {
3589     // We know that the AND will not produce any of the bits shifted in, so if
3590     // the anded constant includes them, clear them now!  This only applies to
3591     // unsigned shifts, because a signed shr may bring in set bits!
3592     //
3593     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3594     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3595     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3596     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3597
3598     if (CI->getValue() == ShrMask) {   
3599     // Masking out bits that the shift already masks.
3600       return ReplaceInstUsesWith(TheAnd, Op);
3601     } else if (CI != AndRHS) {
3602       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3603       return &TheAnd;
3604     }
3605     break;
3606   }
3607   case Instruction::AShr:
3608     // Signed shr.
3609     // See if this is shifting in some sign extension, then masking it out
3610     // with an and.
3611     if (Op->hasOneUse()) {
3612       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3613       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3614       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3615       Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3616       if (C == AndRHS) {          // Masking out bits shifted in.
3617         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3618         // Make the argument unsigned.
3619         Value *ShVal = Op->getOperand(0);
3620         ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
3621         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3622       }
3623     }
3624     break;
3625   }
3626   return 0;
3627 }
3628
3629
3630 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3631 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3632 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3633 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3634 /// insert new instructions.
3635 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3636                                            bool isSigned, bool Inside, 
3637                                            Instruction &IB) {
3638   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3639             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3640          "Lo is not <= Hi in range emission code!");
3641     
3642   if (Inside) {
3643     if (Lo == Hi)  // Trivially false.
3644       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3645
3646     // V >= Min && V < Hi --> V < Hi
3647     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3648       ICmpInst::Predicate pred = (isSigned ? 
3649         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3650       return new ICmpInst(pred, V, Hi);
3651     }
3652
3653     // Emit V-Lo <u Hi-Lo
3654     Constant *NegLo = ConstantExpr::getNeg(Lo);
3655     Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3656     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3657     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3658   }
3659
3660   if (Lo == Hi)  // Trivially true.
3661     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3662
3663   // V < Min || V >= Hi -> V > Hi-1
3664   Hi = SubOne(cast<ConstantInt>(Hi));
3665   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3666     ICmpInst::Predicate pred = (isSigned ? 
3667         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3668     return new ICmpInst(pred, V, Hi);
3669   }
3670
3671   // Emit V-Lo >u Hi-1-Lo
3672   // Note that Hi has already had one subtracted from it, above.
3673   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3674   Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3675   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3676   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3677 }
3678
3679 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3680 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3681 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3682 // not, since all 1s are not contiguous.
3683 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3684   const APInt& V = Val->getValue();
3685   uint32_t BitWidth = Val->getType()->getBitWidth();
3686   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3687
3688   // look for the first zero bit after the run of ones
3689   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3690   // look for the first non-zero bit
3691   ME = V.getActiveBits(); 
3692   return true;
3693 }
3694
3695 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3696 /// where isSub determines whether the operator is a sub.  If we can fold one of
3697 /// the following xforms:
3698 /// 
3699 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3700 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3701 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3702 ///
3703 /// return (A +/- B).
3704 ///
3705 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3706                                         ConstantInt *Mask, bool isSub,
3707                                         Instruction &I) {
3708   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3709   if (!LHSI || LHSI->getNumOperands() != 2 ||
3710       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3711
3712   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3713
3714   switch (LHSI->getOpcode()) {
3715   default: return 0;
3716   case Instruction::And:
3717     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3718       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3719       if ((Mask->getValue().countLeadingZeros() + 
3720            Mask->getValue().countPopulation()) == 
3721           Mask->getValue().getBitWidth())
3722         break;
3723
3724       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3725       // part, we don't need any explicit masks to take them out of A.  If that
3726       // is all N is, ignore it.
3727       uint32_t MB = 0, ME = 0;
3728       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3729         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3730         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3731         if (MaskedValueIsZero(RHS, Mask))
3732           break;
3733       }
3734     }
3735     return 0;
3736   case Instruction::Or:
3737   case Instruction::Xor:
3738     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3739     if ((Mask->getValue().countLeadingZeros() + 
3740          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3741         && ConstantExpr::getAnd(N, Mask)->isNullValue())
3742       break;
3743     return 0;
3744   }
3745   
3746   if (isSub)
3747     return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3748   return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
3749 }
3750
3751 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3752 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3753                                           ICmpInst *LHS, ICmpInst *RHS) {
3754   Value *Val, *Val2;
3755   ConstantInt *LHSCst, *RHSCst;
3756   ICmpInst::Predicate LHSCC, RHSCC;
3757   
3758   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3759   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3760                          m_ConstantInt(LHSCst))) ||
3761       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3762                          m_ConstantInt(RHSCst))))
3763     return 0;
3764   
3765   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3766   // where C is a power of 2
3767   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3768       LHSCst->getValue().isPowerOf2()) {
3769     Value *NewOr = Builder->CreateOr(Val, Val2);
3770     return new ICmpInst(LHSCC, NewOr, LHSCst);
3771   }
3772   
3773   // From here on, we only handle:
3774   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3775   if (Val != Val2) return 0;
3776   
3777   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3778   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3779       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3780       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3781       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3782     return 0;
3783   
3784   // We can't fold (ugt x, C) & (sgt x, C2).
3785   if (!PredicatesFoldable(LHSCC, RHSCC))
3786     return 0;
3787     
3788   // Ensure that the larger constant is on the RHS.
3789   bool ShouldSwap;
3790   if (ICmpInst::isSignedPredicate(LHSCC) ||
3791       (ICmpInst::isEquality(LHSCC) && 
3792        ICmpInst::isSignedPredicate(RHSCC)))
3793     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3794   else
3795     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3796     
3797   if (ShouldSwap) {
3798     std::swap(LHS, RHS);
3799     std::swap(LHSCst, RHSCst);
3800     std::swap(LHSCC, RHSCC);
3801   }
3802
3803   // At this point, we know we have have two icmp instructions
3804   // comparing a value against two constants and and'ing the result
3805   // together.  Because of the above check, we know that we only have
3806   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3807   // (from the FoldICmpLogical check above), that the two constants 
3808   // are not equal and that the larger constant is on the RHS
3809   assert(LHSCst != RHSCst && "Compares not folded above?");
3810
3811   switch (LHSCC) {
3812   default: llvm_unreachable("Unknown integer condition code!");
3813   case ICmpInst::ICMP_EQ:
3814     switch (RHSCC) {
3815     default: llvm_unreachable("Unknown integer condition code!");
3816     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3817     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3818     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3819       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3820     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3821     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3822     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3823       return ReplaceInstUsesWith(I, LHS);
3824     }
3825   case ICmpInst::ICMP_NE:
3826     switch (RHSCC) {
3827     default: llvm_unreachable("Unknown integer condition code!");
3828     case ICmpInst::ICMP_ULT:
3829       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3830         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3831       break;                        // (X != 13 & X u< 15) -> no change
3832     case ICmpInst::ICMP_SLT:
3833       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3834         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3835       break;                        // (X != 13 & X s< 15) -> no change
3836     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3837     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3838     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3839       return ReplaceInstUsesWith(I, RHS);
3840     case ICmpInst::ICMP_NE:
3841       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3842         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3843         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
3844         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3845                             ConstantInt::get(Add->getType(), 1));
3846       }
3847       break;                        // (X != 13 & X != 15) -> no change
3848     }
3849     break;
3850   case ICmpInst::ICMP_ULT:
3851     switch (RHSCC) {
3852     default: llvm_unreachable("Unknown integer condition code!");
3853     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3854     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3855       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3856     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3857       break;
3858     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3859     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3860       return ReplaceInstUsesWith(I, LHS);
3861     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3862       break;
3863     }
3864     break;
3865   case ICmpInst::ICMP_SLT:
3866     switch (RHSCC) {
3867     default: llvm_unreachable("Unknown integer condition code!");
3868     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3869     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3870       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3871     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3872       break;
3873     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3874     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3875       return ReplaceInstUsesWith(I, LHS);
3876     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3877       break;
3878     }
3879     break;
3880   case ICmpInst::ICMP_UGT:
3881     switch (RHSCC) {
3882     default: llvm_unreachable("Unknown integer condition code!");
3883     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3884     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3885       return ReplaceInstUsesWith(I, RHS);
3886     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3887       break;
3888     case ICmpInst::ICMP_NE:
3889       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3890         return new ICmpInst(LHSCC, Val, RHSCst);
3891       break;                        // (X u> 13 & X != 15) -> no change
3892     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3893       return InsertRangeTest(Val, AddOne(LHSCst),
3894                              RHSCst, false, true, I);
3895     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3896       break;
3897     }
3898     break;
3899   case ICmpInst::ICMP_SGT:
3900     switch (RHSCC) {
3901     default: llvm_unreachable("Unknown integer condition code!");
3902     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3903     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3904       return ReplaceInstUsesWith(I, RHS);
3905     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3906       break;
3907     case ICmpInst::ICMP_NE:
3908       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3909         return new ICmpInst(LHSCC, Val, RHSCst);
3910       break;                        // (X s> 13 & X != 15) -> no change
3911     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3912       return InsertRangeTest(Val, AddOne(LHSCst),
3913                              RHSCst, true, true, I);
3914     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3915       break;
3916     }
3917     break;
3918   }
3919  
3920   return 0;
3921 }
3922
3923 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3924                                           FCmpInst *RHS) {
3925   
3926   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3927       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3928     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3929     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3930       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3931         // If either of the constants are nans, then the whole thing returns
3932         // false.
3933         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3934           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3935         return new FCmpInst(FCmpInst::FCMP_ORD,
3936                             LHS->getOperand(0), RHS->getOperand(0));
3937       }
3938     
3939     // Handle vector zeros.  This occurs because the canonical form of
3940     // "fcmp ord x,x" is "fcmp ord x, 0".
3941     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3942         isa<ConstantAggregateZero>(RHS->getOperand(1)))
3943       return new FCmpInst(FCmpInst::FCMP_ORD,
3944                           LHS->getOperand(0), RHS->getOperand(0));
3945     return 0;
3946   }
3947   
3948   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3949   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3950   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3951   
3952   
3953   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3954     // Swap RHS operands to match LHS.
3955     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3956     std::swap(Op1LHS, Op1RHS);
3957   }
3958   
3959   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3960     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3961     if (Op0CC == Op1CC)
3962       return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
3963     
3964     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
3965       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3966     if (Op0CC == FCmpInst::FCMP_TRUE)
3967       return ReplaceInstUsesWith(I, RHS);
3968     if (Op1CC == FCmpInst::FCMP_TRUE)
3969       return ReplaceInstUsesWith(I, LHS);
3970     
3971     bool Op0Ordered;
3972     bool Op1Ordered;
3973     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3974     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3975     if (Op1Pred == 0) {
3976       std::swap(LHS, RHS);
3977       std::swap(Op0Pred, Op1Pred);
3978       std::swap(Op0Ordered, Op1Ordered);
3979     }
3980     if (Op0Pred == 0) {
3981       // uno && ueq -> uno && (uno || eq) -> ueq
3982       // ord && olt -> ord && (ord && lt) -> olt
3983       if (Op0Ordered == Op1Ordered)
3984         return ReplaceInstUsesWith(I, RHS);
3985       
3986       // uno && oeq -> uno && (ord && eq) -> false
3987       // uno && ord -> false
3988       if (!Op0Ordered)
3989         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3990       // ord && ueq -> ord && (uno || eq) -> oeq
3991       return cast<Instruction>(getFCmpValue(true, Op1Pred,
3992                                             Op0LHS, Op0RHS, Context));
3993     }
3994   }
3995
3996   return 0;
3997 }
3998
3999
4000 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4001   bool Changed = SimplifyCommutative(I);
4002   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4003
4004   if (isa<UndefValue>(Op1))                         // X & undef -> 0
4005     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4006
4007   // and X, X = X
4008   if (Op0 == Op1)
4009     return ReplaceInstUsesWith(I, Op1);
4010
4011   // See if we can simplify any instructions used by the instruction whose sole 
4012   // purpose is to compute bits we don't care about.
4013   if (SimplifyDemandedInstructionBits(I))
4014     return &I;
4015   if (isa<VectorType>(I.getType())) {
4016     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4017       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
4018         return ReplaceInstUsesWith(I, I.getOperand(0));
4019     } else if (isa<ConstantAggregateZero>(Op1)) {
4020       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
4021     }
4022   }
4023
4024   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4025     const APInt& AndRHSMask = AndRHS->getValue();
4026     APInt NotAndRHS(~AndRHSMask);
4027
4028     // Optimize a variety of ((val OP C1) & C2) combinations...
4029     if (isa<BinaryOperator>(Op0)) {
4030       Instruction *Op0I = cast<Instruction>(Op0);
4031       Value *Op0LHS = Op0I->getOperand(0);
4032       Value *Op0RHS = Op0I->getOperand(1);
4033       switch (Op0I->getOpcode()) {
4034       case Instruction::Xor:
4035       case Instruction::Or:
4036         // If the mask is only needed on one incoming arm, push it up.
4037         if (Op0I->hasOneUse()) {
4038           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4039             // Not masking anything out for the LHS, move to RHS.
4040             Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4041                                                Op0RHS->getName()+".masked");
4042             return BinaryOperator::Create(
4043                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4044           }
4045           if (!isa<Constant>(Op0RHS) &&
4046               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4047             // Not masking anything out for the RHS, move to LHS.
4048             Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4049                                                Op0LHS->getName()+".masked");
4050             return BinaryOperator::Create(
4051                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4052           }
4053         }
4054
4055         break;
4056       case Instruction::Add:
4057         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4058         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4059         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4060         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4061           return BinaryOperator::CreateAnd(V, AndRHS);
4062         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4063           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4064         break;
4065
4066       case Instruction::Sub:
4067         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4068         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4069         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4070         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4071           return BinaryOperator::CreateAnd(V, AndRHS);
4072
4073         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4074         // has 1's for all bits that the subtraction with A might affect.
4075         if (Op0I->hasOneUse()) {
4076           uint32_t BitWidth = AndRHSMask.getBitWidth();
4077           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4078           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4079
4080           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4081           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4082               MaskedValueIsZero(Op0LHS, Mask)) {
4083             Value *NewNeg = Builder->CreateNeg(Op0RHS);
4084             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4085           }
4086         }
4087         break;
4088
4089       case Instruction::Shl:
4090       case Instruction::LShr:
4091         // (1 << x) & 1 --> zext(x == 0)
4092         // (1 >> x) & 1 --> zext(x == 0)
4093         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4094           Value *NewICmp =
4095             Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
4096           return new ZExtInst(NewICmp, I.getType());
4097         }
4098         break;
4099       }
4100
4101       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4102         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4103           return Res;
4104     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4105       // If this is an integer truncation or change from signed-to-unsigned, and
4106       // if the source is an and/or with immediate, transform it.  This
4107       // frequently occurs for bitfield accesses.
4108       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4109         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4110             CastOp->getNumOperands() == 2)
4111           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4112             if (CastOp->getOpcode() == Instruction::And) {
4113               // Change: and (cast (and X, C1) to T), C2
4114               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4115               // This will fold the two constants together, which may allow 
4116               // other simplifications.
4117               Value *NewCast = Builder->CreateTruncOrBitCast(
4118                 CastOp->getOperand(0), I.getType(), 
4119                 CastOp->getName()+".shrunk");
4120               // trunc_or_bitcast(C1)&C2
4121               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4122               C3 = ConstantExpr::getAnd(C3, AndRHS);
4123               return BinaryOperator::CreateAnd(NewCast, C3);
4124             } else if (CastOp->getOpcode() == Instruction::Or) {
4125               // Change: and (cast (or X, C1) to T), C2
4126               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4127               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4128               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4129                 // trunc(C1)&C2
4130                 return ReplaceInstUsesWith(I, AndRHS);
4131             }
4132           }
4133       }
4134     }
4135
4136     // Try to fold constant and into select arguments.
4137     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4138       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4139         return R;
4140     if (isa<PHINode>(Op0))
4141       if (Instruction *NV = FoldOpIntoPhi(I))
4142         return NV;
4143   }
4144
4145   Value *Op0NotVal = dyn_castNotVal(Op0);
4146   Value *Op1NotVal = dyn_castNotVal(Op1);
4147
4148   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4149     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4150
4151   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4152   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4153     Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4154                                   I.getName()+".demorgan");
4155     return BinaryOperator::CreateNot(Or);
4156   }
4157   
4158   {
4159     Value *A = 0, *B = 0, *C = 0, *D = 0;
4160     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4161       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4162         return ReplaceInstUsesWith(I, Op1);
4163     
4164       // (A|B) & ~(A&B) -> A^B
4165       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4166         if ((A == C && B == D) || (A == D && B == C))
4167           return BinaryOperator::CreateXor(A, B);
4168       }
4169     }
4170     
4171     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4172       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4173         return ReplaceInstUsesWith(I, Op0);
4174
4175       // ~(A&B) & (A|B) -> A^B
4176       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4177         if ((A == C && B == D) || (A == D && B == C))
4178           return BinaryOperator::CreateXor(A, B);
4179       }
4180     }
4181     
4182     if (Op0->hasOneUse() &&
4183         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4184       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4185         I.swapOperands();     // Simplify below
4186         std::swap(Op0, Op1);
4187       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4188         cast<BinaryOperator>(Op0)->swapOperands();
4189         I.swapOperands();     // Simplify below
4190         std::swap(Op0, Op1);
4191       }
4192     }
4193
4194     if (Op1->hasOneUse() &&
4195         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4196       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4197         cast<BinaryOperator>(Op1)->swapOperands();
4198         std::swap(A, B);
4199       }
4200       if (A == Op0)                                // A&(A^B) -> A & ~B
4201         return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
4202     }
4203
4204     // (A&((~A)|B)) -> A&B
4205     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4206         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4207       return BinaryOperator::CreateAnd(A, Op1);
4208     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4209         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4210       return BinaryOperator::CreateAnd(A, Op0);
4211   }
4212   
4213   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4214     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4215     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4216       return R;
4217
4218     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4219       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4220         return Res;
4221   }
4222
4223   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4224   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4225     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4226       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4227         const Type *SrcTy = Op0C->getOperand(0)->getType();
4228         if (SrcTy == Op1C->getOperand(0)->getType() &&
4229             SrcTy->isIntOrIntVector() &&
4230             // Only do this if the casts both really cause code to be generated.
4231             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4232                               I.getType(), TD) &&
4233             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4234                               I.getType(), TD)) {
4235           Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4236                                             Op1C->getOperand(0), I.getName());
4237           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4238         }
4239       }
4240     
4241   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4242   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4243     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4244       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4245           SI0->getOperand(1) == SI1->getOperand(1) &&
4246           (SI0->hasOneUse() || SI1->hasOneUse())) {
4247         Value *NewOp =
4248           Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4249                              SI0->getName());
4250         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4251                                       SI1->getOperand(1));
4252       }
4253   }
4254
4255   // If and'ing two fcmp, try combine them into one.
4256   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4257     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4258       if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4259         return Res;
4260   }
4261
4262   return Changed ? &I : 0;
4263 }
4264
4265 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4266 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4267 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4268 /// the expression came from the corresponding "byte swapped" byte in some other
4269 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4270 /// we know that the expression deposits the low byte of %X into the high byte
4271 /// of the bswap result and that all other bytes are zero.  This expression is
4272 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4273 /// match.
4274 ///
4275 /// This function returns true if the match was unsuccessful and false if so.
4276 /// On entry to the function the "OverallLeftShift" is a signed integer value
4277 /// indicating the number of bytes that the subexpression is later shifted.  For
4278 /// example, if the expression is later right shifted by 16 bits, the
4279 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4280 /// byte of ByteValues is actually being set.
4281 ///
4282 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4283 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4284 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4285 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4286 /// always in the local (OverallLeftShift) coordinate space.
4287 ///
4288 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4289                               SmallVector<Value*, 8> &ByteValues) {
4290   if (Instruction *I = dyn_cast<Instruction>(V)) {
4291     // If this is an or instruction, it may be an inner node of the bswap.
4292     if (I->getOpcode() == Instruction::Or) {
4293       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4294                                ByteValues) ||
4295              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4296                                ByteValues);
4297     }
4298   
4299     // If this is a logical shift by a constant multiple of 8, recurse with
4300     // OverallLeftShift and ByteMask adjusted.
4301     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4302       unsigned ShAmt = 
4303         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4304       // Ensure the shift amount is defined and of a byte value.
4305       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4306         return true;
4307
4308       unsigned ByteShift = ShAmt >> 3;
4309       if (I->getOpcode() == Instruction::Shl) {
4310         // X << 2 -> collect(X, +2)
4311         OverallLeftShift += ByteShift;
4312         ByteMask >>= ByteShift;
4313       } else {
4314         // X >>u 2 -> collect(X, -2)
4315         OverallLeftShift -= ByteShift;
4316         ByteMask <<= ByteShift;
4317         ByteMask &= (~0U >> (32-ByteValues.size()));
4318       }
4319
4320       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4321       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4322
4323       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4324                                ByteValues);
4325     }
4326
4327     // If this is a logical 'and' with a mask that clears bytes, clear the
4328     // corresponding bytes in ByteMask.
4329     if (I->getOpcode() == Instruction::And &&
4330         isa<ConstantInt>(I->getOperand(1))) {
4331       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4332       unsigned NumBytes = ByteValues.size();
4333       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4334       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4335       
4336       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4337         // If this byte is masked out by a later operation, we don't care what
4338         // the and mask is.
4339         if ((ByteMask & (1 << i)) == 0)
4340           continue;
4341         
4342         // If the AndMask is all zeros for this byte, clear the bit.
4343         APInt MaskB = AndMask & Byte;
4344         if (MaskB == 0) {
4345           ByteMask &= ~(1U << i);
4346           continue;
4347         }
4348         
4349         // If the AndMask is not all ones for this byte, it's not a bytezap.
4350         if (MaskB != Byte)
4351           return true;
4352
4353         // Otherwise, this byte is kept.
4354       }
4355
4356       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4357                                ByteValues);
4358     }
4359   }
4360   
4361   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4362   // the input value to the bswap.  Some observations: 1) if more than one byte
4363   // is demanded from this input, then it could not be successfully assembled
4364   // into a byteswap.  At least one of the two bytes would not be aligned with
4365   // their ultimate destination.
4366   if (!isPowerOf2_32(ByteMask)) return true;
4367   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4368   
4369   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4370   // is demanded, it needs to go into byte 0 of the result.  This means that the
4371   // byte needs to be shifted until it lands in the right byte bucket.  The
4372   // shift amount depends on the position: if the byte is coming from the high
4373   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4374   // low part, it must be shifted left.
4375   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4376   if (InputByteNo < ByteValues.size()/2) {
4377     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4378       return true;
4379   } else {
4380     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4381       return true;
4382   }
4383   
4384   // If the destination byte value is already defined, the values are or'd
4385   // together, which isn't a bswap (unless it's an or of the same bits).
4386   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4387     return true;
4388   ByteValues[DestByteNo] = V;
4389   return false;
4390 }
4391
4392 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4393 /// If so, insert the new bswap intrinsic and return it.
4394 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4395   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4396   if (!ITy || ITy->getBitWidth() % 16 || 
4397       // ByteMask only allows up to 32-byte values.
4398       ITy->getBitWidth() > 32*8) 
4399     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4400   
4401   /// ByteValues - For each byte of the result, we keep track of which value
4402   /// defines each byte.
4403   SmallVector<Value*, 8> ByteValues;
4404   ByteValues.resize(ITy->getBitWidth()/8);
4405     
4406   // Try to find all the pieces corresponding to the bswap.
4407   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4408   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4409     return 0;
4410   
4411   // Check to see if all of the bytes come from the same value.
4412   Value *V = ByteValues[0];
4413   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4414   
4415   // Check to make sure that all of the bytes come from the same value.
4416   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4417     if (ByteValues[i] != V)
4418       return 0;
4419   const Type *Tys[] = { ITy };
4420   Module *M = I.getParent()->getParent()->getParent();
4421   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4422   return CallInst::Create(F, V);
4423 }
4424
4425 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4426 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4427 /// we can simplify this expression to "cond ? C : D or B".
4428 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4429                                          Value *C, Value *D,
4430                                          LLVMContext *Context) {
4431   // If A is not a select of -1/0, this cannot match.
4432   Value *Cond = 0;
4433   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4434     return 0;
4435
4436   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4437   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4438     return SelectInst::Create(Cond, C, B);
4439   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4440     return SelectInst::Create(Cond, C, B);
4441   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4442   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4443     return SelectInst::Create(Cond, C, D);
4444   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4445     return SelectInst::Create(Cond, C, D);
4446   return 0;
4447 }
4448
4449 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4450 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4451                                          ICmpInst *LHS, ICmpInst *RHS) {
4452   Value *Val, *Val2;
4453   ConstantInt *LHSCst, *RHSCst;
4454   ICmpInst::Predicate LHSCC, RHSCC;
4455   
4456   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4457   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4458              m_ConstantInt(LHSCst))) ||
4459       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4460              m_ConstantInt(RHSCst))))
4461     return 0;
4462   
4463   // From here on, we only handle:
4464   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4465   if (Val != Val2) return 0;
4466   
4467   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4468   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4469       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4470       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4471       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4472     return 0;
4473   
4474   // We can't fold (ugt x, C) | (sgt x, C2).
4475   if (!PredicatesFoldable(LHSCC, RHSCC))
4476     return 0;
4477   
4478   // Ensure that the larger constant is on the RHS.
4479   bool ShouldSwap;
4480   if (ICmpInst::isSignedPredicate(LHSCC) ||
4481       (ICmpInst::isEquality(LHSCC) && 
4482        ICmpInst::isSignedPredicate(RHSCC)))
4483     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4484   else
4485     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4486   
4487   if (ShouldSwap) {
4488     std::swap(LHS, RHS);
4489     std::swap(LHSCst, RHSCst);
4490     std::swap(LHSCC, RHSCC);
4491   }
4492   
4493   // At this point, we know we have have two icmp instructions
4494   // comparing a value against two constants and or'ing the result
4495   // together.  Because of the above check, we know that we only have
4496   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4497   // FoldICmpLogical check above), that the two constants are not
4498   // equal.
4499   assert(LHSCst != RHSCst && "Compares not folded above?");
4500
4501   switch (LHSCC) {
4502   default: llvm_unreachable("Unknown integer condition code!");
4503   case ICmpInst::ICMP_EQ:
4504     switch (RHSCC) {
4505     default: llvm_unreachable("Unknown integer condition code!");
4506     case ICmpInst::ICMP_EQ:
4507       if (LHSCst == SubOne(RHSCst)) {
4508         // (X == 13 | X == 14) -> X-13 <u 2
4509         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4510         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4511         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4512         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4513       }
4514       break;                         // (X == 13 | X == 15) -> no change
4515     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4516     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4517       break;
4518     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4519     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4520     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4521       return ReplaceInstUsesWith(I, RHS);
4522     }
4523     break;
4524   case ICmpInst::ICMP_NE:
4525     switch (RHSCC) {
4526     default: llvm_unreachable("Unknown integer condition code!");
4527     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4528     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4529     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4530       return ReplaceInstUsesWith(I, LHS);
4531     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4532     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4533     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4534       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4535     }
4536     break;
4537   case ICmpInst::ICMP_ULT:
4538     switch (RHSCC) {
4539     default: llvm_unreachable("Unknown integer condition code!");
4540     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4541       break;
4542     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4543       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4544       // this can cause overflow.
4545       if (RHSCst->isMaxValue(false))
4546         return ReplaceInstUsesWith(I, LHS);
4547       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4548                              false, false, I);
4549     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4550       break;
4551     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4552     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4553       return ReplaceInstUsesWith(I, RHS);
4554     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4555       break;
4556     }
4557     break;
4558   case ICmpInst::ICMP_SLT:
4559     switch (RHSCC) {
4560     default: llvm_unreachable("Unknown integer condition code!");
4561     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4562       break;
4563     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4564       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4565       // this can cause overflow.
4566       if (RHSCst->isMaxValue(true))
4567         return ReplaceInstUsesWith(I, LHS);
4568       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4569                              true, false, I);
4570     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4571       break;
4572     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4573     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4574       return ReplaceInstUsesWith(I, RHS);
4575     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4576       break;
4577     }
4578     break;
4579   case ICmpInst::ICMP_UGT:
4580     switch (RHSCC) {
4581     default: llvm_unreachable("Unknown integer condition code!");
4582     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4583     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4584       return ReplaceInstUsesWith(I, LHS);
4585     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4586       break;
4587     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4588     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4589       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4590     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4591       break;
4592     }
4593     break;
4594   case ICmpInst::ICMP_SGT:
4595     switch (RHSCC) {
4596     default: llvm_unreachable("Unknown integer condition code!");
4597     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4598     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4599       return ReplaceInstUsesWith(I, LHS);
4600     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4601       break;
4602     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4603     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4604       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4605     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4606       break;
4607     }
4608     break;
4609   }
4610   return 0;
4611 }
4612
4613 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4614                                          FCmpInst *RHS) {
4615   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4616       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4617       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4618     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4619       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4620         // If either of the constants are nans, then the whole thing returns
4621         // true.
4622         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4623           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4624         
4625         // Otherwise, no need to compare the two constants, compare the
4626         // rest.
4627         return new FCmpInst(FCmpInst::FCMP_UNO,
4628                             LHS->getOperand(0), RHS->getOperand(0));
4629       }
4630     
4631     // Handle vector zeros.  This occurs because the canonical form of
4632     // "fcmp uno x,x" is "fcmp uno x, 0".
4633     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4634         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4635       return new FCmpInst(FCmpInst::FCMP_UNO,
4636                           LHS->getOperand(0), RHS->getOperand(0));
4637     
4638     return 0;
4639   }
4640   
4641   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4642   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4643   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4644   
4645   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4646     // Swap RHS operands to match LHS.
4647     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4648     std::swap(Op1LHS, Op1RHS);
4649   }
4650   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4651     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4652     if (Op0CC == Op1CC)
4653       return new FCmpInst((FCmpInst::Predicate)Op0CC,
4654                           Op0LHS, Op0RHS);
4655     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4656       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4657     if (Op0CC == FCmpInst::FCMP_FALSE)
4658       return ReplaceInstUsesWith(I, RHS);
4659     if (Op1CC == FCmpInst::FCMP_FALSE)
4660       return ReplaceInstUsesWith(I, LHS);
4661     bool Op0Ordered;
4662     bool Op1Ordered;
4663     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4664     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4665     if (Op0Ordered == Op1Ordered) {
4666       // If both are ordered or unordered, return a new fcmp with
4667       // or'ed predicates.
4668       Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4669                                Op0LHS, Op0RHS, Context);
4670       if (Instruction *I = dyn_cast<Instruction>(RV))
4671         return I;
4672       // Otherwise, it's a constant boolean value...
4673       return ReplaceInstUsesWith(I, RV);
4674     }
4675   }
4676   return 0;
4677 }
4678
4679 /// FoldOrWithConstants - This helper function folds:
4680 ///
4681 ///     ((A | B) & C1) | (B & C2)
4682 ///
4683 /// into:
4684 /// 
4685 ///     (A & C1) | B
4686 ///
4687 /// when the XOR of the two constants is "all ones" (-1).
4688 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4689                                                Value *A, Value *B, Value *C) {
4690   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4691   if (!CI1) return 0;
4692
4693   Value *V1 = 0;
4694   ConstantInt *CI2 = 0;
4695   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4696
4697   APInt Xor = CI1->getValue() ^ CI2->getValue();
4698   if (!Xor.isAllOnesValue()) return 0;
4699
4700   if (V1 == A || V1 == B) {
4701     Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
4702     return BinaryOperator::CreateOr(NewOp, V1);
4703   }
4704
4705   return 0;
4706 }
4707
4708 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4709   bool Changed = SimplifyCommutative(I);
4710   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4711
4712   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4713     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4714
4715   // or X, X = X
4716   if (Op0 == Op1)
4717     return ReplaceInstUsesWith(I, Op0);
4718
4719   // See if we can simplify any instructions used by the instruction whose sole 
4720   // purpose is to compute bits we don't care about.
4721   if (SimplifyDemandedInstructionBits(I))
4722     return &I;
4723   if (isa<VectorType>(I.getType())) {
4724     if (isa<ConstantAggregateZero>(Op1)) {
4725       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4726     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4727       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4728         return ReplaceInstUsesWith(I, I.getOperand(1));
4729     }
4730   }
4731
4732   // or X, -1 == -1
4733   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4734     ConstantInt *C1 = 0; Value *X = 0;
4735     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4736     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
4737         isOnlyUse(Op0)) {
4738       Value *Or = Builder->CreateOr(X, RHS);
4739       Or->takeName(Op0);
4740       return BinaryOperator::CreateAnd(Or, 
4741                ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
4742     }
4743
4744     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4745     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
4746         isOnlyUse(Op0)) {
4747       Value *Or = Builder->CreateOr(X, RHS);
4748       Or->takeName(Op0);
4749       return BinaryOperator::CreateXor(Or,
4750                  ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
4751     }
4752
4753     // Try to fold constant and into select arguments.
4754     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4755       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4756         return R;
4757     if (isa<PHINode>(Op0))
4758       if (Instruction *NV = FoldOpIntoPhi(I))
4759         return NV;
4760   }
4761
4762   Value *A = 0, *B = 0;
4763   ConstantInt *C1 = 0, *C2 = 0;
4764
4765   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4766     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4767       return ReplaceInstUsesWith(I, Op1);
4768   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4769     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4770       return ReplaceInstUsesWith(I, Op0);
4771
4772   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4773   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4774   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4775       match(Op1, m_Or(m_Value(), m_Value())) ||
4776       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4777        match(Op1, m_Shift(m_Value(), m_Value())))) {
4778     if (Instruction *BSwap = MatchBSwap(I))
4779       return BSwap;
4780   }
4781   
4782   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4783   if (Op0->hasOneUse() &&
4784       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4785       MaskedValueIsZero(Op1, C1->getValue())) {
4786     Value *NOr = Builder->CreateOr(A, Op1);
4787     NOr->takeName(Op0);
4788     return BinaryOperator::CreateXor(NOr, C1);
4789   }
4790
4791   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4792   if (Op1->hasOneUse() &&
4793       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4794       MaskedValueIsZero(Op0, C1->getValue())) {
4795     Value *NOr = Builder->CreateOr(A, Op0);
4796     NOr->takeName(Op0);
4797     return BinaryOperator::CreateXor(NOr, C1);
4798   }
4799
4800   // (A & C)|(B & D)
4801   Value *C = 0, *D = 0;
4802   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4803       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4804     Value *V1 = 0, *V2 = 0, *V3 = 0;
4805     C1 = dyn_cast<ConstantInt>(C);
4806     C2 = dyn_cast<ConstantInt>(D);
4807     if (C1 && C2) {  // (A & C1)|(B & C2)
4808       // If we have: ((V + N) & C1) | (V & C2)
4809       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4810       // replace with V+N.
4811       if (C1->getValue() == ~C2->getValue()) {
4812         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4813             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4814           // Add commutes, try both ways.
4815           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4816             return ReplaceInstUsesWith(I, A);
4817           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4818             return ReplaceInstUsesWith(I, A);
4819         }
4820         // Or commutes, try both ways.
4821         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4822             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4823           // Add commutes, try both ways.
4824           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4825             return ReplaceInstUsesWith(I, B);
4826           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4827             return ReplaceInstUsesWith(I, B);
4828         }
4829       }
4830       V1 = 0; V2 = 0; V3 = 0;
4831     }
4832     
4833     // Check to see if we have any common things being and'ed.  If so, find the
4834     // terms for V1 & (V2|V3).
4835     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4836       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4837         V1 = A, V2 = C, V3 = D;
4838       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4839         V1 = A, V2 = B, V3 = C;
4840       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4841         V1 = C, V2 = A, V3 = D;
4842       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4843         V1 = C, V2 = A, V3 = B;
4844       
4845       if (V1) {
4846         Value *Or = Builder->CreateOr(V2, V3, "tmp");
4847         return BinaryOperator::CreateAnd(V1, Or);
4848       }
4849     }
4850
4851     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4852     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4853       return Match;
4854     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4855       return Match;
4856     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4857       return Match;
4858     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4859       return Match;
4860
4861     // ((A&~B)|(~A&B)) -> A^B
4862     if ((match(C, m_Not(m_Specific(D))) &&
4863          match(B, m_Not(m_Specific(A)))))
4864       return BinaryOperator::CreateXor(A, D);
4865     // ((~B&A)|(~A&B)) -> A^B
4866     if ((match(A, m_Not(m_Specific(D))) &&
4867          match(B, m_Not(m_Specific(C)))))
4868       return BinaryOperator::CreateXor(C, D);
4869     // ((A&~B)|(B&~A)) -> A^B
4870     if ((match(C, m_Not(m_Specific(B))) &&
4871          match(D, m_Not(m_Specific(A)))))
4872       return BinaryOperator::CreateXor(A, B);
4873     // ((~B&A)|(B&~A)) -> A^B
4874     if ((match(A, m_Not(m_Specific(B))) &&
4875          match(D, m_Not(m_Specific(C)))))
4876       return BinaryOperator::CreateXor(C, B);
4877   }
4878   
4879   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4880   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4881     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4882       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4883           SI0->getOperand(1) == SI1->getOperand(1) &&
4884           (SI0->hasOneUse() || SI1->hasOneUse())) {
4885         Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4886                                          SI0->getName());
4887         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4888                                       SI1->getOperand(1));
4889       }
4890   }
4891
4892   // ((A|B)&1)|(B&-2) -> (A&1) | B
4893   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4894       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4895     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4896     if (Ret) return Ret;
4897   }
4898   // (B&-2)|((A|B)&1) -> (A&1) | B
4899   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4900       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4901     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4902     if (Ret) return Ret;
4903   }
4904
4905   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4906     if (A == Op1)   // ~A | A == -1
4907       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4908   } else {
4909     A = 0;
4910   }
4911   // Note, A is still live here!
4912   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4913     if (Op0 == B)
4914       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4915
4916     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4917     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4918       Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
4919       return BinaryOperator::CreateNot(And);
4920     }
4921   }
4922
4923   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4924   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4925     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4926       return R;
4927
4928     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4929       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4930         return Res;
4931   }
4932     
4933   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4934   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4935     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4936       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4937         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4938             !isa<ICmpInst>(Op1C->getOperand(0))) {
4939           const Type *SrcTy = Op0C->getOperand(0)->getType();
4940           if (SrcTy == Op1C->getOperand(0)->getType() &&
4941               SrcTy->isIntOrIntVector() &&
4942               // Only do this if the casts both really cause code to be
4943               // generated.
4944               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4945                                 I.getType(), TD) &&
4946               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4947                                 I.getType(), TD)) {
4948             Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
4949                                              Op1C->getOperand(0), I.getName());
4950             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4951           }
4952         }
4953       }
4954   }
4955   
4956     
4957   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4958   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4959     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4960       if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4961         return Res;
4962   }
4963
4964   return Changed ? &I : 0;
4965 }
4966
4967 namespace {
4968
4969 // XorSelf - Implements: X ^ X --> 0
4970 struct XorSelf {
4971   Value *RHS;
4972   XorSelf(Value *rhs) : RHS(rhs) {}
4973   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4974   Instruction *apply(BinaryOperator &Xor) const {
4975     return &Xor;
4976   }
4977 };
4978
4979 }
4980
4981 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4982   bool Changed = SimplifyCommutative(I);
4983   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4984
4985   if (isa<UndefValue>(Op1)) {
4986     if (isa<UndefValue>(Op0))
4987       // Handle undef ^ undef -> 0 special case. This is a common
4988       // idiom (misuse).
4989       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4990     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4991   }
4992
4993   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4994   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4995     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4996     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4997   }
4998   
4999   // See if we can simplify any instructions used by the instruction whose sole 
5000   // purpose is to compute bits we don't care about.
5001   if (SimplifyDemandedInstructionBits(I))
5002     return &I;
5003   if (isa<VectorType>(I.getType()))
5004     if (isa<ConstantAggregateZero>(Op1))
5005       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5006
5007   // Is this a ~ operation?
5008   if (Value *NotOp = dyn_castNotVal(&I)) {
5009     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5010     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5011     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5012       if (Op0I->getOpcode() == Instruction::And || 
5013           Op0I->getOpcode() == Instruction::Or) {
5014         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5015         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5016           Value *NotY =
5017             Builder->CreateNot(Op0I->getOperand(1),
5018                                Op0I->getOperand(1)->getName()+".not");
5019           if (Op0I->getOpcode() == Instruction::And)
5020             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5021           return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5022         }
5023       }
5024     }
5025   }
5026   
5027   
5028   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5029     if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
5030       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5031       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5032         return new ICmpInst(ICI->getInversePredicate(),
5033                             ICI->getOperand(0), ICI->getOperand(1));
5034
5035       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5036         return new FCmpInst(FCI->getInversePredicate(),
5037                             FCI->getOperand(0), FCI->getOperand(1));
5038     }
5039
5040     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5041     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5042       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5043         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5044           Instruction::CastOps Opcode = Op0C->getOpcode();
5045           if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5046               (RHS == ConstantExpr::getCast(Opcode, 
5047                                             ConstantInt::getTrue(*Context),
5048                                             Op0C->getDestTy()))) {
5049             CI->setPredicate(CI->getInversePredicate());
5050             return CastInst::Create(Opcode, CI, Op0C->getType());
5051           }
5052         }
5053       }
5054     }
5055
5056     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5057       // ~(c-X) == X-c-1 == X+(-c-1)
5058       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5059         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5060           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5061           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5062                                       ConstantInt::get(I.getType(), 1));
5063           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5064         }
5065           
5066       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5067         if (Op0I->getOpcode() == Instruction::Add) {
5068           // ~(X-c) --> (-c-1)-X
5069           if (RHS->isAllOnesValue()) {
5070             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5071             return BinaryOperator::CreateSub(
5072                            ConstantExpr::getSub(NegOp0CI,
5073                                       ConstantInt::get(I.getType(), 1)),
5074                                       Op0I->getOperand(0));
5075           } else if (RHS->getValue().isSignBit()) {
5076             // (X + C) ^ signbit -> (X + C + signbit)
5077             Constant *C = ConstantInt::get(*Context,
5078                                            RHS->getValue() + Op0CI->getValue());
5079             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5080
5081           }
5082         } else if (Op0I->getOpcode() == Instruction::Or) {
5083           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5084           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5085             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5086             // Anything in both C1 and C2 is known to be zero, remove it from
5087             // NewRHS.
5088             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5089             NewRHS = ConstantExpr::getAnd(NewRHS, 
5090                                        ConstantExpr::getNot(CommonBits));
5091             Worklist.Add(Op0I);
5092             I.setOperand(0, Op0I->getOperand(0));
5093             I.setOperand(1, NewRHS);
5094             return &I;
5095           }
5096         }
5097       }
5098     }
5099
5100     // Try to fold constant and into select arguments.
5101     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5102       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5103         return R;
5104     if (isa<PHINode>(Op0))
5105       if (Instruction *NV = FoldOpIntoPhi(I))
5106         return NV;
5107   }
5108
5109   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5110     if (X == Op1)
5111       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5112
5113   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5114     if (X == Op0)
5115       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5116
5117   
5118   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5119   if (Op1I) {
5120     Value *A, *B;
5121     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5122       if (A == Op0) {              // B^(B|A) == (A|B)^B
5123         Op1I->swapOperands();
5124         I.swapOperands();
5125         std::swap(Op0, Op1);
5126       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5127         I.swapOperands();     // Simplified below.
5128         std::swap(Op0, Op1);
5129       }
5130     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5131       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5132     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5133       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5134     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && 
5135                Op1I->hasOneUse()){
5136       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5137         Op1I->swapOperands();
5138         std::swap(A, B);
5139       }
5140       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5141         I.swapOperands();     // Simplified below.
5142         std::swap(Op0, Op1);
5143       }
5144     }
5145   }
5146   
5147   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5148   if (Op0I) {
5149     Value *A, *B;
5150     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5151         Op0I->hasOneUse()) {
5152       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5153         std::swap(A, B);
5154       if (B == Op1)                                  // (A|B)^B == A & ~B
5155         return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
5156     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5157       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5158     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5159       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5160     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && 
5161                Op0I->hasOneUse()){
5162       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5163         std::swap(A, B);
5164       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5165           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5166         return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
5167       }
5168     }
5169   }
5170   
5171   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5172   if (Op0I && Op1I && Op0I->isShift() && 
5173       Op0I->getOpcode() == Op1I->getOpcode() && 
5174       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5175       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5176     Value *NewOp =
5177       Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5178                          Op0I->getName());
5179     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5180                                   Op1I->getOperand(1));
5181   }
5182     
5183   if (Op0I && Op1I) {
5184     Value *A, *B, *C, *D;
5185     // (A & B)^(A | B) -> A ^ B
5186     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5187         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5188       if ((A == C && B == D) || (A == D && B == C)) 
5189         return BinaryOperator::CreateXor(A, B);
5190     }
5191     // (A | B)^(A & B) -> A ^ B
5192     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5193         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5194       if ((A == C && B == D) || (A == D && B == C)) 
5195         return BinaryOperator::CreateXor(A, B);
5196     }
5197     
5198     // (A & B)^(C & D)
5199     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5200         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5201         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5202       // (X & Y)^(X & Y) -> (Y^Z) & X
5203       Value *X = 0, *Y = 0, *Z = 0;
5204       if (A == C)
5205         X = A, Y = B, Z = D;
5206       else if (A == D)
5207         X = A, Y = B, Z = C;
5208       else if (B == C)
5209         X = B, Y = A, Z = D;
5210       else if (B == D)
5211         X = B, Y = A, Z = C;
5212       
5213       if (X) {
5214         Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
5215         return BinaryOperator::CreateAnd(NewOp, X);
5216       }
5217     }
5218   }
5219     
5220   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5221   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5222     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5223       return R;
5224
5225   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5226   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5227     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5228       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5229         const Type *SrcTy = Op0C->getOperand(0)->getType();
5230         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5231             // Only do this if the casts both really cause code to be generated.
5232             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5233                               I.getType(), TD) &&
5234             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5235                               I.getType(), TD)) {
5236           Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5237                                             Op1C->getOperand(0), I.getName());
5238           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5239         }
5240       }
5241   }
5242
5243   return Changed ? &I : 0;
5244 }
5245
5246 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5247                                    LLVMContext *Context) {
5248   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5249 }
5250
5251 static bool HasAddOverflow(ConstantInt *Result,
5252                            ConstantInt *In1, ConstantInt *In2,
5253                            bool IsSigned) {
5254   if (IsSigned)
5255     if (In2->getValue().isNegative())
5256       return Result->getValue().sgt(In1->getValue());
5257     else
5258       return Result->getValue().slt(In1->getValue());
5259   else
5260     return Result->getValue().ult(In1->getValue());
5261 }
5262
5263 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5264 /// overflowed for this type.
5265 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5266                             Constant *In2, LLVMContext *Context,
5267                             bool IsSigned = false) {
5268   Result = ConstantExpr::getAdd(In1, In2);
5269
5270   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5271     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5272       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5273       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5274                          ExtractElement(In1, Idx, Context),
5275                          ExtractElement(In2, Idx, Context),
5276                          IsSigned))
5277         return true;
5278     }
5279     return false;
5280   }
5281
5282   return HasAddOverflow(cast<ConstantInt>(Result),
5283                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5284                         IsSigned);
5285 }
5286
5287 static bool HasSubOverflow(ConstantInt *Result,
5288                            ConstantInt *In1, ConstantInt *In2,
5289                            bool IsSigned) {
5290   if (IsSigned)
5291     if (In2->getValue().isNegative())
5292       return Result->getValue().slt(In1->getValue());
5293     else
5294       return Result->getValue().sgt(In1->getValue());
5295   else
5296     return Result->getValue().ugt(In1->getValue());
5297 }
5298
5299 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5300 /// overflowed for this type.
5301 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5302                             Constant *In2, LLVMContext *Context,
5303                             bool IsSigned = false) {
5304   Result = ConstantExpr::getSub(In1, In2);
5305
5306   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5307     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5308       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5309       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5310                          ExtractElement(In1, Idx, Context),
5311                          ExtractElement(In2, Idx, Context),
5312                          IsSigned))
5313         return true;
5314     }
5315     return false;
5316   }
5317
5318   return HasSubOverflow(cast<ConstantInt>(Result),
5319                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5320                         IsSigned);
5321 }
5322
5323 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5324 /// code necessary to compute the offset from the base pointer (without adding
5325 /// in the base pointer).  Return the result as a signed integer of intptr size.
5326 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5327   TargetData &TD = *IC.getTargetData();
5328   gep_type_iterator GTI = gep_type_begin(GEP);
5329   const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
5330   Value *Result = Constant::getNullValue(IntPtrTy);
5331
5332   // Build a mask for high order bits.
5333   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5334   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5335
5336   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5337        ++i, ++GTI) {
5338     Value *Op = *i;
5339     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5340     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5341       if (OpC->isZero()) continue;
5342       
5343       // Handle a struct index, which adds its field offset to the pointer.
5344       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5345         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5346         
5347         Result = IC.Builder->CreateAdd(Result,
5348                                        ConstantInt::get(IntPtrTy, Size),
5349                                        GEP->getName()+".offs");
5350         continue;
5351       }
5352       
5353       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5354       Constant *OC =
5355               ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5356       Scale = ConstantExpr::getMul(OC, Scale);
5357       // Emit an add instruction.
5358       Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
5359       continue;
5360     }
5361     // Convert to correct type.
5362     if (Op->getType() != IntPtrTy)
5363       Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
5364     if (Size != 1) {
5365       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5366       // We'll let instcombine(mul) convert this to a shl if possible.
5367       Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
5368     }
5369
5370     // Emit an add instruction.
5371     Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
5372   }
5373   return Result;
5374 }
5375
5376
5377 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5378 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
5379 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
5380 /// be complex, and scales are involved.  The above expression would also be
5381 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5382 /// This later form is less amenable to optimization though, and we are allowed
5383 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5384 ///
5385 /// If we can't emit an optimized form for this expression, this returns null.
5386 /// 
5387 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5388                                           InstCombiner &IC) {
5389   TargetData &TD = *IC.getTargetData();
5390   gep_type_iterator GTI = gep_type_begin(GEP);
5391
5392   // Check to see if this gep only has a single variable index.  If so, and if
5393   // any constant indices are a multiple of its scale, then we can compute this
5394   // in terms of the scale of the variable index.  For example, if the GEP
5395   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5396   // because the expression will cross zero at the same point.
5397   unsigned i, e = GEP->getNumOperands();
5398   int64_t Offset = 0;
5399   for (i = 1; i != e; ++i, ++GTI) {
5400     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5401       // Compute the aggregate offset of constant indices.
5402       if (CI->isZero()) continue;
5403
5404       // Handle a struct index, which adds its field offset to the pointer.
5405       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5406         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5407       } else {
5408         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5409         Offset += Size*CI->getSExtValue();
5410       }
5411     } else {
5412       // Found our variable index.
5413       break;
5414     }
5415   }
5416   
5417   // If there are no variable indices, we must have a constant offset, just
5418   // evaluate it the general way.
5419   if (i == e) return 0;
5420   
5421   Value *VariableIdx = GEP->getOperand(i);
5422   // Determine the scale factor of the variable element.  For example, this is
5423   // 4 if the variable index is into an array of i32.
5424   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5425   
5426   // Verify that there are no other variable indices.  If so, emit the hard way.
5427   for (++i, ++GTI; i != e; ++i, ++GTI) {
5428     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5429     if (!CI) return 0;
5430    
5431     // Compute the aggregate offset of constant indices.
5432     if (CI->isZero()) continue;
5433     
5434     // Handle a struct index, which adds its field offset to the pointer.
5435     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5436       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5437     } else {
5438       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5439       Offset += Size*CI->getSExtValue();
5440     }
5441   }
5442   
5443   // Okay, we know we have a single variable index, which must be a
5444   // pointer/array/vector index.  If there is no offset, life is simple, return
5445   // the index.
5446   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5447   if (Offset == 0) {
5448     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5449     // we don't need to bother extending: the extension won't affect where the
5450     // computation crosses zero.
5451     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5452       VariableIdx = new TruncInst(VariableIdx, 
5453                                   TD.getIntPtrType(VariableIdx->getContext()),
5454                                   VariableIdx->getName(), &I);
5455     return VariableIdx;
5456   }
5457   
5458   // Otherwise, there is an index.  The computation we will do will be modulo
5459   // the pointer size, so get it.
5460   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5461   
5462   Offset &= PtrSizeMask;
5463   VariableScale &= PtrSizeMask;
5464
5465   // To do this transformation, any constant index must be a multiple of the
5466   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5467   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5468   // multiple of the variable scale.
5469   int64_t NewOffs = Offset / (int64_t)VariableScale;
5470   if (Offset != NewOffs*(int64_t)VariableScale)
5471     return 0;
5472
5473   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5474   const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
5475   if (VariableIdx->getType() != IntPtrTy)
5476     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5477                                               true /*SExt*/, 
5478                                               VariableIdx->getName(), &I);
5479   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5480   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5481 }
5482
5483
5484 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5485 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5486 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5487                                        ICmpInst::Predicate Cond,
5488                                        Instruction &I) {
5489   // Look through bitcasts.
5490   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5491     RHS = BCI->getOperand(0);
5492
5493   Value *PtrBase = GEPLHS->getOperand(0);
5494   if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5495     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5496     // This transformation (ignoring the base and scales) is valid because we
5497     // know pointers can't overflow since the gep is inbounds.  See if we can
5498     // output an optimized form.
5499     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5500     
5501     // If not, synthesize the offset the hard way.
5502     if (Offset == 0)
5503       Offset = EmitGEPOffset(GEPLHS, I, *this);
5504     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5505                         Constant::getNullValue(Offset->getType()));
5506   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5507     // If the base pointers are different, but the indices are the same, just
5508     // compare the base pointer.
5509     if (PtrBase != GEPRHS->getOperand(0)) {
5510       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5511       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5512                         GEPRHS->getOperand(0)->getType();
5513       if (IndicesTheSame)
5514         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5515           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5516             IndicesTheSame = false;
5517             break;
5518           }
5519
5520       // If all indices are the same, just compare the base pointers.
5521       if (IndicesTheSame)
5522         return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5523                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5524
5525       // Otherwise, the base pointers are different and the indices are
5526       // different, bail out.
5527       return 0;
5528     }
5529
5530     // If one of the GEPs has all zero indices, recurse.
5531     bool AllZeros = true;
5532     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5533       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5534           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5535         AllZeros = false;
5536         break;
5537       }
5538     if (AllZeros)
5539       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5540                           ICmpInst::getSwappedPredicate(Cond), I);
5541
5542     // If the other GEP has all zero indices, recurse.
5543     AllZeros = true;
5544     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5545       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5546           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5547         AllZeros = false;
5548         break;
5549       }
5550     if (AllZeros)
5551       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5552
5553     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5554       // If the GEPs only differ by one index, compare it.
5555       unsigned NumDifferences = 0;  // Keep track of # differences.
5556       unsigned DiffOperand = 0;     // The operand that differs.
5557       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5558         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5559           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5560                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5561             // Irreconcilable differences.
5562             NumDifferences = 2;
5563             break;
5564           } else {
5565             if (NumDifferences++) break;
5566             DiffOperand = i;
5567           }
5568         }
5569
5570       if (NumDifferences == 0)   // SAME GEP?
5571         return ReplaceInstUsesWith(I, // No comparison is needed here.
5572                                    ConstantInt::get(Type::getInt1Ty(*Context),
5573                                              ICmpInst::isTrueWhenEqual(Cond)));
5574
5575       else if (NumDifferences == 1) {
5576         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5577         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5578         // Make sure we do a signed comparison here.
5579         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5580       }
5581     }
5582
5583     // Only lower this if the icmp is the only user of the GEP or if we expect
5584     // the result to fold to a constant!
5585     if (TD &&
5586         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5587         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5588       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5589       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5590       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5591       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5592     }
5593   }
5594   return 0;
5595 }
5596
5597 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5598 ///
5599 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5600                                                 Instruction *LHSI,
5601                                                 Constant *RHSC) {
5602   if (!isa<ConstantFP>(RHSC)) return 0;
5603   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5604   
5605   // Get the width of the mantissa.  We don't want to hack on conversions that
5606   // might lose information from the integer, e.g. "i64 -> float"
5607   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5608   if (MantissaWidth == -1) return 0;  // Unknown.
5609   
5610   // Check to see that the input is converted from an integer type that is small
5611   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5612   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5613   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5614   
5615   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5616   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5617   if (LHSUnsigned)
5618     ++InputSize;
5619   
5620   // If the conversion would lose info, don't hack on this.
5621   if ((int)InputSize > MantissaWidth)
5622     return 0;
5623   
5624   // Otherwise, we can potentially simplify the comparison.  We know that it
5625   // will always come through as an integer value and we know the constant is
5626   // not a NAN (it would have been previously simplified).
5627   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5628   
5629   ICmpInst::Predicate Pred;
5630   switch (I.getPredicate()) {
5631   default: llvm_unreachable("Unexpected predicate!");
5632   case FCmpInst::FCMP_UEQ:
5633   case FCmpInst::FCMP_OEQ:
5634     Pred = ICmpInst::ICMP_EQ;
5635     break;
5636   case FCmpInst::FCMP_UGT:
5637   case FCmpInst::FCMP_OGT:
5638     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5639     break;
5640   case FCmpInst::FCMP_UGE:
5641   case FCmpInst::FCMP_OGE:
5642     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5643     break;
5644   case FCmpInst::FCMP_ULT:
5645   case FCmpInst::FCMP_OLT:
5646     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5647     break;
5648   case FCmpInst::FCMP_ULE:
5649   case FCmpInst::FCMP_OLE:
5650     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5651     break;
5652   case FCmpInst::FCMP_UNE:
5653   case FCmpInst::FCMP_ONE:
5654     Pred = ICmpInst::ICMP_NE;
5655     break;
5656   case FCmpInst::FCMP_ORD:
5657     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5658   case FCmpInst::FCMP_UNO:
5659     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5660   }
5661   
5662   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5663   
5664   // Now we know that the APFloat is a normal number, zero or inf.
5665   
5666   // See if the FP constant is too large for the integer.  For example,
5667   // comparing an i8 to 300.0.
5668   unsigned IntWidth = IntTy->getScalarSizeInBits();
5669   
5670   if (!LHSUnsigned) {
5671     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5672     // and large values.
5673     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5674     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5675                           APFloat::rmNearestTiesToEven);
5676     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5677       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5678           Pred == ICmpInst::ICMP_SLE)
5679         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5680       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5681     }
5682   } else {
5683     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5684     // +INF and large values.
5685     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5686     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5687                           APFloat::rmNearestTiesToEven);
5688     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5689       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5690           Pred == ICmpInst::ICMP_ULE)
5691         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5692       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5693     }
5694   }
5695   
5696   if (!LHSUnsigned) {
5697     // See if the RHS value is < SignedMin.
5698     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5699     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5700                           APFloat::rmNearestTiesToEven);
5701     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5702       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5703           Pred == ICmpInst::ICMP_SGE)
5704         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5705       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5706     }
5707   }
5708
5709   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5710   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5711   // casting the FP value to the integer value and back, checking for equality.
5712   // Don't do this for zero, because -0.0 is not fractional.
5713   Constant *RHSInt = LHSUnsigned
5714     ? ConstantExpr::getFPToUI(RHSC, IntTy)
5715     : ConstantExpr::getFPToSI(RHSC, IntTy);
5716   if (!RHS.isZero()) {
5717     bool Equal = LHSUnsigned
5718       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5719       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5720     if (!Equal) {
5721       // If we had a comparison against a fractional value, we have to adjust
5722       // the compare predicate and sometimes the value.  RHSC is rounded towards
5723       // zero at this point.
5724       switch (Pred) {
5725       default: llvm_unreachable("Unexpected integer comparison!");
5726       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5727         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5728       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5729         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5730       case ICmpInst::ICMP_ULE:
5731         // (float)int <= 4.4   --> int <= 4
5732         // (float)int <= -4.4  --> false
5733         if (RHS.isNegative())
5734           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5735         break;
5736       case ICmpInst::ICMP_SLE:
5737         // (float)int <= 4.4   --> int <= 4
5738         // (float)int <= -4.4  --> int < -4
5739         if (RHS.isNegative())
5740           Pred = ICmpInst::ICMP_SLT;
5741         break;
5742       case ICmpInst::ICMP_ULT:
5743         // (float)int < -4.4   --> false
5744         // (float)int < 4.4    --> int <= 4
5745         if (RHS.isNegative())
5746           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5747         Pred = ICmpInst::ICMP_ULE;
5748         break;
5749       case ICmpInst::ICMP_SLT:
5750         // (float)int < -4.4   --> int < -4
5751         // (float)int < 4.4    --> int <= 4
5752         if (!RHS.isNegative())
5753           Pred = ICmpInst::ICMP_SLE;
5754         break;
5755       case ICmpInst::ICMP_UGT:
5756         // (float)int > 4.4    --> int > 4
5757         // (float)int > -4.4   --> true
5758         if (RHS.isNegative())
5759           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5760         break;
5761       case ICmpInst::ICMP_SGT:
5762         // (float)int > 4.4    --> int > 4
5763         // (float)int > -4.4   --> int >= -4
5764         if (RHS.isNegative())
5765           Pred = ICmpInst::ICMP_SGE;
5766         break;
5767       case ICmpInst::ICMP_UGE:
5768         // (float)int >= -4.4   --> true
5769         // (float)int >= 4.4    --> int > 4
5770         if (!RHS.isNegative())
5771           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5772         Pred = ICmpInst::ICMP_UGT;
5773         break;
5774       case ICmpInst::ICMP_SGE:
5775         // (float)int >= -4.4   --> int >= -4
5776         // (float)int >= 4.4    --> int > 4
5777         if (!RHS.isNegative())
5778           Pred = ICmpInst::ICMP_SGT;
5779         break;
5780       }
5781     }
5782   }
5783
5784   // Lower this FP comparison into an appropriate integer version of the
5785   // comparison.
5786   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5787 }
5788
5789 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5790   bool Changed = SimplifyCompare(I);
5791   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5792
5793   // Fold trivial predicates.
5794   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5795     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5796   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5797     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5798   
5799   // Simplify 'fcmp pred X, X'
5800   if (Op0 == Op1) {
5801     switch (I.getPredicate()) {
5802     default: llvm_unreachable("Unknown predicate!");
5803     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5804     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5805     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5806       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5807     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5808     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5809     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5810       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5811       
5812     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5813     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5814     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5815     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5816       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5817       I.setPredicate(FCmpInst::FCMP_UNO);
5818       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5819       return &I;
5820       
5821     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5822     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5823     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5824     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5825       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5826       I.setPredicate(FCmpInst::FCMP_ORD);
5827       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5828       return &I;
5829     }
5830   }
5831     
5832   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5833     return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
5834
5835   // Handle fcmp with constant RHS
5836   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5837     // If the constant is a nan, see if we can fold the comparison based on it.
5838     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5839       if (CFP->getValueAPF().isNaN()) {
5840         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5841           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5842         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5843                "Comparison must be either ordered or unordered!");
5844         // True if unordered.
5845         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5846       }
5847     }
5848     
5849     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5850       switch (LHSI->getOpcode()) {
5851       case Instruction::PHI:
5852         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5853         // block.  If in the same block, we're encouraging jump threading.  If
5854         // not, we are just pessimizing the code by making an i1 phi.
5855         if (LHSI->getParent() == I.getParent())
5856           if (Instruction *NV = FoldOpIntoPhi(I))
5857             return NV;
5858         break;
5859       case Instruction::SIToFP:
5860       case Instruction::UIToFP:
5861         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5862           return NV;
5863         break;
5864       case Instruction::Select:
5865         // If either operand of the select is a constant, we can fold the
5866         // comparison into the select arms, which will cause one to be
5867         // constant folded and the select turned into a bitwise or.
5868         Value *Op1 = 0, *Op2 = 0;
5869         if (LHSI->hasOneUse()) {
5870           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5871             // Fold the known value into the constant operand.
5872             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5873             // Insert a new FCmp of the other select operand.
5874             Op2 = Builder->CreateFCmp(I.getPredicate(),
5875                                       LHSI->getOperand(2), RHSC, I.getName());
5876           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5877             // Fold the known value into the constant operand.
5878             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5879             // Insert a new FCmp of the other select operand.
5880             Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5881                                       RHSC, I.getName());
5882           }
5883         }
5884
5885         if (Op1)
5886           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5887         break;
5888       }
5889   }
5890
5891   return Changed ? &I : 0;
5892 }
5893
5894 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5895   bool Changed = SimplifyCompare(I);
5896   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5897   const Type *Ty = Op0->getType();
5898
5899   // icmp X, X
5900   if (Op0 == Op1)
5901     return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context), 
5902                                                    I.isTrueWhenEqual()));
5903
5904   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5905     return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
5906   
5907   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5908   // addresses never equal each other!  We already know that Op0 != Op1.
5909   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5910        isa<ConstantPointerNull>(Op0)) &&
5911       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5912        isa<ConstantPointerNull>(Op1)))
5913     return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context), 
5914                                                    !I.isTrueWhenEqual()));
5915
5916   // icmp's with boolean values can always be turned into bitwise operations
5917   if (Ty == Type::getInt1Ty(*Context)) {
5918     switch (I.getPredicate()) {
5919     default: llvm_unreachable("Invalid icmp instruction!");
5920     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5921       Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
5922       return BinaryOperator::CreateNot(Xor);
5923     }
5924     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5925       return BinaryOperator::CreateXor(Op0, Op1);
5926
5927     case ICmpInst::ICMP_UGT:
5928       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5929       // FALL THROUGH
5930     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5931       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
5932       return BinaryOperator::CreateAnd(Not, Op1);
5933     }
5934     case ICmpInst::ICMP_SGT:
5935       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5936       // FALL THROUGH
5937     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5938       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
5939       return BinaryOperator::CreateAnd(Not, Op0);
5940     }
5941     case ICmpInst::ICMP_UGE:
5942       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5943       // FALL THROUGH
5944     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5945       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
5946       return BinaryOperator::CreateOr(Not, Op1);
5947     }
5948     case ICmpInst::ICMP_SGE:
5949       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5950       // FALL THROUGH
5951     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5952       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
5953       return BinaryOperator::CreateOr(Not, Op0);
5954     }
5955     }
5956   }
5957
5958   unsigned BitWidth = 0;
5959   if (TD)
5960     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
5961   else if (Ty->isIntOrIntVector())
5962     BitWidth = Ty->getScalarSizeInBits();
5963
5964   bool isSignBit = false;
5965
5966   // See if we are doing a comparison with a constant.
5967   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5968     Value *A = 0, *B = 0;
5969     
5970     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5971     if (I.isEquality() && CI->isNullValue() &&
5972         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5973       // (icmp cond A B) if cond is equality
5974       return new ICmpInst(I.getPredicate(), A, B);
5975     }
5976     
5977     // If we have an icmp le or icmp ge instruction, turn it into the
5978     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
5979     // them being folded in the code below.
5980     switch (I.getPredicate()) {
5981     default: break;
5982     case ICmpInst::ICMP_ULE:
5983       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5984         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5985       return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
5986                           AddOne(CI));
5987     case ICmpInst::ICMP_SLE:
5988       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5989         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5990       return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5991                           AddOne(CI));
5992     case ICmpInst::ICMP_UGE:
5993       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5994         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5995       return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
5996                           SubOne(CI));
5997     case ICmpInst::ICMP_SGE:
5998       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5999         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6000       return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6001                           SubOne(CI));
6002     }
6003     
6004     // If this comparison is a normal comparison, it demands all
6005     // bits, if it is a sign bit comparison, it only demands the sign bit.
6006     bool UnusedBit;
6007     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6008   }
6009
6010   // See if we can fold the comparison based on range information we can get
6011   // by checking whether bits are known to be zero or one in the input.
6012   if (BitWidth != 0) {
6013     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6014     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6015
6016     if (SimplifyDemandedBits(I.getOperandUse(0),
6017                              isSignBit ? APInt::getSignBit(BitWidth)
6018                                        : APInt::getAllOnesValue(BitWidth),
6019                              Op0KnownZero, Op0KnownOne, 0))
6020       return &I;
6021     if (SimplifyDemandedBits(I.getOperandUse(1),
6022                              APInt::getAllOnesValue(BitWidth),
6023                              Op1KnownZero, Op1KnownOne, 0))
6024       return &I;
6025
6026     // Given the known and unknown bits, compute a range that the LHS could be
6027     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6028     // EQ and NE we use unsigned values.
6029     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6030     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6031     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6032       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6033                                              Op0Min, Op0Max);
6034       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6035                                              Op1Min, Op1Max);
6036     } else {
6037       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6038                                                Op0Min, Op0Max);
6039       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6040                                                Op1Min, Op1Max);
6041     }
6042
6043     // If Min and Max are known to be the same, then SimplifyDemandedBits
6044     // figured out that the LHS is a constant.  Just constant fold this now so
6045     // that code below can assume that Min != Max.
6046     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6047       return new ICmpInst(I.getPredicate(),
6048                           ConstantInt::get(*Context, Op0Min), Op1);
6049     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6050       return new ICmpInst(I.getPredicate(), Op0,
6051                           ConstantInt::get(*Context, Op1Min));
6052
6053     // Based on the range information we know about the LHS, see if we can
6054     // simplify this comparison.  For example, (x&4) < 8  is always true.
6055     switch (I.getPredicate()) {
6056     default: llvm_unreachable("Unknown icmp opcode!");
6057     case ICmpInst::ICMP_EQ:
6058       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6059         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6060       break;
6061     case ICmpInst::ICMP_NE:
6062       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6063         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6064       break;
6065     case ICmpInst::ICMP_ULT:
6066       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6067         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6068       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6069         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6070       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6071         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6072       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6073         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6074           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6075                               SubOne(CI));
6076
6077         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6078         if (CI->isMinValue(true))
6079           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6080                            Constant::getAllOnesValue(Op0->getType()));
6081       }
6082       break;
6083     case ICmpInst::ICMP_UGT:
6084       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6085         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6086       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6087         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6088
6089       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6090         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6091       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6092         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6093           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6094                               AddOne(CI));
6095
6096         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6097         if (CI->isMaxValue(true))
6098           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6099                               Constant::getNullValue(Op0->getType()));
6100       }
6101       break;
6102     case ICmpInst::ICMP_SLT:
6103       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6104         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6105       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6106         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6107       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6108         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6109       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6110         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6111           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6112                               SubOne(CI));
6113       }
6114       break;
6115     case ICmpInst::ICMP_SGT:
6116       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6117         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6118       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6119         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6120
6121       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6122         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6123       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6124         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6125           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6126                               AddOne(CI));
6127       }
6128       break;
6129     case ICmpInst::ICMP_SGE:
6130       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6131       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6132         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6133       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6134         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6135       break;
6136     case ICmpInst::ICMP_SLE:
6137       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6138       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6139         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6140       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6141         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6142       break;
6143     case ICmpInst::ICMP_UGE:
6144       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6145       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6146         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6147       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6148         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6149       break;
6150     case ICmpInst::ICMP_ULE:
6151       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6152       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6153         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6154       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6155         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6156       break;
6157     }
6158
6159     // Turn a signed comparison into an unsigned one if both operands
6160     // are known to have the same sign.
6161     if (I.isSignedPredicate() &&
6162         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6163          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6164       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6165   }
6166
6167   // Test if the ICmpInst instruction is used exclusively by a select as
6168   // part of a minimum or maximum operation. If so, refrain from doing
6169   // any other folding. This helps out other analyses which understand
6170   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6171   // and CodeGen. And in this case, at least one of the comparison
6172   // operands has at least one user besides the compare (the select),
6173   // which would often largely negate the benefit of folding anyway.
6174   if (I.hasOneUse())
6175     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6176       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6177           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6178         return 0;
6179
6180   // See if we are doing a comparison between a constant and an instruction that
6181   // can be folded into the comparison.
6182   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6183     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6184     // instruction, see if that instruction also has constants so that the 
6185     // instruction can be folded into the icmp 
6186     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6187       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6188         return Res;
6189   }
6190
6191   // Handle icmp with constant (but not simple integer constant) RHS
6192   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6193     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6194       switch (LHSI->getOpcode()) {
6195       case Instruction::GetElementPtr:
6196         if (RHSC->isNullValue()) {
6197           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6198           bool isAllZeros = true;
6199           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6200             if (!isa<Constant>(LHSI->getOperand(i)) ||
6201                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6202               isAllZeros = false;
6203               break;
6204             }
6205           if (isAllZeros)
6206             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6207                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6208         }
6209         break;
6210
6211       case Instruction::PHI:
6212         // Only fold icmp into the PHI if the phi and fcmp are in the same
6213         // block.  If in the same block, we're encouraging jump threading.  If
6214         // not, we are just pessimizing the code by making an i1 phi.
6215         if (LHSI->getParent() == I.getParent())
6216           if (Instruction *NV = FoldOpIntoPhi(I))
6217             return NV;
6218         break;
6219       case Instruction::Select: {
6220         // If either operand of the select is a constant, we can fold the
6221         // comparison into the select arms, which will cause one to be
6222         // constant folded and the select turned into a bitwise or.
6223         Value *Op1 = 0, *Op2 = 0;
6224         if (LHSI->hasOneUse()) {
6225           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6226             // Fold the known value into the constant operand.
6227             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6228             // Insert a new ICmp of the other select operand.
6229             Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6230                                       RHSC, I.getName());
6231           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6232             // Fold the known value into the constant operand.
6233             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6234             // Insert a new ICmp of the other select operand.
6235             Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6236                                       RHSC, I.getName());
6237           }
6238         }
6239
6240         if (Op1)
6241           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6242         break;
6243       }
6244       case Instruction::Malloc:
6245         // If we have (malloc != null), and if the malloc has a single use, we
6246         // can assume it is successful and remove the malloc.
6247         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6248           Worklist.Add(LHSI);
6249           return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
6250                                                          !I.isTrueWhenEqual()));
6251         }
6252         break;
6253       }
6254   }
6255
6256   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6257   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6258     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6259       return NI;
6260   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6261     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6262                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6263       return NI;
6264
6265   // Test to see if the operands of the icmp are casted versions of other
6266   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6267   // now.
6268   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6269     if (isa<PointerType>(Op0->getType()) && 
6270         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6271       // We keep moving the cast from the left operand over to the right
6272       // operand, where it can often be eliminated completely.
6273       Op0 = CI->getOperand(0);
6274
6275       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6276       // so eliminate it as well.
6277       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6278         Op1 = CI2->getOperand(0);
6279
6280       // If Op1 is a constant, we can fold the cast into the constant.
6281       if (Op0->getType() != Op1->getType()) {
6282         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6283           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6284         } else {
6285           // Otherwise, cast the RHS right before the icmp
6286           Op1 = Builder->CreateBitCast(Op1, Op0->getType());
6287         }
6288       }
6289       return new ICmpInst(I.getPredicate(), Op0, Op1);
6290     }
6291   }
6292   
6293   if (isa<CastInst>(Op0)) {
6294     // Handle the special case of: icmp (cast bool to X), <cst>
6295     // This comes up when you have code like
6296     //   int X = A < B;
6297     //   if (X) ...
6298     // For generality, we handle any zero-extension of any operand comparison
6299     // with a constant or another cast from the same type.
6300     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6301       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6302         return R;
6303   }
6304   
6305   // See if it's the same type of instruction on the left and right.
6306   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6307     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6308       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6309           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6310         switch (Op0I->getOpcode()) {
6311         default: break;
6312         case Instruction::Add:
6313         case Instruction::Sub:
6314         case Instruction::Xor:
6315           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6316             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6317                                 Op1I->getOperand(0));
6318           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6319           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6320             if (CI->getValue().isSignBit()) {
6321               ICmpInst::Predicate Pred = I.isSignedPredicate()
6322                                              ? I.getUnsignedPredicate()
6323                                              : I.getSignedPredicate();
6324               return new ICmpInst(Pred, Op0I->getOperand(0),
6325                                   Op1I->getOperand(0));
6326             }
6327             
6328             if (CI->getValue().isMaxSignedValue()) {
6329               ICmpInst::Predicate Pred = I.isSignedPredicate()
6330                                              ? I.getUnsignedPredicate()
6331                                              : I.getSignedPredicate();
6332               Pred = I.getSwappedPredicate(Pred);
6333               return new ICmpInst(Pred, Op0I->getOperand(0),
6334                                   Op1I->getOperand(0));
6335             }
6336           }
6337           break;
6338         case Instruction::Mul:
6339           if (!I.isEquality())
6340             break;
6341
6342           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6343             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6344             // Mask = -1 >> count-trailing-zeros(Cst).
6345             if (!CI->isZero() && !CI->isOne()) {
6346               const APInt &AP = CI->getValue();
6347               ConstantInt *Mask = ConstantInt::get(*Context, 
6348                                       APInt::getLowBitsSet(AP.getBitWidth(),
6349                                                            AP.getBitWidth() -
6350                                                       AP.countTrailingZeros()));
6351               Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6352               Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
6353               return new ICmpInst(I.getPredicate(), And1, And2);
6354             }
6355           }
6356           break;
6357         }
6358       }
6359     }
6360   }
6361   
6362   // ~x < ~y --> y < x
6363   { Value *A, *B;
6364     if (match(Op0, m_Not(m_Value(A))) &&
6365         match(Op1, m_Not(m_Value(B))))
6366       return new ICmpInst(I.getPredicate(), B, A);
6367   }
6368   
6369   if (I.isEquality()) {
6370     Value *A, *B, *C, *D;
6371     
6372     // -x == -y --> x == y
6373     if (match(Op0, m_Neg(m_Value(A))) &&
6374         match(Op1, m_Neg(m_Value(B))))
6375       return new ICmpInst(I.getPredicate(), A, B);
6376     
6377     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6378       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6379         Value *OtherVal = A == Op1 ? B : A;
6380         return new ICmpInst(I.getPredicate(), OtherVal,
6381                             Constant::getNullValue(A->getType()));
6382       }
6383
6384       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6385         // A^c1 == C^c2 --> A == C^(c1^c2)
6386         ConstantInt *C1, *C2;
6387         if (match(B, m_ConstantInt(C1)) &&
6388             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6389           Constant *NC = 
6390                    ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6391           Value *Xor = Builder->CreateXor(C, NC, "tmp");
6392           return new ICmpInst(I.getPredicate(), A, Xor);
6393         }
6394         
6395         // A^B == A^D -> B == D
6396         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6397         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6398         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6399         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6400       }
6401     }
6402     
6403     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6404         (A == Op0 || B == Op0)) {
6405       // A == (A^B)  ->  B == 0
6406       Value *OtherVal = A == Op0 ? B : A;
6407       return new ICmpInst(I.getPredicate(), OtherVal,
6408                           Constant::getNullValue(A->getType()));
6409     }
6410
6411     // (A-B) == A  ->  B == 0
6412     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6413       return new ICmpInst(I.getPredicate(), B, 
6414                           Constant::getNullValue(B->getType()));
6415
6416     // A == (A-B)  ->  B == 0
6417     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6418       return new ICmpInst(I.getPredicate(), B,
6419                           Constant::getNullValue(B->getType()));
6420     
6421     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6422     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6423         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6424         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6425       Value *X = 0, *Y = 0, *Z = 0;
6426       
6427       if (A == C) {
6428         X = B; Y = D; Z = A;
6429       } else if (A == D) {
6430         X = B; Y = C; Z = A;
6431       } else if (B == C) {
6432         X = A; Y = D; Z = B;
6433       } else if (B == D) {
6434         X = A; Y = C; Z = B;
6435       }
6436       
6437       if (X) {   // Build (X^Y) & Z
6438         Op1 = Builder->CreateXor(X, Y, "tmp");
6439         Op1 = Builder->CreateAnd(Op1, Z, "tmp");
6440         I.setOperand(0, Op1);
6441         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6442         return &I;
6443       }
6444     }
6445   }
6446   return Changed ? &I : 0;
6447 }
6448
6449
6450 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6451 /// and CmpRHS are both known to be integer constants.
6452 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6453                                           ConstantInt *DivRHS) {
6454   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6455   const APInt &CmpRHSV = CmpRHS->getValue();
6456   
6457   // FIXME: If the operand types don't match the type of the divide 
6458   // then don't attempt this transform. The code below doesn't have the
6459   // logic to deal with a signed divide and an unsigned compare (and
6460   // vice versa). This is because (x /s C1) <s C2  produces different 
6461   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6462   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6463   // work. :(  The if statement below tests that condition and bails 
6464   // if it finds it. 
6465   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6466   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6467     return 0;
6468   if (DivRHS->isZero())
6469     return 0; // The ProdOV computation fails on divide by zero.
6470   if (DivIsSigned && DivRHS->isAllOnesValue())
6471     return 0; // The overflow computation also screws up here
6472   if (DivRHS->isOne())
6473     return 0; // Not worth bothering, and eliminates some funny cases
6474               // with INT_MIN.
6475
6476   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6477   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6478   // C2 (CI). By solving for X we can turn this into a range check 
6479   // instead of computing a divide. 
6480   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6481
6482   // Determine if the product overflows by seeing if the product is
6483   // not equal to the divide. Make sure we do the same kind of divide
6484   // as in the LHS instruction that we're folding. 
6485   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6486                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6487
6488   // Get the ICmp opcode
6489   ICmpInst::Predicate Pred = ICI.getPredicate();
6490
6491   // Figure out the interval that is being checked.  For example, a comparison
6492   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6493   // Compute this interval based on the constants involved and the signedness of
6494   // the compare/divide.  This computes a half-open interval, keeping track of
6495   // whether either value in the interval overflows.  After analysis each
6496   // overflow variable is set to 0 if it's corresponding bound variable is valid
6497   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6498   int LoOverflow = 0, HiOverflow = 0;
6499   Constant *LoBound = 0, *HiBound = 0;
6500   
6501   if (!DivIsSigned) {  // udiv
6502     // e.g. X/5 op 3  --> [15, 20)
6503     LoBound = Prod;
6504     HiOverflow = LoOverflow = ProdOV;
6505     if (!HiOverflow)
6506       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6507   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6508     if (CmpRHSV == 0) {       // (X / pos) op 0
6509       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6510       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6511       HiBound = DivRHS;
6512     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6513       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6514       HiOverflow = LoOverflow = ProdOV;
6515       if (!HiOverflow)
6516         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6517     } else {                       // (X / pos) op neg
6518       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6519       HiBound = AddOne(Prod);
6520       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6521       if (!LoOverflow) {
6522         ConstantInt* DivNeg =
6523                          cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6524         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6525                                      true) ? -1 : 0;
6526        }
6527     }
6528   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6529     if (CmpRHSV == 0) {       // (X / neg) op 0
6530       // e.g. X/-5 op 0  --> [-4, 5)
6531       LoBound = AddOne(DivRHS);
6532       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6533       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6534         HiOverflow = 1;            // [INTMIN+1, overflow)
6535         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6536       }
6537     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6538       // e.g. X/-5 op 3  --> [-19, -14)
6539       HiBound = AddOne(Prod);
6540       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6541       if (!LoOverflow)
6542         LoOverflow = AddWithOverflow(LoBound, HiBound,
6543                                      DivRHS, Context, true) ? -1 : 0;
6544     } else {                       // (X / neg) op neg
6545       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6546       LoOverflow = HiOverflow = ProdOV;
6547       if (!HiOverflow)
6548         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6549     }
6550     
6551     // Dividing by a negative swaps the condition.  LT <-> GT
6552     Pred = ICmpInst::getSwappedPredicate(Pred);
6553   }
6554
6555   Value *X = DivI->getOperand(0);
6556   switch (Pred) {
6557   default: llvm_unreachable("Unhandled icmp opcode!");
6558   case ICmpInst::ICMP_EQ:
6559     if (LoOverflow && HiOverflow)
6560       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6561     else if (HiOverflow)
6562       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6563                           ICmpInst::ICMP_UGE, X, LoBound);
6564     else if (LoOverflow)
6565       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6566                           ICmpInst::ICMP_ULT, X, HiBound);
6567     else
6568       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6569   case ICmpInst::ICMP_NE:
6570     if (LoOverflow && HiOverflow)
6571       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6572     else if (HiOverflow)
6573       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6574                           ICmpInst::ICMP_ULT, X, LoBound);
6575     else if (LoOverflow)
6576       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6577                           ICmpInst::ICMP_UGE, X, HiBound);
6578     else
6579       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6580   case ICmpInst::ICMP_ULT:
6581   case ICmpInst::ICMP_SLT:
6582     if (LoOverflow == +1)   // Low bound is greater than input range.
6583       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6584     if (LoOverflow == -1)   // Low bound is less than input range.
6585       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6586     return new ICmpInst(Pred, X, LoBound);
6587   case ICmpInst::ICMP_UGT:
6588   case ICmpInst::ICMP_SGT:
6589     if (HiOverflow == +1)       // High bound greater than input range.
6590       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6591     else if (HiOverflow == -1)  // High bound less than input range.
6592       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6593     if (Pred == ICmpInst::ICMP_UGT)
6594       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6595     else
6596       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6597   }
6598 }
6599
6600
6601 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6602 ///
6603 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6604                                                           Instruction *LHSI,
6605                                                           ConstantInt *RHS) {
6606   const APInt &RHSV = RHS->getValue();
6607   
6608   switch (LHSI->getOpcode()) {
6609   case Instruction::Trunc:
6610     if (ICI.isEquality() && LHSI->hasOneUse()) {
6611       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6612       // of the high bits truncated out of x are known.
6613       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6614              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6615       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6616       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6617       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6618       
6619       // If all the high bits are known, we can do this xform.
6620       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6621         // Pull in the high bits from known-ones set.
6622         APInt NewRHS(RHS->getValue());
6623         NewRHS.zext(SrcBits);
6624         NewRHS |= KnownOne;
6625         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6626                             ConstantInt::get(*Context, NewRHS));
6627       }
6628     }
6629     break;
6630       
6631   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6632     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6633       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6634       // fold the xor.
6635       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6636           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6637         Value *CompareVal = LHSI->getOperand(0);
6638         
6639         // If the sign bit of the XorCST is not set, there is no change to
6640         // the operation, just stop using the Xor.
6641         if (!XorCST->getValue().isNegative()) {
6642           ICI.setOperand(0, CompareVal);
6643           Worklist.Add(LHSI);
6644           return &ICI;
6645         }
6646         
6647         // Was the old condition true if the operand is positive?
6648         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6649         
6650         // If so, the new one isn't.
6651         isTrueIfPositive ^= true;
6652         
6653         if (isTrueIfPositive)
6654           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
6655                               SubOne(RHS));
6656         else
6657           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
6658                               AddOne(RHS));
6659       }
6660
6661       if (LHSI->hasOneUse()) {
6662         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6663         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6664           const APInt &SignBit = XorCST->getValue();
6665           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6666                                          ? ICI.getUnsignedPredicate()
6667                                          : ICI.getSignedPredicate();
6668           return new ICmpInst(Pred, LHSI->getOperand(0),
6669                               ConstantInt::get(*Context, RHSV ^ SignBit));
6670         }
6671
6672         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6673         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6674           const APInt &NotSignBit = XorCST->getValue();
6675           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6676                                          ? ICI.getUnsignedPredicate()
6677                                          : ICI.getSignedPredicate();
6678           Pred = ICI.getSwappedPredicate(Pred);
6679           return new ICmpInst(Pred, LHSI->getOperand(0),
6680                               ConstantInt::get(*Context, RHSV ^ NotSignBit));
6681         }
6682       }
6683     }
6684     break;
6685   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6686     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6687         LHSI->getOperand(0)->hasOneUse()) {
6688       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6689       
6690       // If the LHS is an AND of a truncating cast, we can widen the
6691       // and/compare to be the input width without changing the value
6692       // produced, eliminating a cast.
6693       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6694         // We can do this transformation if either the AND constant does not
6695         // have its sign bit set or if it is an equality comparison. 
6696         // Extending a relational comparison when we're checking the sign
6697         // bit would not work.
6698         if (Cast->hasOneUse() &&
6699             (ICI.isEquality() ||
6700              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6701           uint32_t BitWidth = 
6702             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6703           APInt NewCST = AndCST->getValue();
6704           NewCST.zext(BitWidth);
6705           APInt NewCI = RHSV;
6706           NewCI.zext(BitWidth);
6707           Value *NewAnd = 
6708             Builder->CreateAnd(Cast->getOperand(0),
6709                            ConstantInt::get(*Context, NewCST), LHSI->getName());
6710           return new ICmpInst(ICI.getPredicate(), NewAnd,
6711                               ConstantInt::get(*Context, NewCI));
6712         }
6713       }
6714       
6715       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6716       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6717       // happens a LOT in code produced by the C front-end, for bitfield
6718       // access.
6719       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6720       if (Shift && !Shift->isShift())
6721         Shift = 0;
6722       
6723       ConstantInt *ShAmt;
6724       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6725       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6726       const Type *AndTy = AndCST->getType();          // Type of the and.
6727       
6728       // We can fold this as long as we can't shift unknown bits
6729       // into the mask.  This can only happen with signed shift
6730       // rights, as they sign-extend.
6731       if (ShAmt) {
6732         bool CanFold = Shift->isLogicalShift();
6733         if (!CanFold) {
6734           // To test for the bad case of the signed shr, see if any
6735           // of the bits shifted in could be tested after the mask.
6736           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6737           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6738           
6739           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6740           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6741                AndCST->getValue()) == 0)
6742             CanFold = true;
6743         }
6744         
6745         if (CanFold) {
6746           Constant *NewCst;
6747           if (Shift->getOpcode() == Instruction::Shl)
6748             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6749           else
6750             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6751           
6752           // Check to see if we are shifting out any of the bits being
6753           // compared.
6754           if (ConstantExpr::get(Shift->getOpcode(),
6755                                        NewCst, ShAmt) != RHS) {
6756             // If we shifted bits out, the fold is not going to work out.
6757             // As a special case, check to see if this means that the
6758             // result is always true or false now.
6759             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6760               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6761             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6762               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6763           } else {
6764             ICI.setOperand(1, NewCst);
6765             Constant *NewAndCST;
6766             if (Shift->getOpcode() == Instruction::Shl)
6767               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6768             else
6769               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6770             LHSI->setOperand(1, NewAndCST);
6771             LHSI->setOperand(0, Shift->getOperand(0));
6772             Worklist.Add(Shift); // Shift is dead.
6773             return &ICI;
6774           }
6775         }
6776       }
6777       
6778       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6779       // preferable because it allows the C<<Y expression to be hoisted out
6780       // of a loop if Y is invariant and X is not.
6781       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6782           ICI.isEquality() && !Shift->isArithmeticShift() &&
6783           !isa<Constant>(Shift->getOperand(0))) {
6784         // Compute C << Y.
6785         Value *NS;
6786         if (Shift->getOpcode() == Instruction::LShr) {
6787           NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
6788         } else {
6789           // Insert a logical shift.
6790           NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
6791         }
6792         
6793         // Compute X & (C << Y).
6794         Value *NewAnd = 
6795           Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6796         
6797         ICI.setOperand(0, NewAnd);
6798         return &ICI;
6799       }
6800     }
6801     break;
6802     
6803   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6804     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6805     if (!ShAmt) break;
6806     
6807     uint32_t TypeBits = RHSV.getBitWidth();
6808     
6809     // Check that the shift amount is in range.  If not, don't perform
6810     // undefined shifts.  When the shift is visited it will be
6811     // simplified.
6812     if (ShAmt->uge(TypeBits))
6813       break;
6814     
6815     if (ICI.isEquality()) {
6816       // If we are comparing against bits always shifted out, the
6817       // comparison cannot succeed.
6818       Constant *Comp =
6819         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
6820                                                                  ShAmt);
6821       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6822         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6823         Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6824         return ReplaceInstUsesWith(ICI, Cst);
6825       }
6826       
6827       if (LHSI->hasOneUse()) {
6828         // Otherwise strength reduce the shift into an and.
6829         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6830         Constant *Mask =
6831           ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits, 
6832                                                        TypeBits-ShAmtVal));
6833         
6834         Value *And =
6835           Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
6836         return new ICmpInst(ICI.getPredicate(), And,
6837                             ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
6838       }
6839     }
6840     
6841     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6842     bool TrueIfSigned = false;
6843     if (LHSI->hasOneUse() &&
6844         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6845       // (X << 31) <s 0  --> (X&1) != 0
6846       Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
6847                                            (TypeBits-ShAmt->getZExtValue()-1));
6848       Value *And =
6849         Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
6850       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6851                           And, Constant::getNullValue(And->getType()));
6852     }
6853     break;
6854   }
6855     
6856   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6857   case Instruction::AShr: {
6858     // Only handle equality comparisons of shift-by-constant.
6859     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6860     if (!ShAmt || !ICI.isEquality()) break;
6861
6862     // Check that the shift amount is in range.  If not, don't perform
6863     // undefined shifts.  When the shift is visited it will be
6864     // simplified.
6865     uint32_t TypeBits = RHSV.getBitWidth();
6866     if (ShAmt->uge(TypeBits))
6867       break;
6868     
6869     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6870       
6871     // If we are comparing against bits always shifted out, the
6872     // comparison cannot succeed.
6873     APInt Comp = RHSV << ShAmtVal;
6874     if (LHSI->getOpcode() == Instruction::LShr)
6875       Comp = Comp.lshr(ShAmtVal);
6876     else
6877       Comp = Comp.ashr(ShAmtVal);
6878     
6879     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6880       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6881       Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6882       return ReplaceInstUsesWith(ICI, Cst);
6883     }
6884     
6885     // Otherwise, check to see if the bits shifted out are known to be zero.
6886     // If so, we can compare against the unshifted value:
6887     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6888     if (LHSI->hasOneUse() &&
6889         MaskedValueIsZero(LHSI->getOperand(0), 
6890                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6891       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6892                           ConstantExpr::getShl(RHS, ShAmt));
6893     }
6894       
6895     if (LHSI->hasOneUse()) {
6896       // Otherwise strength reduce the shift into an and.
6897       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6898       Constant *Mask = ConstantInt::get(*Context, Val);
6899       
6900       Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6901                                       Mask, LHSI->getName()+".mask");
6902       return new ICmpInst(ICI.getPredicate(), And,
6903                           ConstantExpr::getShl(RHS, ShAmt));
6904     }
6905     break;
6906   }
6907     
6908   case Instruction::SDiv:
6909   case Instruction::UDiv:
6910     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6911     // Fold this div into the comparison, producing a range check. 
6912     // Determine, based on the divide type, what the range is being 
6913     // checked.  If there is an overflow on the low or high side, remember 
6914     // it, otherwise compute the range [low, hi) bounding the new value.
6915     // See: InsertRangeTest above for the kinds of replacements possible.
6916     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6917       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6918                                           DivRHS))
6919         return R;
6920     break;
6921
6922   case Instruction::Add:
6923     // Fold: icmp pred (add, X, C1), C2
6924
6925     if (!ICI.isEquality()) {
6926       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6927       if (!LHSC) break;
6928       const APInt &LHSV = LHSC->getValue();
6929
6930       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6931                             .subtract(LHSV);
6932
6933       if (ICI.isSignedPredicate()) {
6934         if (CR.getLower().isSignBit()) {
6935           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6936                               ConstantInt::get(*Context, CR.getUpper()));
6937         } else if (CR.getUpper().isSignBit()) {
6938           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6939                               ConstantInt::get(*Context, CR.getLower()));
6940         }
6941       } else {
6942         if (CR.getLower().isMinValue()) {
6943           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6944                               ConstantInt::get(*Context, CR.getUpper()));
6945         } else if (CR.getUpper().isMinValue()) {
6946           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6947                               ConstantInt::get(*Context, CR.getLower()));
6948         }
6949       }
6950     }
6951     break;
6952   }
6953   
6954   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6955   if (ICI.isEquality()) {
6956     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6957     
6958     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6959     // the second operand is a constant, simplify a bit.
6960     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6961       switch (BO->getOpcode()) {
6962       case Instruction::SRem:
6963         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6964         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6965           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6966           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6967             Value *NewRem =
6968               Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
6969                                   BO->getName());
6970             return new ICmpInst(ICI.getPredicate(), NewRem,
6971                                 Constant::getNullValue(BO->getType()));
6972           }
6973         }
6974         break;
6975       case Instruction::Add:
6976         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6977         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6978           if (BO->hasOneUse())
6979             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6980                                 ConstantExpr::getSub(RHS, BOp1C));
6981         } else if (RHSV == 0) {
6982           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6983           // efficiently invertible, or if the add has just this one use.
6984           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6985           
6986           if (Value *NegVal = dyn_castNegVal(BOp1))
6987             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6988           else if (Value *NegVal = dyn_castNegVal(BOp0))
6989             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6990           else if (BO->hasOneUse()) {
6991             Value *Neg = Builder->CreateNeg(BOp1);
6992             Neg->takeName(BO);
6993             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6994           }
6995         }
6996         break;
6997       case Instruction::Xor:
6998         // For the xor case, we can xor two constants together, eliminating
6999         // the explicit xor.
7000         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7001           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
7002                               ConstantExpr::getXor(RHS, BOC));
7003         
7004         // FALLTHROUGH
7005       case Instruction::Sub:
7006         // Replace (([sub|xor] A, B) != 0) with (A != B)
7007         if (RHSV == 0)
7008           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7009                               BO->getOperand(1));
7010         break;
7011         
7012       case Instruction::Or:
7013         // If bits are being or'd in that are not present in the constant we
7014         // are comparing against, then the comparison could never succeed!
7015         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7016           Constant *NotCI = ConstantExpr::getNot(RHS);
7017           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7018             return ReplaceInstUsesWith(ICI,
7019                                        ConstantInt::get(Type::getInt1Ty(*Context), 
7020                                        isICMP_NE));
7021         }
7022         break;
7023         
7024       case Instruction::And:
7025         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7026           // If bits are being compared against that are and'd out, then the
7027           // comparison can never succeed!
7028           if ((RHSV & ~BOC->getValue()) != 0)
7029             return ReplaceInstUsesWith(ICI,
7030                                        ConstantInt::get(Type::getInt1Ty(*Context),
7031                                        isICMP_NE));
7032           
7033           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7034           if (RHS == BOC && RHSV.isPowerOf2())
7035             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7036                                 ICmpInst::ICMP_NE, LHSI,
7037                                 Constant::getNullValue(RHS->getType()));
7038           
7039           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7040           if (BOC->getValue().isSignBit()) {
7041             Value *X = BO->getOperand(0);
7042             Constant *Zero = Constant::getNullValue(X->getType());
7043             ICmpInst::Predicate pred = isICMP_NE ? 
7044               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7045             return new ICmpInst(pred, X, Zero);
7046           }
7047           
7048           // ((X & ~7) == 0) --> X < 8
7049           if (RHSV == 0 && isHighOnes(BOC)) {
7050             Value *X = BO->getOperand(0);
7051             Constant *NegX = ConstantExpr::getNeg(BOC);
7052             ICmpInst::Predicate pred = isICMP_NE ? 
7053               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7054             return new ICmpInst(pred, X, NegX);
7055           }
7056         }
7057       default: break;
7058       }
7059     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7060       // Handle icmp {eq|ne} <intrinsic>, intcst.
7061       if (II->getIntrinsicID() == Intrinsic::bswap) {
7062         Worklist.Add(II);
7063         ICI.setOperand(0, II->getOperand(1));
7064         ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7065         return &ICI;
7066       }
7067     }
7068   }
7069   return 0;
7070 }
7071
7072 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7073 /// We only handle extending casts so far.
7074 ///
7075 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7076   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7077   Value *LHSCIOp        = LHSCI->getOperand(0);
7078   const Type *SrcTy     = LHSCIOp->getType();
7079   const Type *DestTy    = LHSCI->getType();
7080   Value *RHSCIOp;
7081
7082   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7083   // integer type is the same size as the pointer type.
7084   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7085       TD->getPointerSizeInBits() ==
7086          cast<IntegerType>(DestTy)->getBitWidth()) {
7087     Value *RHSOp = 0;
7088     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7089       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7090     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7091       RHSOp = RHSC->getOperand(0);
7092       // If the pointer types don't match, insert a bitcast.
7093       if (LHSCIOp->getType() != RHSOp->getType())
7094         RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
7095     }
7096
7097     if (RHSOp)
7098       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7099   }
7100   
7101   // The code below only handles extension cast instructions, so far.
7102   // Enforce this.
7103   if (LHSCI->getOpcode() != Instruction::ZExt &&
7104       LHSCI->getOpcode() != Instruction::SExt)
7105     return 0;
7106
7107   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7108   bool isSignedCmp = ICI.isSignedPredicate();
7109
7110   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7111     // Not an extension from the same type?
7112     RHSCIOp = CI->getOperand(0);
7113     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7114       return 0;
7115     
7116     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7117     // and the other is a zext), then we can't handle this.
7118     if (CI->getOpcode() != LHSCI->getOpcode())
7119       return 0;
7120
7121     // Deal with equality cases early.
7122     if (ICI.isEquality())
7123       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7124
7125     // A signed comparison of sign extended values simplifies into a
7126     // signed comparison.
7127     if (isSignedCmp && isSignedExt)
7128       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7129
7130     // The other three cases all fold into an unsigned comparison.
7131     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7132   }
7133
7134   // If we aren't dealing with a constant on the RHS, exit early
7135   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7136   if (!CI)
7137     return 0;
7138
7139   // Compute the constant that would happen if we truncated to SrcTy then
7140   // reextended to DestTy.
7141   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7142   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7143                                                 Res1, DestTy);
7144
7145   // If the re-extended constant didn't change...
7146   if (Res2 == CI) {
7147     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7148     // For example, we might have:
7149     //    %A = sext i16 %X to i32
7150     //    %B = icmp ugt i32 %A, 1330
7151     // It is incorrect to transform this into 
7152     //    %B = icmp ugt i16 %X, 1330
7153     // because %A may have negative value. 
7154     //
7155     // However, we allow this when the compare is EQ/NE, because they are
7156     // signless.
7157     if (isSignedExt == isSignedCmp || ICI.isEquality())
7158       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7159     return 0;
7160   }
7161
7162   // The re-extended constant changed so the constant cannot be represented 
7163   // in the shorter type. Consequently, we cannot emit a simple comparison.
7164
7165   // First, handle some easy cases. We know the result cannot be equal at this
7166   // point so handle the ICI.isEquality() cases
7167   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7168     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7169   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7170     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7171
7172   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7173   // should have been folded away previously and not enter in here.
7174   Value *Result;
7175   if (isSignedCmp) {
7176     // We're performing a signed comparison.
7177     if (cast<ConstantInt>(CI)->getValue().isNegative())
7178       Result = ConstantInt::getFalse(*Context);          // X < (small) --> false
7179     else
7180       Result = ConstantInt::getTrue(*Context);           // X < (large) --> true
7181   } else {
7182     // We're performing an unsigned comparison.
7183     if (isSignedExt) {
7184       // We're performing an unsigned comp with a sign extended value.
7185       // This is true if the input is >= 0. [aka >s -1]
7186       Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7187       Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
7188     } else {
7189       // Unsigned extend & unsigned compare -> always true.
7190       Result = ConstantInt::getTrue(*Context);
7191     }
7192   }
7193
7194   // Finally, return the value computed.
7195   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7196       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7197     return ReplaceInstUsesWith(ICI, Result);
7198
7199   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7200           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7201          "ICmp should be folded!");
7202   if (Constant *CI = dyn_cast<Constant>(Result))
7203     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7204   return BinaryOperator::CreateNot(Result);
7205 }
7206
7207 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7208   return commonShiftTransforms(I);
7209 }
7210
7211 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7212   return commonShiftTransforms(I);
7213 }
7214
7215 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7216   if (Instruction *R = commonShiftTransforms(I))
7217     return R;
7218   
7219   Value *Op0 = I.getOperand(0);
7220   
7221   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7222   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7223     if (CSI->isAllOnesValue())
7224       return ReplaceInstUsesWith(I, CSI);
7225
7226   // See if we can turn a signed shr into an unsigned shr.
7227   if (MaskedValueIsZero(Op0,
7228                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7229     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7230
7231   // Arithmetic shifting an all-sign-bit value is a no-op.
7232   unsigned NumSignBits = ComputeNumSignBits(Op0);
7233   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7234     return ReplaceInstUsesWith(I, Op0);
7235
7236   return 0;
7237 }
7238
7239 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7240   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7241   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7242
7243   // shl X, 0 == X and shr X, 0 == X
7244   // shl 0, X == 0 and shr 0, X == 0
7245   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7246       Op0 == Constant::getNullValue(Op0->getType()))
7247     return ReplaceInstUsesWith(I, Op0);
7248   
7249   if (isa<UndefValue>(Op0)) {            
7250     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7251       return ReplaceInstUsesWith(I, Op0);
7252     else                                    // undef << X -> 0, undef >>u X -> 0
7253       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7254   }
7255   if (isa<UndefValue>(Op1)) {
7256     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7257       return ReplaceInstUsesWith(I, Op0);          
7258     else                                     // X << undef, X >>u undef -> 0
7259       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7260   }
7261
7262   // See if we can fold away this shift.
7263   if (SimplifyDemandedInstructionBits(I))
7264     return &I;
7265
7266   // Try to fold constant and into select arguments.
7267   if (isa<Constant>(Op0))
7268     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7269       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7270         return R;
7271
7272   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7273     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7274       return Res;
7275   return 0;
7276 }
7277
7278 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7279                                                BinaryOperator &I) {
7280   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7281
7282   // See if we can simplify any instructions used by the instruction whose sole 
7283   // purpose is to compute bits we don't care about.
7284   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7285   
7286   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7287   // a signed shift.
7288   //
7289   if (Op1->uge(TypeBits)) {
7290     if (I.getOpcode() != Instruction::AShr)
7291       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7292     else {
7293       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7294       return &I;
7295     }
7296   }
7297   
7298   // ((X*C1) << C2) == (X * (C1 << C2))
7299   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7300     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7301       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7302         return BinaryOperator::CreateMul(BO->getOperand(0),
7303                                         ConstantExpr::getShl(BOOp, Op1));
7304   
7305   // Try to fold constant and into select arguments.
7306   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7307     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7308       return R;
7309   if (isa<PHINode>(Op0))
7310     if (Instruction *NV = FoldOpIntoPhi(I))
7311       return NV;
7312   
7313   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7314   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7315     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7316     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7317     // place.  Don't try to do this transformation in this case.  Also, we
7318     // require that the input operand is a shift-by-constant so that we have
7319     // confidence that the shifts will get folded together.  We could do this
7320     // xform in more cases, but it is unlikely to be profitable.
7321     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7322         isa<ConstantInt>(TrOp->getOperand(1))) {
7323       // Okay, we'll do this xform.  Make the shift of shift.
7324       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7325       // (shift2 (shift1 & 0x00FF), c2)
7326       Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
7327
7328       // For logical shifts, the truncation has the effect of making the high
7329       // part of the register be zeros.  Emulate this by inserting an AND to
7330       // clear the top bits as needed.  This 'and' will usually be zapped by
7331       // other xforms later if dead.
7332       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7333       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7334       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7335       
7336       // The mask we constructed says what the trunc would do if occurring
7337       // between the shifts.  We want to know the effect *after* the second
7338       // shift.  We know that it is a logical shift by a constant, so adjust the
7339       // mask as appropriate.
7340       if (I.getOpcode() == Instruction::Shl)
7341         MaskV <<= Op1->getZExtValue();
7342       else {
7343         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7344         MaskV = MaskV.lshr(Op1->getZExtValue());
7345       }
7346
7347       // shift1 & 0x00FF
7348       Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7349                                       TI->getName());
7350
7351       // Return the value truncated to the interesting size.
7352       return new TruncInst(And, I.getType());
7353     }
7354   }
7355   
7356   if (Op0->hasOneUse()) {
7357     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7358       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7359       Value *V1, *V2;
7360       ConstantInt *CC;
7361       switch (Op0BO->getOpcode()) {
7362         default: break;
7363         case Instruction::Add:
7364         case Instruction::And:
7365         case Instruction::Or:
7366         case Instruction::Xor: {
7367           // These operators commute.
7368           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7369           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7370               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7371                     m_Specific(Op1)))) {
7372             Value *YS =         // (Y << C)
7373               Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7374             // (X + (Y << C))
7375             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7376                                             Op0BO->getOperand(1)->getName());
7377             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7378             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7379                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7380           }
7381           
7382           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7383           Value *Op0BOOp1 = Op0BO->getOperand(1);
7384           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7385               match(Op0BOOp1, 
7386                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7387                           m_ConstantInt(CC))) &&
7388               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7389             Value *YS =   // (Y << C)
7390               Builder->CreateShl(Op0BO->getOperand(0), Op1,
7391                                            Op0BO->getName());
7392             // X & (CC << C)
7393             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7394                                            V1->getName()+".mask");
7395             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7396           }
7397         }
7398           
7399         // FALL THROUGH.
7400         case Instruction::Sub: {
7401           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7402           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7403               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7404                     m_Specific(Op1)))) {
7405             Value *YS =  // (Y << C)
7406               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7407             // (X + (Y << C))
7408             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7409                                             Op0BO->getOperand(0)->getName());
7410             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7411             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7412                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7413           }
7414           
7415           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7416           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7417               match(Op0BO->getOperand(0),
7418                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7419                           m_ConstantInt(CC))) && V2 == Op1 &&
7420               cast<BinaryOperator>(Op0BO->getOperand(0))
7421                   ->getOperand(0)->hasOneUse()) {
7422             Value *YS = // (Y << C)
7423               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7424             // X & (CC << C)
7425             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7426                                            V1->getName()+".mask");
7427             
7428             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7429           }
7430           
7431           break;
7432         }
7433       }
7434       
7435       
7436       // If the operand is an bitwise operator with a constant RHS, and the
7437       // shift is the only use, we can pull it out of the shift.
7438       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7439         bool isValid = true;     // Valid only for And, Or, Xor
7440         bool highBitSet = false; // Transform if high bit of constant set?
7441         
7442         switch (Op0BO->getOpcode()) {
7443           default: isValid = false; break;   // Do not perform transform!
7444           case Instruction::Add:
7445             isValid = isLeftShift;
7446             break;
7447           case Instruction::Or:
7448           case Instruction::Xor:
7449             highBitSet = false;
7450             break;
7451           case Instruction::And:
7452             highBitSet = true;
7453             break;
7454         }
7455         
7456         // If this is a signed shift right, and the high bit is modified
7457         // by the logical operation, do not perform the transformation.
7458         // The highBitSet boolean indicates the value of the high bit of
7459         // the constant which would cause it to be modified for this
7460         // operation.
7461         //
7462         if (isValid && I.getOpcode() == Instruction::AShr)
7463           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7464         
7465         if (isValid) {
7466           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7467           
7468           Value *NewShift =
7469             Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
7470           NewShift->takeName(Op0BO);
7471           
7472           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7473                                         NewRHS);
7474         }
7475       }
7476     }
7477   }
7478   
7479   // Find out if this is a shift of a shift by a constant.
7480   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7481   if (ShiftOp && !ShiftOp->isShift())
7482     ShiftOp = 0;
7483   
7484   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7485     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7486     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7487     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7488     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7489     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7490     Value *X = ShiftOp->getOperand(0);
7491     
7492     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7493     
7494     const IntegerType *Ty = cast<IntegerType>(I.getType());
7495     
7496     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7497     if (I.getOpcode() == ShiftOp->getOpcode()) {
7498       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7499       // saturates.
7500       if (AmtSum >= TypeBits) {
7501         if (I.getOpcode() != Instruction::AShr)
7502           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7503         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7504       }
7505       
7506       return BinaryOperator::Create(I.getOpcode(), X,
7507                                     ConstantInt::get(Ty, AmtSum));
7508     }
7509     
7510     if (ShiftOp->getOpcode() == Instruction::LShr &&
7511         I.getOpcode() == Instruction::AShr) {
7512       if (AmtSum >= TypeBits)
7513         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7514       
7515       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7516       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7517     }
7518     
7519     if (ShiftOp->getOpcode() == Instruction::AShr &&
7520         I.getOpcode() == Instruction::LShr) {
7521       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7522       if (AmtSum >= TypeBits)
7523         AmtSum = TypeBits-1;
7524       
7525       Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7526
7527       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7528       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7529     }
7530     
7531     // Okay, if we get here, one shift must be left, and the other shift must be
7532     // right.  See if the amounts are equal.
7533     if (ShiftAmt1 == ShiftAmt2) {
7534       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7535       if (I.getOpcode() == Instruction::Shl) {
7536         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7537         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7538       }
7539       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7540       if (I.getOpcode() == Instruction::LShr) {
7541         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7542         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7543       }
7544       // We can simplify ((X << C) >>s C) into a trunc + sext.
7545       // NOTE: we could do this for any C, but that would make 'unusual' integer
7546       // types.  For now, just stick to ones well-supported by the code
7547       // generators.
7548       const Type *SExtType = 0;
7549       switch (Ty->getBitWidth() - ShiftAmt1) {
7550       case 1  :
7551       case 8  :
7552       case 16 :
7553       case 32 :
7554       case 64 :
7555       case 128:
7556         SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
7557         break;
7558       default: break;
7559       }
7560       if (SExtType)
7561         return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
7562       // Otherwise, we can't handle it yet.
7563     } else if (ShiftAmt1 < ShiftAmt2) {
7564       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7565       
7566       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7567       if (I.getOpcode() == Instruction::Shl) {
7568         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7569                ShiftOp->getOpcode() == Instruction::AShr);
7570         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7571         
7572         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7573         return BinaryOperator::CreateAnd(Shift,
7574                                          ConstantInt::get(*Context, Mask));
7575       }
7576       
7577       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7578       if (I.getOpcode() == Instruction::LShr) {
7579         assert(ShiftOp->getOpcode() == Instruction::Shl);
7580         Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7581         
7582         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7583         return BinaryOperator::CreateAnd(Shift,
7584                                          ConstantInt::get(*Context, Mask));
7585       }
7586       
7587       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7588     } else {
7589       assert(ShiftAmt2 < ShiftAmt1);
7590       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7591
7592       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7593       if (I.getOpcode() == Instruction::Shl) {
7594         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7595                ShiftOp->getOpcode() == Instruction::AShr);
7596         Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7597                                             ConstantInt::get(Ty, ShiftDiff));
7598         
7599         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7600         return BinaryOperator::CreateAnd(Shift,
7601                                          ConstantInt::get(*Context, Mask));
7602       }
7603       
7604       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7605       if (I.getOpcode() == Instruction::LShr) {
7606         assert(ShiftOp->getOpcode() == Instruction::Shl);
7607         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7608         
7609         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7610         return BinaryOperator::CreateAnd(Shift,
7611                                          ConstantInt::get(*Context, Mask));
7612       }
7613       
7614       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7615     }
7616   }
7617   return 0;
7618 }
7619
7620
7621 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7622 /// expression.  If so, decompose it, returning some value X, such that Val is
7623 /// X*Scale+Offset.
7624 ///
7625 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7626                                         int &Offset, LLVMContext *Context) {
7627   assert(Val->getType() == Type::getInt32Ty(*Context) && 
7628          "Unexpected allocation size type!");
7629   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7630     Offset = CI->getZExtValue();
7631     Scale  = 0;
7632     return ConstantInt::get(Type::getInt32Ty(*Context), 0);
7633   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7634     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7635       if (I->getOpcode() == Instruction::Shl) {
7636         // This is a value scaled by '1 << the shift amt'.
7637         Scale = 1U << RHS->getZExtValue();
7638         Offset = 0;
7639         return I->getOperand(0);
7640       } else if (I->getOpcode() == Instruction::Mul) {
7641         // This value is scaled by 'RHS'.
7642         Scale = RHS->getZExtValue();
7643         Offset = 0;
7644         return I->getOperand(0);
7645       } else if (I->getOpcode() == Instruction::Add) {
7646         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7647         // where C1 is divisible by C2.
7648         unsigned SubScale;
7649         Value *SubVal = 
7650           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7651                                     Offset, Context);
7652         Offset += RHS->getZExtValue();
7653         Scale = SubScale;
7654         return SubVal;
7655       }
7656     }
7657   }
7658
7659   // Otherwise, we can't look past this.
7660   Scale = 1;
7661   Offset = 0;
7662   return Val;
7663 }
7664
7665
7666 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7667 /// try to eliminate the cast by moving the type information into the alloc.
7668 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7669                                                    AllocationInst &AI) {
7670   const PointerType *PTy = cast<PointerType>(CI.getType());
7671   
7672   BuilderTy AllocaBuilder(*Builder);
7673   AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7674   
7675   // Remove any uses of AI that are dead.
7676   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7677   
7678   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7679     Instruction *User = cast<Instruction>(*UI++);
7680     if (isInstructionTriviallyDead(User)) {
7681       while (UI != E && *UI == User)
7682         ++UI; // If this instruction uses AI more than once, don't break UI.
7683       
7684       ++NumDeadInst;
7685       DEBUG(errs() << "IC: DCE: " << *User << '\n');
7686       EraseInstFromFunction(*User);
7687     }
7688   }
7689
7690   // This requires TargetData to get the alloca alignment and size information.
7691   if (!TD) return 0;
7692
7693   // Get the type really allocated and the type casted to.
7694   const Type *AllocElTy = AI.getAllocatedType();
7695   const Type *CastElTy = PTy->getElementType();
7696   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7697
7698   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7699   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7700   if (CastElTyAlign < AllocElTyAlign) return 0;
7701
7702   // If the allocation has multiple uses, only promote it if we are strictly
7703   // increasing the alignment of the resultant allocation.  If we keep it the
7704   // same, we open the door to infinite loops of various kinds.  (A reference
7705   // from a dbg.declare doesn't count as a use for this purpose.)
7706   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7707       CastElTyAlign == AllocElTyAlign) return 0;
7708
7709   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7710   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7711   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7712
7713   // See if we can satisfy the modulus by pulling a scale out of the array
7714   // size argument.
7715   unsigned ArraySizeScale;
7716   int ArrayOffset;
7717   Value *NumElements = // See if the array size is a decomposable linear expr.
7718     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7719                               ArrayOffset, Context);
7720  
7721   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7722   // do the xform.
7723   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7724       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7725
7726   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7727   Value *Amt = 0;
7728   if (Scale == 1) {
7729     Amt = NumElements;
7730   } else {
7731     Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
7732     // Insert before the alloca, not before the cast.
7733     Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
7734   }
7735   
7736   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7737     Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
7738     Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
7739   }
7740   
7741   AllocationInst *New;
7742   if (isa<MallocInst>(AI))
7743     New = AllocaBuilder.CreateMalloc(CastElTy, Amt);
7744   else
7745     New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7746   New->setAlignment(AI.getAlignment());
7747   New->takeName(&AI);
7748   
7749   // If the allocation has one real use plus a dbg.declare, just remove the
7750   // declare.
7751   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7752     EraseInstFromFunction(*DI);
7753   }
7754   // If the allocation has multiple real uses, insert a cast and change all
7755   // things that used it to use the new cast.  This will also hack on CI, but it
7756   // will die soon.
7757   else if (!AI.hasOneUse()) {
7758     // New is the allocation instruction, pointer typed. AI is the original
7759     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7760     Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
7761     AI.replaceAllUsesWith(NewCast);
7762   }
7763   return ReplaceInstUsesWith(CI, New);
7764 }
7765
7766 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7767 /// and return it as type Ty without inserting any new casts and without
7768 /// changing the computed value.  This is used by code that tries to decide
7769 /// whether promoting or shrinking integer operations to wider or smaller types
7770 /// will allow us to eliminate a truncate or extend.
7771 ///
7772 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7773 /// extension operation if Ty is larger.
7774 ///
7775 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7776 /// should return true if trunc(V) can be computed by computing V in the smaller
7777 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7778 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7779 /// efficiently truncated.
7780 ///
7781 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7782 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7783 /// the final result.
7784 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7785                                               unsigned CastOpc,
7786                                               int &NumCastsRemoved){
7787   // We can always evaluate constants in another type.
7788   if (isa<Constant>(V))
7789     return true;
7790   
7791   Instruction *I = dyn_cast<Instruction>(V);
7792   if (!I) return false;
7793   
7794   const Type *OrigTy = V->getType();
7795   
7796   // If this is an extension or truncate, we can often eliminate it.
7797   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7798     // If this is a cast from the destination type, we can trivially eliminate
7799     // it, and this will remove a cast overall.
7800     if (I->getOperand(0)->getType() == Ty) {
7801       // If the first operand is itself a cast, and is eliminable, do not count
7802       // this as an eliminable cast.  We would prefer to eliminate those two
7803       // casts first.
7804       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7805         ++NumCastsRemoved;
7806       return true;
7807     }
7808   }
7809
7810   // We can't extend or shrink something that has multiple uses: doing so would
7811   // require duplicating the instruction in general, which isn't profitable.
7812   if (!I->hasOneUse()) return false;
7813
7814   unsigned Opc = I->getOpcode();
7815   switch (Opc) {
7816   case Instruction::Add:
7817   case Instruction::Sub:
7818   case Instruction::Mul:
7819   case Instruction::And:
7820   case Instruction::Or:
7821   case Instruction::Xor:
7822     // These operators can all arbitrarily be extended or truncated.
7823     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7824                                       NumCastsRemoved) &&
7825            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7826                                       NumCastsRemoved);
7827
7828   case Instruction::UDiv:
7829   case Instruction::URem: {
7830     // UDiv and URem can be truncated if all the truncated bits are zero.
7831     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7832     uint32_t BitWidth = Ty->getScalarSizeInBits();
7833     if (BitWidth < OrigBitWidth) {
7834       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7835       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7836           MaskedValueIsZero(I->getOperand(1), Mask)) {
7837         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7838                                           NumCastsRemoved) &&
7839                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7840                                           NumCastsRemoved);
7841       }
7842     }
7843     break;
7844   }
7845   case Instruction::Shl:
7846     // If we are truncating the result of this SHL, and if it's a shift of a
7847     // constant amount, we can always perform a SHL in a smaller type.
7848     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7849       uint32_t BitWidth = Ty->getScalarSizeInBits();
7850       if (BitWidth < OrigTy->getScalarSizeInBits() &&
7851           CI->getLimitedValue(BitWidth) < BitWidth)
7852         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7853                                           NumCastsRemoved);
7854     }
7855     break;
7856   case Instruction::LShr:
7857     // If this is a truncate of a logical shr, we can truncate it to a smaller
7858     // lshr iff we know that the bits we would otherwise be shifting in are
7859     // already zeros.
7860     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7861       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7862       uint32_t BitWidth = Ty->getScalarSizeInBits();
7863       if (BitWidth < OrigBitWidth &&
7864           MaskedValueIsZero(I->getOperand(0),
7865             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7866           CI->getLimitedValue(BitWidth) < BitWidth) {
7867         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7868                                           NumCastsRemoved);
7869       }
7870     }
7871     break;
7872   case Instruction::ZExt:
7873   case Instruction::SExt:
7874   case Instruction::Trunc:
7875     // If this is the same kind of case as our original (e.g. zext+zext), we
7876     // can safely replace it.  Note that replacing it does not reduce the number
7877     // of casts in the input.
7878     if (Opc == CastOpc)
7879       return true;
7880
7881     // sext (zext ty1), ty2 -> zext ty2
7882     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7883       return true;
7884     break;
7885   case Instruction::Select: {
7886     SelectInst *SI = cast<SelectInst>(I);
7887     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7888                                       NumCastsRemoved) &&
7889            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7890                                       NumCastsRemoved);
7891   }
7892   case Instruction::PHI: {
7893     // We can change a phi if we can change all operands.
7894     PHINode *PN = cast<PHINode>(I);
7895     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7896       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7897                                       NumCastsRemoved))
7898         return false;
7899     return true;
7900   }
7901   default:
7902     // TODO: Can handle more cases here.
7903     break;
7904   }
7905   
7906   return false;
7907 }
7908
7909 /// EvaluateInDifferentType - Given an expression that 
7910 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7911 /// evaluate the expression.
7912 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7913                                              bool isSigned) {
7914   if (Constant *C = dyn_cast<Constant>(V))
7915     return ConstantExpr::getIntegerCast(C, Ty,
7916                                                isSigned /*Sext or ZExt*/);
7917
7918   // Otherwise, it must be an instruction.
7919   Instruction *I = cast<Instruction>(V);
7920   Instruction *Res = 0;
7921   unsigned Opc = I->getOpcode();
7922   switch (Opc) {
7923   case Instruction::Add:
7924   case Instruction::Sub:
7925   case Instruction::Mul:
7926   case Instruction::And:
7927   case Instruction::Or:
7928   case Instruction::Xor:
7929   case Instruction::AShr:
7930   case Instruction::LShr:
7931   case Instruction::Shl:
7932   case Instruction::UDiv:
7933   case Instruction::URem: {
7934     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7935     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7936     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7937     break;
7938   }    
7939   case Instruction::Trunc:
7940   case Instruction::ZExt:
7941   case Instruction::SExt:
7942     // If the source type of the cast is the type we're trying for then we can
7943     // just return the source.  There's no need to insert it because it is not
7944     // new.
7945     if (I->getOperand(0)->getType() == Ty)
7946       return I->getOperand(0);
7947     
7948     // Otherwise, must be the same type of cast, so just reinsert a new one.
7949     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7950                            Ty);
7951     break;
7952   case Instruction::Select: {
7953     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7954     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7955     Res = SelectInst::Create(I->getOperand(0), True, False);
7956     break;
7957   }
7958   case Instruction::PHI: {
7959     PHINode *OPN = cast<PHINode>(I);
7960     PHINode *NPN = PHINode::Create(Ty);
7961     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7962       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7963       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7964     }
7965     Res = NPN;
7966     break;
7967   }
7968   default: 
7969     // TODO: Can handle more cases here.
7970     llvm_unreachable("Unreachable!");
7971     break;
7972   }
7973   
7974   Res->takeName(I);
7975   return InsertNewInstBefore(Res, *I);
7976 }
7977
7978 /// @brief Implement the transforms common to all CastInst visitors.
7979 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7980   Value *Src = CI.getOperand(0);
7981
7982   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7983   // eliminate it now.
7984   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7985     if (Instruction::CastOps opc = 
7986         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7987       // The first cast (CSrc) is eliminable so we need to fix up or replace
7988       // the second cast (CI). CSrc will then have a good chance of being dead.
7989       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7990     }
7991   }
7992
7993   // If we are casting a select then fold the cast into the select
7994   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7995     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7996       return NV;
7997
7998   // If we are casting a PHI then fold the cast into the PHI
7999   if (isa<PHINode>(Src))
8000     if (Instruction *NV = FoldOpIntoPhi(CI))
8001       return NV;
8002   
8003   return 0;
8004 }
8005
8006 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8007 /// or not there is a sequence of GEP indices into the type that will land us at
8008 /// the specified offset.  If so, fill them into NewIndices and return the
8009 /// resultant element type, otherwise return null.
8010 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8011                                        SmallVectorImpl<Value*> &NewIndices,
8012                                        const TargetData *TD,
8013                                        LLVMContext *Context) {
8014   if (!TD) return 0;
8015   if (!Ty->isSized()) return 0;
8016   
8017   // Start with the index over the outer type.  Note that the type size
8018   // might be zero (even if the offset isn't zero) if the indexed type
8019   // is something like [0 x {int, int}]
8020   const Type *IntPtrTy = TD->getIntPtrType(*Context);
8021   int64_t FirstIdx = 0;
8022   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8023     FirstIdx = Offset/TySize;
8024     Offset -= FirstIdx*TySize;
8025     
8026     // Handle hosts where % returns negative instead of values [0..TySize).
8027     if (Offset < 0) {
8028       --FirstIdx;
8029       Offset += TySize;
8030       assert(Offset >= 0);
8031     }
8032     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8033   }
8034   
8035   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8036     
8037   // Index into the types.  If we fail, set OrigBase to null.
8038   while (Offset) {
8039     // Indexing into tail padding between struct/array elements.
8040     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8041       return 0;
8042     
8043     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8044       const StructLayout *SL = TD->getStructLayout(STy);
8045       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8046              "Offset must stay within the indexed type");
8047       
8048       unsigned Elt = SL->getElementContainingOffset(Offset);
8049       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8050       
8051       Offset -= SL->getElementOffset(Elt);
8052       Ty = STy->getElementType(Elt);
8053     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8054       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8055       assert(EltSize && "Cannot index into a zero-sized array");
8056       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8057       Offset %= EltSize;
8058       Ty = AT->getElementType();
8059     } else {
8060       // Otherwise, we can't index into the middle of this atomic type, bail.
8061       return 0;
8062     }
8063   }
8064   
8065   return Ty;
8066 }
8067
8068 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8069 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8070   Value *Src = CI.getOperand(0);
8071   
8072   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8073     // If casting the result of a getelementptr instruction with no offset, turn
8074     // this into a cast of the original pointer!
8075     if (GEP->hasAllZeroIndices()) {
8076       // Changing the cast operand is usually not a good idea but it is safe
8077       // here because the pointer operand is being replaced with another 
8078       // pointer operand so the opcode doesn't need to change.
8079       Worklist.Add(GEP);
8080       CI.setOperand(0, GEP->getOperand(0));
8081       return &CI;
8082     }
8083     
8084     // If the GEP has a single use, and the base pointer is a bitcast, and the
8085     // GEP computes a constant offset, see if we can convert these three
8086     // instructions into fewer.  This typically happens with unions and other
8087     // non-type-safe code.
8088     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8089       if (GEP->hasAllConstantIndices()) {
8090         // We are guaranteed to get a constant from EmitGEPOffset.
8091         ConstantInt *OffsetV =
8092                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8093         int64_t Offset = OffsetV->getSExtValue();
8094         
8095         // Get the base pointer input of the bitcast, and the type it points to.
8096         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8097         const Type *GEPIdxTy =
8098           cast<PointerType>(OrigBase->getType())->getElementType();
8099         SmallVector<Value*, 8> NewIndices;
8100         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8101           // If we were able to index down into an element, create the GEP
8102           // and bitcast the result.  This eliminates one bitcast, potentially
8103           // two.
8104           Value *NGEP = Builder->CreateGEP(OrigBase, NewIndices.begin(),
8105                                            NewIndices.end());
8106           NGEP->takeName(GEP);
8107           if (isa<Instruction>(NGEP) && cast<GEPOperator>(GEP)->isInBounds())
8108             cast<GEPOperator>(NGEP)->setIsInBounds(true);
8109           
8110           if (isa<BitCastInst>(CI))
8111             return new BitCastInst(NGEP, CI.getType());
8112           assert(isa<PtrToIntInst>(CI));
8113           return new PtrToIntInst(NGEP, CI.getType());
8114         }
8115       }      
8116     }
8117   }
8118     
8119   return commonCastTransforms(CI);
8120 }
8121
8122 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8123 /// type like i42.  We don't want to introduce operations on random non-legal
8124 /// integer types where they don't already exist in the code.  In the future,
8125 /// we should consider making this based off target-data, so that 32-bit targets
8126 /// won't get i64 operations etc.
8127 static bool isSafeIntegerType(const Type *Ty) {
8128   switch (Ty->getPrimitiveSizeInBits()) {
8129   case 8:
8130   case 16:
8131   case 32:
8132   case 64:
8133     return true;
8134   default: 
8135     return false;
8136   }
8137 }
8138
8139 /// commonIntCastTransforms - This function implements the common transforms
8140 /// for trunc, zext, and sext.
8141 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8142   if (Instruction *Result = commonCastTransforms(CI))
8143     return Result;
8144
8145   Value *Src = CI.getOperand(0);
8146   const Type *SrcTy = Src->getType();
8147   const Type *DestTy = CI.getType();
8148   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8149   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8150
8151   // See if we can simplify any instructions used by the LHS whose sole 
8152   // purpose is to compute bits we don't care about.
8153   if (SimplifyDemandedInstructionBits(CI))
8154     return &CI;
8155
8156   // If the source isn't an instruction or has more than one use then we
8157   // can't do anything more. 
8158   Instruction *SrcI = dyn_cast<Instruction>(Src);
8159   if (!SrcI || !Src->hasOneUse())
8160     return 0;
8161
8162   // Attempt to propagate the cast into the instruction for int->int casts.
8163   int NumCastsRemoved = 0;
8164   // Only do this if the dest type is a simple type, don't convert the
8165   // expression tree to something weird like i93 unless the source is also
8166   // strange.
8167   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8168        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8169       CanEvaluateInDifferentType(SrcI, DestTy,
8170                                  CI.getOpcode(), NumCastsRemoved)) {
8171     // If this cast is a truncate, evaluting in a different type always
8172     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8173     // we need to do an AND to maintain the clear top-part of the computation,
8174     // so we require that the input have eliminated at least one cast.  If this
8175     // is a sign extension, we insert two new casts (to do the extension) so we
8176     // require that two casts have been eliminated.
8177     bool DoXForm = false;
8178     bool JustReplace = false;
8179     switch (CI.getOpcode()) {
8180     default:
8181       // All the others use floating point so we shouldn't actually 
8182       // get here because of the check above.
8183       llvm_unreachable("Unknown cast type");
8184     case Instruction::Trunc:
8185       DoXForm = true;
8186       break;
8187     case Instruction::ZExt: {
8188       DoXForm = NumCastsRemoved >= 1;
8189       if (!DoXForm && 0) {
8190         // If it's unnecessary to issue an AND to clear the high bits, it's
8191         // always profitable to do this xform.
8192         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8193         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8194         if (MaskedValueIsZero(TryRes, Mask))
8195           return ReplaceInstUsesWith(CI, TryRes);
8196         
8197         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8198           if (TryI->use_empty())
8199             EraseInstFromFunction(*TryI);
8200       }
8201       break;
8202     }
8203     case Instruction::SExt: {
8204       DoXForm = NumCastsRemoved >= 2;
8205       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8206         // If we do not have to emit the truncate + sext pair, then it's always
8207         // profitable to do this xform.
8208         //
8209         // It's not safe to eliminate the trunc + sext pair if one of the
8210         // eliminated cast is a truncate. e.g.
8211         // t2 = trunc i32 t1 to i16
8212         // t3 = sext i16 t2 to i32
8213         // !=
8214         // i32 t1
8215         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8216         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8217         if (NumSignBits > (DestBitSize - SrcBitSize))
8218           return ReplaceInstUsesWith(CI, TryRes);
8219         
8220         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8221           if (TryI->use_empty())
8222             EraseInstFromFunction(*TryI);
8223       }
8224       break;
8225     }
8226     }
8227     
8228     if (DoXForm) {
8229       DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8230             " to avoid cast: " << CI);
8231       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8232                                            CI.getOpcode() == Instruction::SExt);
8233       if (JustReplace)
8234         // Just replace this cast with the result.
8235         return ReplaceInstUsesWith(CI, Res);
8236
8237       assert(Res->getType() == DestTy);
8238       switch (CI.getOpcode()) {
8239       default: llvm_unreachable("Unknown cast type!");
8240       case Instruction::Trunc:
8241         // Just replace this cast with the result.
8242         return ReplaceInstUsesWith(CI, Res);
8243       case Instruction::ZExt: {
8244         assert(SrcBitSize < DestBitSize && "Not a zext?");
8245
8246         // If the high bits are already zero, just replace this cast with the
8247         // result.
8248         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8249         if (MaskedValueIsZero(Res, Mask))
8250           return ReplaceInstUsesWith(CI, Res);
8251
8252         // We need to emit an AND to clear the high bits.
8253         Constant *C = ConstantInt::get(*Context, 
8254                                  APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8255         return BinaryOperator::CreateAnd(Res, C);
8256       }
8257       case Instruction::SExt: {
8258         // If the high bits are already filled with sign bit, just replace this
8259         // cast with the result.
8260         unsigned NumSignBits = ComputeNumSignBits(Res);
8261         if (NumSignBits > (DestBitSize - SrcBitSize))
8262           return ReplaceInstUsesWith(CI, Res);
8263
8264         // We need to emit a cast to truncate, then a cast to sext.
8265         return CastInst::Create(Instruction::SExt,
8266             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8267                              CI), DestTy);
8268       }
8269       }
8270     }
8271   }
8272   
8273   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8274   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8275
8276   switch (SrcI->getOpcode()) {
8277   case Instruction::Add:
8278   case Instruction::Mul:
8279   case Instruction::And:
8280   case Instruction::Or:
8281   case Instruction::Xor:
8282     // If we are discarding information, rewrite.
8283     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8284       // Don't insert two casts unless at least one can be eliminated.
8285       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8286           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8287         Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8288         Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8289         return BinaryOperator::Create(
8290             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8291       }
8292     }
8293
8294     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8295     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8296         SrcI->getOpcode() == Instruction::Xor &&
8297         Op1 == ConstantInt::getTrue(*Context) &&
8298         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8299       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8300       return BinaryOperator::CreateXor(New,
8301                                       ConstantInt::get(CI.getType(), 1));
8302     }
8303     break;
8304
8305   case Instruction::Shl: {
8306     // Canonicalize trunc inside shl, if we can.
8307     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8308     if (CI && DestBitSize < SrcBitSize &&
8309         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8310       Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8311       Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8312       return BinaryOperator::CreateShl(Op0c, Op1c);
8313     }
8314     break;
8315   }
8316   }
8317   return 0;
8318 }
8319
8320 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8321   if (Instruction *Result = commonIntCastTransforms(CI))
8322     return Result;
8323   
8324   Value *Src = CI.getOperand(0);
8325   const Type *Ty = CI.getType();
8326   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8327   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8328
8329   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8330   if (DestBitWidth == 1) {
8331     Constant *One = ConstantInt::get(Src->getType(), 1);
8332     Src = Builder->CreateAnd(Src, One, "tmp");
8333     Value *Zero = Constant::getNullValue(Src->getType());
8334     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8335   }
8336
8337   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8338   ConstantInt *ShAmtV = 0;
8339   Value *ShiftOp = 0;
8340   if (Src->hasOneUse() &&
8341       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8342     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8343     
8344     // Get a mask for the bits shifting in.
8345     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8346     if (MaskedValueIsZero(ShiftOp, Mask)) {
8347       if (ShAmt >= DestBitWidth)        // All zeros.
8348         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8349       
8350       // Okay, we can shrink this.  Truncate the input, then return a new
8351       // shift.
8352       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8353       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8354       return BinaryOperator::CreateLShr(V1, V2);
8355     }
8356   }
8357   
8358   return 0;
8359 }
8360
8361 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8362 /// in order to eliminate the icmp.
8363 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8364                                              bool DoXform) {
8365   // If we are just checking for a icmp eq of a single bit and zext'ing it
8366   // to an integer, then shift the bit to the appropriate place and then
8367   // cast to integer to avoid the comparison.
8368   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8369     const APInt &Op1CV = Op1C->getValue();
8370       
8371     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8372     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8373     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8374         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8375       if (!DoXform) return ICI;
8376
8377       Value *In = ICI->getOperand(0);
8378       Value *Sh = ConstantInt::get(In->getType(),
8379                                    In->getType()->getScalarSizeInBits()-1);
8380       In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
8381       if (In->getType() != CI.getType())
8382         In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
8383
8384       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8385         Constant *One = ConstantInt::get(In->getType(), 1);
8386         In = Builder->CreateXor(In, One, In->getName()+".not");
8387       }
8388
8389       return ReplaceInstUsesWith(CI, In);
8390     }
8391       
8392       
8393       
8394     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8395     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8396     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8397     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8398     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8399     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8400     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8401     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8402     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8403         // This only works for EQ and NE
8404         ICI->isEquality()) {
8405       // If Op1C some other power of two, convert:
8406       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8407       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8408       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8409       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8410         
8411       APInt KnownZeroMask(~KnownZero);
8412       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8413         if (!DoXform) return ICI;
8414
8415         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8416         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8417           // (X&4) == 2 --> false
8418           // (X&4) != 2 --> true
8419           Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8420           Res = ConstantExpr::getZExt(Res, CI.getType());
8421           return ReplaceInstUsesWith(CI, Res);
8422         }
8423           
8424         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8425         Value *In = ICI->getOperand(0);
8426         if (ShiftAmt) {
8427           // Perform a logical shr by shiftamt.
8428           // Insert the shift to put the result in the low bit.
8429           In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8430                                    In->getName()+".lobit");
8431         }
8432           
8433         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8434           Constant *One = ConstantInt::get(In->getType(), 1);
8435           In = Builder->CreateXor(In, One, "tmp");
8436         }
8437           
8438         if (CI.getType() == In->getType())
8439           return ReplaceInstUsesWith(CI, In);
8440         else
8441           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8442       }
8443     }
8444   }
8445
8446   return 0;
8447 }
8448
8449 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8450   // If one of the common conversion will work ..
8451   if (Instruction *Result = commonIntCastTransforms(CI))
8452     return Result;
8453
8454   Value *Src = CI.getOperand(0);
8455
8456   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8457   // types and if the sizes are just right we can convert this into a logical
8458   // 'and' which will be much cheaper than the pair of casts.
8459   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8460     // Get the sizes of the types involved.  We know that the intermediate type
8461     // will be smaller than A or C, but don't know the relation between A and C.
8462     Value *A = CSrc->getOperand(0);
8463     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8464     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8465     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8466     // If we're actually extending zero bits, then if
8467     // SrcSize <  DstSize: zext(a & mask)
8468     // SrcSize == DstSize: a & mask
8469     // SrcSize  > DstSize: trunc(a) & mask
8470     if (SrcSize < DstSize) {
8471       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8472       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8473       Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
8474       return new ZExtInst(And, CI.getType());
8475     }
8476     
8477     if (SrcSize == DstSize) {
8478       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8479       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8480                                                            AndValue));
8481     }
8482     if (SrcSize > DstSize) {
8483       Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
8484       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8485       return BinaryOperator::CreateAnd(Trunc, 
8486                                        ConstantInt::get(Trunc->getType(),
8487                                                                AndValue));
8488     }
8489   }
8490
8491   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8492     return transformZExtICmp(ICI, CI);
8493
8494   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8495   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8496     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8497     // of the (zext icmp) will be transformed.
8498     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8499     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8500     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8501         (transformZExtICmp(LHS, CI, false) ||
8502          transformZExtICmp(RHS, CI, false))) {
8503       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8504       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8505       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8506     }
8507   }
8508
8509   // zext(trunc(t) & C) -> (t & zext(C)).
8510   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8511     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8512       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8513         Value *TI0 = TI->getOperand(0);
8514         if (TI0->getType() == CI.getType())
8515           return
8516             BinaryOperator::CreateAnd(TI0,
8517                                 ConstantExpr::getZExt(C, CI.getType()));
8518       }
8519
8520   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8521   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8522     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8523       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8524         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8525             And->getOperand(1) == C)
8526           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8527             Value *TI0 = TI->getOperand(0);
8528             if (TI0->getType() == CI.getType()) {
8529               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8530               Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
8531               return BinaryOperator::CreateXor(NewAnd, ZC);
8532             }
8533           }
8534
8535   return 0;
8536 }
8537
8538 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8539   if (Instruction *I = commonIntCastTransforms(CI))
8540     return I;
8541   
8542   Value *Src = CI.getOperand(0);
8543   
8544   // Canonicalize sign-extend from i1 to a select.
8545   if (Src->getType() == Type::getInt1Ty(*Context))
8546     return SelectInst::Create(Src,
8547                               Constant::getAllOnesValue(CI.getType()),
8548                               Constant::getNullValue(CI.getType()));
8549
8550   // See if the value being truncated is already sign extended.  If so, just
8551   // eliminate the trunc/sext pair.
8552   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8553     Value *Op = cast<User>(Src)->getOperand(0);
8554     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8555     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8556     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8557     unsigned NumSignBits = ComputeNumSignBits(Op);
8558
8559     if (OpBits == DestBits) {
8560       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8561       // bits, it is already ready.
8562       if (NumSignBits > DestBits-MidBits)
8563         return ReplaceInstUsesWith(CI, Op);
8564     } else if (OpBits < DestBits) {
8565       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8566       // bits, just sext from i32.
8567       if (NumSignBits > OpBits-MidBits)
8568         return new SExtInst(Op, CI.getType(), "tmp");
8569     } else {
8570       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8571       // bits, just truncate to i32.
8572       if (NumSignBits > OpBits-MidBits)
8573         return new TruncInst(Op, CI.getType(), "tmp");
8574     }
8575   }
8576
8577   // If the input is a shl/ashr pair of a same constant, then this is a sign
8578   // extension from a smaller value.  If we could trust arbitrary bitwidth
8579   // integers, we could turn this into a truncate to the smaller bit and then
8580   // use a sext for the whole extension.  Since we don't, look deeper and check
8581   // for a truncate.  If the source and dest are the same type, eliminate the
8582   // trunc and extend and just do shifts.  For example, turn:
8583   //   %a = trunc i32 %i to i8
8584   //   %b = shl i8 %a, 6
8585   //   %c = ashr i8 %b, 6
8586   //   %d = sext i8 %c to i32
8587   // into:
8588   //   %a = shl i32 %i, 30
8589   //   %d = ashr i32 %a, 30
8590   Value *A = 0;
8591   ConstantInt *BA = 0, *CA = 0;
8592   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8593                         m_ConstantInt(CA))) &&
8594       BA == CA && isa<TruncInst>(A)) {
8595     Value *I = cast<TruncInst>(A)->getOperand(0);
8596     if (I->getType() == CI.getType()) {
8597       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8598       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8599       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8600       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8601       I = Builder->CreateShl(I, ShAmtV, CI.getName());
8602       return BinaryOperator::CreateAShr(I, ShAmtV);
8603     }
8604   }
8605   
8606   return 0;
8607 }
8608
8609 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8610 /// in the specified FP type without changing its value.
8611 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8612                               LLVMContext *Context) {
8613   bool losesInfo;
8614   APFloat F = CFP->getValueAPF();
8615   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8616   if (!losesInfo)
8617     return ConstantFP::get(*Context, F);
8618   return 0;
8619 }
8620
8621 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8622 /// through it until we get the source value.
8623 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8624   if (Instruction *I = dyn_cast<Instruction>(V))
8625     if (I->getOpcode() == Instruction::FPExt)
8626       return LookThroughFPExtensions(I->getOperand(0), Context);
8627   
8628   // If this value is a constant, return the constant in the smallest FP type
8629   // that can accurately represent it.  This allows us to turn
8630   // (float)((double)X+2.0) into x+2.0f.
8631   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8632     if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
8633       return V;  // No constant folding of this.
8634     // See if the value can be truncated to float and then reextended.
8635     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8636       return V;
8637     if (CFP->getType() == Type::getDoubleTy(*Context))
8638       return V;  // Won't shrink.
8639     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8640       return V;
8641     // Don't try to shrink to various long double types.
8642   }
8643   
8644   return V;
8645 }
8646
8647 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8648   if (Instruction *I = commonCastTransforms(CI))
8649     return I;
8650   
8651   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8652   // smaller than the destination type, we can eliminate the truncate by doing
8653   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8654   // many builtins (sqrt, etc).
8655   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8656   if (OpI && OpI->hasOneUse()) {
8657     switch (OpI->getOpcode()) {
8658     default: break;
8659     case Instruction::FAdd:
8660     case Instruction::FSub:
8661     case Instruction::FMul:
8662     case Instruction::FDiv:
8663     case Instruction::FRem:
8664       const Type *SrcTy = OpI->getType();
8665       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8666       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8667       if (LHSTrunc->getType() != SrcTy && 
8668           RHSTrunc->getType() != SrcTy) {
8669         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8670         // If the source types were both smaller than the destination type of
8671         // the cast, do this xform.
8672         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8673             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8674           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8675                                       CI.getType(), CI);
8676           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8677                                       CI.getType(), CI);
8678           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8679         }
8680       }
8681       break;  
8682     }
8683   }
8684   return 0;
8685 }
8686
8687 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8688   return commonCastTransforms(CI);
8689 }
8690
8691 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8692   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8693   if (OpI == 0)
8694     return commonCastTransforms(FI);
8695
8696   // fptoui(uitofp(X)) --> X
8697   // fptoui(sitofp(X)) --> X
8698   // This is safe if the intermediate type has enough bits in its mantissa to
8699   // accurately represent all values of X.  For example, do not do this with
8700   // i64->float->i64.  This is also safe for sitofp case, because any negative
8701   // 'X' value would cause an undefined result for the fptoui. 
8702   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8703       OpI->getOperand(0)->getType() == FI.getType() &&
8704       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8705                     OpI->getType()->getFPMantissaWidth())
8706     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8707
8708   return commonCastTransforms(FI);
8709 }
8710
8711 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8712   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8713   if (OpI == 0)
8714     return commonCastTransforms(FI);
8715   
8716   // fptosi(sitofp(X)) --> X
8717   // fptosi(uitofp(X)) --> X
8718   // This is safe if the intermediate type has enough bits in its mantissa to
8719   // accurately represent all values of X.  For example, do not do this with
8720   // i64->float->i64.  This is also safe for sitofp case, because any negative
8721   // 'X' value would cause an undefined result for the fptoui. 
8722   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8723       OpI->getOperand(0)->getType() == FI.getType() &&
8724       (int)FI.getType()->getScalarSizeInBits() <=
8725                     OpI->getType()->getFPMantissaWidth())
8726     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8727   
8728   return commonCastTransforms(FI);
8729 }
8730
8731 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8732   return commonCastTransforms(CI);
8733 }
8734
8735 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8736   return commonCastTransforms(CI);
8737 }
8738
8739 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8740   // If the destination integer type is smaller than the intptr_t type for
8741   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8742   // trunc to be exposed to other transforms.  Don't do this for extending
8743   // ptrtoint's, because we don't know if the target sign or zero extends its
8744   // pointers.
8745   if (TD &&
8746       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8747     Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8748                                        TD->getIntPtrType(CI.getContext()),
8749                                        "tmp");
8750     return new TruncInst(P, CI.getType());
8751   }
8752   
8753   return commonPointerCastTransforms(CI);
8754 }
8755
8756 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8757   // If the source integer type is larger than the intptr_t type for
8758   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8759   // allows the trunc to be exposed to other transforms.  Don't do this for
8760   // extending inttoptr's, because we don't know if the target sign or zero
8761   // extends to pointers.
8762   if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
8763       TD->getPointerSizeInBits()) {
8764     Value *P = Builder->CreateTrunc(CI.getOperand(0),
8765                                     TD->getIntPtrType(CI.getContext()), "tmp");
8766     return new IntToPtrInst(P, CI.getType());
8767   }
8768   
8769   if (Instruction *I = commonCastTransforms(CI))
8770     return I;
8771
8772   return 0;
8773 }
8774
8775 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8776   // If the operands are integer typed then apply the integer transforms,
8777   // otherwise just apply the common ones.
8778   Value *Src = CI.getOperand(0);
8779   const Type *SrcTy = Src->getType();
8780   const Type *DestTy = CI.getType();
8781
8782   if (isa<PointerType>(SrcTy)) {
8783     if (Instruction *I = commonPointerCastTransforms(CI))
8784       return I;
8785   } else {
8786     if (Instruction *Result = commonCastTransforms(CI))
8787       return Result;
8788   }
8789
8790
8791   // Get rid of casts from one type to the same type. These are useless and can
8792   // be replaced by the operand.
8793   if (DestTy == Src->getType())
8794     return ReplaceInstUsesWith(CI, Src);
8795
8796   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8797     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8798     const Type *DstElTy = DstPTy->getElementType();
8799     const Type *SrcElTy = SrcPTy->getElementType();
8800     
8801     // If the address spaces don't match, don't eliminate the bitcast, which is
8802     // required for changing types.
8803     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8804       return 0;
8805     
8806     // If we are casting a malloc or alloca to a pointer to a type of the same
8807     // size, rewrite the allocation instruction to allocate the "right" type.
8808     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8809       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8810         return V;
8811     
8812     // If the source and destination are pointers, and this cast is equivalent
8813     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8814     // This can enhance SROA and other transforms that want type-safe pointers.
8815     Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
8816     unsigned NumZeros = 0;
8817     while (SrcElTy != DstElTy && 
8818            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8819            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8820       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8821       ++NumZeros;
8822     }
8823
8824     // If we found a path from the src to dest, create the getelementptr now.
8825     if (SrcElTy == DstElTy) {
8826       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8827       Instruction *GEP = GetElementPtrInst::Create(Src,
8828                                                    Idxs.begin(), Idxs.end(), "",
8829                                                    ((Instruction*) NULL));
8830       cast<GEPOperator>(GEP)->setIsInBounds(true);
8831       return GEP;
8832     }
8833   }
8834
8835   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8836     if (DestVTy->getNumElements() == 1) {
8837       if (!isa<VectorType>(SrcTy)) {
8838         Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
8839                                        DestVTy->getElementType(), CI);
8840         return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
8841                                          Constant::getNullValue(Type::getInt32Ty(*Context)));
8842       }
8843       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8844     }
8845   }
8846
8847   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8848     if (SrcVTy->getNumElements() == 1) {
8849       if (!isa<VectorType>(DestTy)) {
8850         Value *Elem = 
8851           Builder->CreateExtractElement(Src,
8852                             Constant::getNullValue(Type::getInt32Ty(*Context)));
8853         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8854       }
8855     }
8856   }
8857
8858   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8859     if (SVI->hasOneUse()) {
8860       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8861       // a bitconvert to a vector with the same # elts.
8862       if (isa<VectorType>(DestTy) && 
8863           cast<VectorType>(DestTy)->getNumElements() ==
8864                 SVI->getType()->getNumElements() &&
8865           SVI->getType()->getNumElements() ==
8866             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8867         CastInst *Tmp;
8868         // If either of the operands is a cast from CI.getType(), then
8869         // evaluating the shuffle in the casted destination's type will allow
8870         // us to eliminate at least one cast.
8871         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8872              Tmp->getOperand(0)->getType() == DestTy) ||
8873             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8874              Tmp->getOperand(0)->getType() == DestTy)) {
8875           Value *LHS = InsertCastBefore(Instruction::BitCast,
8876                                         SVI->getOperand(0), DestTy, CI);
8877           Value *RHS = InsertCastBefore(Instruction::BitCast,
8878                                         SVI->getOperand(1), DestTy, CI);
8879           // Return a new shuffle vector.  Use the same element ID's, as we
8880           // know the vector types match #elts.
8881           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8882         }
8883       }
8884     }
8885   }
8886   return 0;
8887 }
8888
8889 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8890 ///   %C = or %A, %B
8891 ///   %D = select %cond, %C, %A
8892 /// into:
8893 ///   %C = select %cond, %B, 0
8894 ///   %D = or %A, %C
8895 ///
8896 /// Assuming that the specified instruction is an operand to the select, return
8897 /// a bitmask indicating which operands of this instruction are foldable if they
8898 /// equal the other incoming value of the select.
8899 ///
8900 static unsigned GetSelectFoldableOperands(Instruction *I) {
8901   switch (I->getOpcode()) {
8902   case Instruction::Add:
8903   case Instruction::Mul:
8904   case Instruction::And:
8905   case Instruction::Or:
8906   case Instruction::Xor:
8907     return 3;              // Can fold through either operand.
8908   case Instruction::Sub:   // Can only fold on the amount subtracted.
8909   case Instruction::Shl:   // Can only fold on the shift amount.
8910   case Instruction::LShr:
8911   case Instruction::AShr:
8912     return 1;
8913   default:
8914     return 0;              // Cannot fold
8915   }
8916 }
8917
8918 /// GetSelectFoldableConstant - For the same transformation as the previous
8919 /// function, return the identity constant that goes into the select.
8920 static Constant *GetSelectFoldableConstant(Instruction *I,
8921                                            LLVMContext *Context) {
8922   switch (I->getOpcode()) {
8923   default: llvm_unreachable("This cannot happen!");
8924   case Instruction::Add:
8925   case Instruction::Sub:
8926   case Instruction::Or:
8927   case Instruction::Xor:
8928   case Instruction::Shl:
8929   case Instruction::LShr:
8930   case Instruction::AShr:
8931     return Constant::getNullValue(I->getType());
8932   case Instruction::And:
8933     return Constant::getAllOnesValue(I->getType());
8934   case Instruction::Mul:
8935     return ConstantInt::get(I->getType(), 1);
8936   }
8937 }
8938
8939 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8940 /// have the same opcode and only one use each.  Try to simplify this.
8941 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8942                                           Instruction *FI) {
8943   if (TI->getNumOperands() == 1) {
8944     // If this is a non-volatile load or a cast from the same type,
8945     // merge.
8946     if (TI->isCast()) {
8947       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8948         return 0;
8949     } else {
8950       return 0;  // unknown unary op.
8951     }
8952
8953     // Fold this by inserting a select from the input values.
8954     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8955                                           FI->getOperand(0), SI.getName()+".v");
8956     InsertNewInstBefore(NewSI, SI);
8957     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8958                             TI->getType());
8959   }
8960
8961   // Only handle binary operators here.
8962   if (!isa<BinaryOperator>(TI))
8963     return 0;
8964
8965   // Figure out if the operations have any operands in common.
8966   Value *MatchOp, *OtherOpT, *OtherOpF;
8967   bool MatchIsOpZero;
8968   if (TI->getOperand(0) == FI->getOperand(0)) {
8969     MatchOp  = TI->getOperand(0);
8970     OtherOpT = TI->getOperand(1);
8971     OtherOpF = FI->getOperand(1);
8972     MatchIsOpZero = true;
8973   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8974     MatchOp  = TI->getOperand(1);
8975     OtherOpT = TI->getOperand(0);
8976     OtherOpF = FI->getOperand(0);
8977     MatchIsOpZero = false;
8978   } else if (!TI->isCommutative()) {
8979     return 0;
8980   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8981     MatchOp  = TI->getOperand(0);
8982     OtherOpT = TI->getOperand(1);
8983     OtherOpF = FI->getOperand(0);
8984     MatchIsOpZero = true;
8985   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8986     MatchOp  = TI->getOperand(1);
8987     OtherOpT = TI->getOperand(0);
8988     OtherOpF = FI->getOperand(1);
8989     MatchIsOpZero = true;
8990   } else {
8991     return 0;
8992   }
8993
8994   // If we reach here, they do have operations in common.
8995   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8996                                          OtherOpF, SI.getName()+".v");
8997   InsertNewInstBefore(NewSI, SI);
8998
8999   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9000     if (MatchIsOpZero)
9001       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9002     else
9003       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9004   }
9005   llvm_unreachable("Shouldn't get here");
9006   return 0;
9007 }
9008
9009 static bool isSelect01(Constant *C1, Constant *C2) {
9010   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9011   if (!C1I)
9012     return false;
9013   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9014   if (!C2I)
9015     return false;
9016   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9017 }
9018
9019 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9020 /// facilitate further optimization.
9021 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9022                                             Value *FalseVal) {
9023   // See the comment above GetSelectFoldableOperands for a description of the
9024   // transformation we are doing here.
9025   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9026     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9027         !isa<Constant>(FalseVal)) {
9028       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9029         unsigned OpToFold = 0;
9030         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9031           OpToFold = 1;
9032         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9033           OpToFold = 2;
9034         }
9035
9036         if (OpToFold) {
9037           Constant *C = GetSelectFoldableConstant(TVI, Context);
9038           Value *OOp = TVI->getOperand(2-OpToFold);
9039           // Avoid creating select between 2 constants unless it's selecting
9040           // between 0 and 1.
9041           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9042             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9043             InsertNewInstBefore(NewSel, SI);
9044             NewSel->takeName(TVI);
9045             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9046               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9047             llvm_unreachable("Unknown instruction!!");
9048           }
9049         }
9050       }
9051     }
9052   }
9053
9054   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9055     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9056         !isa<Constant>(TrueVal)) {
9057       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9058         unsigned OpToFold = 0;
9059         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9060           OpToFold = 1;
9061         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9062           OpToFold = 2;
9063         }
9064
9065         if (OpToFold) {
9066           Constant *C = GetSelectFoldableConstant(FVI, Context);
9067           Value *OOp = FVI->getOperand(2-OpToFold);
9068           // Avoid creating select between 2 constants unless it's selecting
9069           // between 0 and 1.
9070           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9071             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9072             InsertNewInstBefore(NewSel, SI);
9073             NewSel->takeName(FVI);
9074             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9075               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9076             llvm_unreachable("Unknown instruction!!");
9077           }
9078         }
9079       }
9080     }
9081   }
9082
9083   return 0;
9084 }
9085
9086 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9087 /// ICmpInst as its first operand.
9088 ///
9089 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9090                                                    ICmpInst *ICI) {
9091   bool Changed = false;
9092   ICmpInst::Predicate Pred = ICI->getPredicate();
9093   Value *CmpLHS = ICI->getOperand(0);
9094   Value *CmpRHS = ICI->getOperand(1);
9095   Value *TrueVal = SI.getTrueValue();
9096   Value *FalseVal = SI.getFalseValue();
9097
9098   // Check cases where the comparison is with a constant that
9099   // can be adjusted to fit the min/max idiom. We may edit ICI in
9100   // place here, so make sure the select is the only user.
9101   if (ICI->hasOneUse())
9102     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9103       switch (Pred) {
9104       default: break;
9105       case ICmpInst::ICMP_ULT:
9106       case ICmpInst::ICMP_SLT: {
9107         // X < MIN ? T : F  -->  F
9108         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9109           return ReplaceInstUsesWith(SI, FalseVal);
9110         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9111         Constant *AdjustedRHS = SubOne(CI);
9112         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9113             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9114           Pred = ICmpInst::getSwappedPredicate(Pred);
9115           CmpRHS = AdjustedRHS;
9116           std::swap(FalseVal, TrueVal);
9117           ICI->setPredicate(Pred);
9118           ICI->setOperand(1, CmpRHS);
9119           SI.setOperand(1, TrueVal);
9120           SI.setOperand(2, FalseVal);
9121           Changed = true;
9122         }
9123         break;
9124       }
9125       case ICmpInst::ICMP_UGT:
9126       case ICmpInst::ICMP_SGT: {
9127         // X > MAX ? T : F  -->  F
9128         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9129           return ReplaceInstUsesWith(SI, FalseVal);
9130         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9131         Constant *AdjustedRHS = AddOne(CI);
9132         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9133             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9134           Pred = ICmpInst::getSwappedPredicate(Pred);
9135           CmpRHS = AdjustedRHS;
9136           std::swap(FalseVal, TrueVal);
9137           ICI->setPredicate(Pred);
9138           ICI->setOperand(1, CmpRHS);
9139           SI.setOperand(1, TrueVal);
9140           SI.setOperand(2, FalseVal);
9141           Changed = true;
9142         }
9143         break;
9144       }
9145       }
9146
9147       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9148       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9149       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9150       if (match(TrueVal, m_ConstantInt<-1>()) &&
9151           match(FalseVal, m_ConstantInt<0>()))
9152         Pred = ICI->getPredicate();
9153       else if (match(TrueVal, m_ConstantInt<0>()) &&
9154                match(FalseVal, m_ConstantInt<-1>()))
9155         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9156       
9157       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9158         // If we are just checking for a icmp eq of a single bit and zext'ing it
9159         // to an integer, then shift the bit to the appropriate place and then
9160         // cast to integer to avoid the comparison.
9161         const APInt &Op1CV = CI->getValue();
9162     
9163         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9164         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9165         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9166             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9167           Value *In = ICI->getOperand(0);
9168           Value *Sh = ConstantInt::get(In->getType(),
9169                                        In->getType()->getScalarSizeInBits()-1);
9170           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9171                                                         In->getName()+".lobit"),
9172                                    *ICI);
9173           if (In->getType() != SI.getType())
9174             In = CastInst::CreateIntegerCast(In, SI.getType(),
9175                                              true/*SExt*/, "tmp", ICI);
9176     
9177           if (Pred == ICmpInst::ICMP_SGT)
9178             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9179                                        In->getName()+".not"), *ICI);
9180     
9181           return ReplaceInstUsesWith(SI, In);
9182         }
9183       }
9184     }
9185
9186   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9187     // Transform (X == Y) ? X : Y  -> Y
9188     if (Pred == ICmpInst::ICMP_EQ)
9189       return ReplaceInstUsesWith(SI, FalseVal);
9190     // Transform (X != Y) ? X : Y  -> X
9191     if (Pred == ICmpInst::ICMP_NE)
9192       return ReplaceInstUsesWith(SI, TrueVal);
9193     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9194
9195   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9196     // Transform (X == Y) ? Y : X  -> X
9197     if (Pred == ICmpInst::ICMP_EQ)
9198       return ReplaceInstUsesWith(SI, FalseVal);
9199     // Transform (X != Y) ? Y : X  -> Y
9200     if (Pred == ICmpInst::ICMP_NE)
9201       return ReplaceInstUsesWith(SI, TrueVal);
9202     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9203   }
9204
9205   /// NOTE: if we wanted to, this is where to detect integer ABS
9206
9207   return Changed ? &SI : 0;
9208 }
9209
9210 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9211   Value *CondVal = SI.getCondition();
9212   Value *TrueVal = SI.getTrueValue();
9213   Value *FalseVal = SI.getFalseValue();
9214
9215   // select true, X, Y  -> X
9216   // select false, X, Y -> Y
9217   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9218     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9219
9220   // select C, X, X -> X
9221   if (TrueVal == FalseVal)
9222     return ReplaceInstUsesWith(SI, TrueVal);
9223
9224   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9225     return ReplaceInstUsesWith(SI, FalseVal);
9226   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9227     return ReplaceInstUsesWith(SI, TrueVal);
9228   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9229     if (isa<Constant>(TrueVal))
9230       return ReplaceInstUsesWith(SI, TrueVal);
9231     else
9232       return ReplaceInstUsesWith(SI, FalseVal);
9233   }
9234
9235   if (SI.getType() == Type::getInt1Ty(*Context)) {
9236     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9237       if (C->getZExtValue()) {
9238         // Change: A = select B, true, C --> A = or B, C
9239         return BinaryOperator::CreateOr(CondVal, FalseVal);
9240       } else {
9241         // Change: A = select B, false, C --> A = and !B, C
9242         Value *NotCond =
9243           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9244                                              "not."+CondVal->getName()), SI);
9245         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9246       }
9247     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9248       if (C->getZExtValue() == false) {
9249         // Change: A = select B, C, false --> A = and B, C
9250         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9251       } else {
9252         // Change: A = select B, C, true --> A = or !B, C
9253         Value *NotCond =
9254           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9255                                              "not."+CondVal->getName()), SI);
9256         return BinaryOperator::CreateOr(NotCond, TrueVal);
9257       }
9258     }
9259     
9260     // select a, b, a  -> a&b
9261     // select a, a, b  -> a|b
9262     if (CondVal == TrueVal)
9263       return BinaryOperator::CreateOr(CondVal, FalseVal);
9264     else if (CondVal == FalseVal)
9265       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9266   }
9267
9268   // Selecting between two integer constants?
9269   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9270     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9271       // select C, 1, 0 -> zext C to int
9272       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9273         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9274       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9275         // select C, 0, 1 -> zext !C to int
9276         Value *NotCond =
9277           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9278                                                "not."+CondVal->getName()), SI);
9279         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9280       }
9281
9282       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9283         // If one of the constants is zero (we know they can't both be) and we
9284         // have an icmp instruction with zero, and we have an 'and' with the
9285         // non-constant value, eliminate this whole mess.  This corresponds to
9286         // cases like this: ((X & 27) ? 27 : 0)
9287         if (TrueValC->isZero() || FalseValC->isZero())
9288           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9289               cast<Constant>(IC->getOperand(1))->isNullValue())
9290             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9291               if (ICA->getOpcode() == Instruction::And &&
9292                   isa<ConstantInt>(ICA->getOperand(1)) &&
9293                   (ICA->getOperand(1) == TrueValC ||
9294                    ICA->getOperand(1) == FalseValC) &&
9295                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9296                 // Okay, now we know that everything is set up, we just don't
9297                 // know whether we have a icmp_ne or icmp_eq and whether the 
9298                 // true or false val is the zero.
9299                 bool ShouldNotVal = !TrueValC->isZero();
9300                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9301                 Value *V = ICA;
9302                 if (ShouldNotVal)
9303                   V = InsertNewInstBefore(BinaryOperator::Create(
9304                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9305                 return ReplaceInstUsesWith(SI, V);
9306               }
9307       }
9308     }
9309
9310   // See if we are selecting two values based on a comparison of the two values.
9311   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9312     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9313       // Transform (X == Y) ? X : Y  -> Y
9314       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9315         // This is not safe in general for floating point:  
9316         // consider X== -0, Y== +0.
9317         // It becomes safe if either operand is a nonzero constant.
9318         ConstantFP *CFPt, *CFPf;
9319         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9320               !CFPt->getValueAPF().isZero()) ||
9321             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9322              !CFPf->getValueAPF().isZero()))
9323         return ReplaceInstUsesWith(SI, FalseVal);
9324       }
9325       // Transform (X != Y) ? X : Y  -> X
9326       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9327         return ReplaceInstUsesWith(SI, TrueVal);
9328       // NOTE: if we wanted to, this is where to detect MIN/MAX
9329
9330     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9331       // Transform (X == Y) ? Y : X  -> X
9332       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9333         // This is not safe in general for floating point:  
9334         // consider X== -0, Y== +0.
9335         // It becomes safe if either operand is a nonzero constant.
9336         ConstantFP *CFPt, *CFPf;
9337         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9338               !CFPt->getValueAPF().isZero()) ||
9339             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9340              !CFPf->getValueAPF().isZero()))
9341           return ReplaceInstUsesWith(SI, FalseVal);
9342       }
9343       // Transform (X != Y) ? Y : X  -> Y
9344       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9345         return ReplaceInstUsesWith(SI, TrueVal);
9346       // NOTE: if we wanted to, this is where to detect MIN/MAX
9347     }
9348     // NOTE: if we wanted to, this is where to detect ABS
9349   }
9350
9351   // See if we are selecting two values based on a comparison of the two values.
9352   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9353     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9354       return Result;
9355
9356   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9357     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9358       if (TI->hasOneUse() && FI->hasOneUse()) {
9359         Instruction *AddOp = 0, *SubOp = 0;
9360
9361         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9362         if (TI->getOpcode() == FI->getOpcode())
9363           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9364             return IV;
9365
9366         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9367         // even legal for FP.
9368         if ((TI->getOpcode() == Instruction::Sub &&
9369              FI->getOpcode() == Instruction::Add) ||
9370             (TI->getOpcode() == Instruction::FSub &&
9371              FI->getOpcode() == Instruction::FAdd)) {
9372           AddOp = FI; SubOp = TI;
9373         } else if ((FI->getOpcode() == Instruction::Sub &&
9374                     TI->getOpcode() == Instruction::Add) ||
9375                    (FI->getOpcode() == Instruction::FSub &&
9376                     TI->getOpcode() == Instruction::FAdd)) {
9377           AddOp = TI; SubOp = FI;
9378         }
9379
9380         if (AddOp) {
9381           Value *OtherAddOp = 0;
9382           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9383             OtherAddOp = AddOp->getOperand(1);
9384           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9385             OtherAddOp = AddOp->getOperand(0);
9386           }
9387
9388           if (OtherAddOp) {
9389             // So at this point we know we have (Y -> OtherAddOp):
9390             //        select C, (add X, Y), (sub X, Z)
9391             Value *NegVal;  // Compute -Z
9392             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9393               NegVal = ConstantExpr::getNeg(C);
9394             } else {
9395               NegVal = InsertNewInstBefore(
9396                     BinaryOperator::CreateNeg(SubOp->getOperand(1),
9397                                               "tmp"), SI);
9398             }
9399
9400             Value *NewTrueOp = OtherAddOp;
9401             Value *NewFalseOp = NegVal;
9402             if (AddOp != TI)
9403               std::swap(NewTrueOp, NewFalseOp);
9404             Instruction *NewSel =
9405               SelectInst::Create(CondVal, NewTrueOp,
9406                                  NewFalseOp, SI.getName() + ".p");
9407
9408             NewSel = InsertNewInstBefore(NewSel, SI);
9409             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9410           }
9411         }
9412       }
9413
9414   // See if we can fold the select into one of our operands.
9415   if (SI.getType()->isInteger()) {
9416     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9417     if (FoldI)
9418       return FoldI;
9419   }
9420
9421   if (BinaryOperator::isNot(CondVal)) {
9422     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9423     SI.setOperand(1, FalseVal);
9424     SI.setOperand(2, TrueVal);
9425     return &SI;
9426   }
9427
9428   return 0;
9429 }
9430
9431 /// EnforceKnownAlignment - If the specified pointer points to an object that
9432 /// we control, modify the object's alignment to PrefAlign. This isn't
9433 /// often possible though. If alignment is important, a more reliable approach
9434 /// is to simply align all global variables and allocation instructions to
9435 /// their preferred alignment from the beginning.
9436 ///
9437 static unsigned EnforceKnownAlignment(Value *V,
9438                                       unsigned Align, unsigned PrefAlign) {
9439
9440   User *U = dyn_cast<User>(V);
9441   if (!U) return Align;
9442
9443   switch (Operator::getOpcode(U)) {
9444   default: break;
9445   case Instruction::BitCast:
9446     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9447   case Instruction::GetElementPtr: {
9448     // If all indexes are zero, it is just the alignment of the base pointer.
9449     bool AllZeroOperands = true;
9450     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9451       if (!isa<Constant>(*i) ||
9452           !cast<Constant>(*i)->isNullValue()) {
9453         AllZeroOperands = false;
9454         break;
9455       }
9456
9457     if (AllZeroOperands) {
9458       // Treat this like a bitcast.
9459       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9460     }
9461     break;
9462   }
9463   }
9464
9465   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9466     // If there is a large requested alignment and we can, bump up the alignment
9467     // of the global.
9468     if (!GV->isDeclaration()) {
9469       if (GV->getAlignment() >= PrefAlign)
9470         Align = GV->getAlignment();
9471       else {
9472         GV->setAlignment(PrefAlign);
9473         Align = PrefAlign;
9474       }
9475     }
9476   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9477     // If there is a requested alignment and if this is an alloca, round up.  We
9478     // don't do this for malloc, because some systems can't respect the request.
9479     if (isa<AllocaInst>(AI)) {
9480       if (AI->getAlignment() >= PrefAlign)
9481         Align = AI->getAlignment();
9482       else {
9483         AI->setAlignment(PrefAlign);
9484         Align = PrefAlign;
9485       }
9486     }
9487   }
9488
9489   return Align;
9490 }
9491
9492 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9493 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9494 /// and it is more than the alignment of the ultimate object, see if we can
9495 /// increase the alignment of the ultimate object, making this check succeed.
9496 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9497                                                   unsigned PrefAlign) {
9498   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9499                       sizeof(PrefAlign) * CHAR_BIT;
9500   APInt Mask = APInt::getAllOnesValue(BitWidth);
9501   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9502   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9503   unsigned TrailZ = KnownZero.countTrailingOnes();
9504   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9505
9506   if (PrefAlign > Align)
9507     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9508   
9509     // We don't need to make any adjustment.
9510   return Align;
9511 }
9512
9513 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9514   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9515   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9516   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9517   unsigned CopyAlign = MI->getAlignment();
9518
9519   if (CopyAlign < MinAlign) {
9520     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 
9521                                              MinAlign, false));
9522     return MI;
9523   }
9524   
9525   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9526   // load/store.
9527   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9528   if (MemOpLength == 0) return 0;
9529   
9530   // Source and destination pointer types are always "i8*" for intrinsic.  See
9531   // if the size is something we can handle with a single primitive load/store.
9532   // A single load+store correctly handles overlapping memory in the memmove
9533   // case.
9534   unsigned Size = MemOpLength->getZExtValue();
9535   if (Size == 0) return MI;  // Delete this mem transfer.
9536   
9537   if (Size > 8 || (Size&(Size-1)))
9538     return 0;  // If not 1/2/4/8 bytes, exit.
9539   
9540   // Use an integer load+store unless we can find something better.
9541   Type *NewPtrTy =
9542                 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
9543   
9544   // Memcpy forces the use of i8* for the source and destination.  That means
9545   // that if you're using memcpy to move one double around, you'll get a cast
9546   // from double* to i8*.  We'd much rather use a double load+store rather than
9547   // an i64 load+store, here because this improves the odds that the source or
9548   // dest address will be promotable.  See if we can find a better type than the
9549   // integer datatype.
9550   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9551     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9552     if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9553       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9554       // down through these levels if so.
9555       while (!SrcETy->isSingleValueType()) {
9556         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9557           if (STy->getNumElements() == 1)
9558             SrcETy = STy->getElementType(0);
9559           else
9560             break;
9561         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9562           if (ATy->getNumElements() == 1)
9563             SrcETy = ATy->getElementType();
9564           else
9565             break;
9566         } else
9567           break;
9568       }
9569       
9570       if (SrcETy->isSingleValueType())
9571         NewPtrTy = PointerType::getUnqual(SrcETy);
9572     }
9573   }
9574   
9575   
9576   // If the memcpy/memmove provides better alignment info than we can
9577   // infer, use it.
9578   SrcAlign = std::max(SrcAlign, CopyAlign);
9579   DstAlign = std::max(DstAlign, CopyAlign);
9580   
9581   Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9582   Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
9583   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9584   InsertNewInstBefore(L, *MI);
9585   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9586
9587   // Set the size of the copy to 0, it will be deleted on the next iteration.
9588   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9589   return MI;
9590 }
9591
9592 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9593   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9594   if (MI->getAlignment() < Alignment) {
9595     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9596                                              Alignment, false));
9597     return MI;
9598   }
9599   
9600   // Extract the length and alignment and fill if they are constant.
9601   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9602   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9603   if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
9604     return 0;
9605   uint64_t Len = LenC->getZExtValue();
9606   Alignment = MI->getAlignment();
9607   
9608   // If the length is zero, this is a no-op
9609   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9610   
9611   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9612   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9613     const Type *ITy = IntegerType::get(*Context, Len*8);  // n=1 -> i8.
9614     
9615     Value *Dest = MI->getDest();
9616     Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
9617
9618     // Alignment 0 is identity for alignment 1 for memset, but not store.
9619     if (Alignment == 0) Alignment = 1;
9620     
9621     // Extract the fill value and store.
9622     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9623     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9624                                       Dest, false, Alignment), *MI);
9625     
9626     // Set the size of the copy to 0, it will be deleted on the next iteration.
9627     MI->setLength(Constant::getNullValue(LenC->getType()));
9628     return MI;
9629   }
9630
9631   return 0;
9632 }
9633
9634
9635 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9636 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9637 /// the heavy lifting.
9638 ///
9639 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9640   // If the caller function is nounwind, mark the call as nounwind, even if the
9641   // callee isn't.
9642   if (CI.getParent()->getParent()->doesNotThrow() &&
9643       !CI.doesNotThrow()) {
9644     CI.setDoesNotThrow();
9645     return &CI;
9646   }
9647   
9648   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9649   if (!II) return visitCallSite(&CI);
9650   
9651   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9652   // visitCallSite.
9653   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9654     bool Changed = false;
9655
9656     // memmove/cpy/set of zero bytes is a noop.
9657     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9658       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9659
9660       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9661         if (CI->getZExtValue() == 1) {
9662           // Replace the instruction with just byte operations.  We would
9663           // transform other cases to loads/stores, but we don't know if
9664           // alignment is sufficient.
9665         }
9666     }
9667
9668     // If we have a memmove and the source operation is a constant global,
9669     // then the source and dest pointers can't alias, so we can change this
9670     // into a call to memcpy.
9671     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9672       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9673         if (GVSrc->isConstant()) {
9674           Module *M = CI.getParent()->getParent()->getParent();
9675           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9676           const Type *Tys[1];
9677           Tys[0] = CI.getOperand(3)->getType();
9678           CI.setOperand(0, 
9679                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9680           Changed = true;
9681         }
9682
9683       // memmove(x,x,size) -> noop.
9684       if (MMI->getSource() == MMI->getDest())
9685         return EraseInstFromFunction(CI);
9686     }
9687
9688     // If we can determine a pointer alignment that is bigger than currently
9689     // set, update the alignment.
9690     if (isa<MemTransferInst>(MI)) {
9691       if (Instruction *I = SimplifyMemTransfer(MI))
9692         return I;
9693     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9694       if (Instruction *I = SimplifyMemSet(MSI))
9695         return I;
9696     }
9697           
9698     if (Changed) return II;
9699   }
9700   
9701   switch (II->getIntrinsicID()) {
9702   default: break;
9703   case Intrinsic::bswap:
9704     // bswap(bswap(x)) -> x
9705     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9706       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9707         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9708     break;
9709   case Intrinsic::ppc_altivec_lvx:
9710   case Intrinsic::ppc_altivec_lvxl:
9711   case Intrinsic::x86_sse_loadu_ps:
9712   case Intrinsic::x86_sse2_loadu_pd:
9713   case Intrinsic::x86_sse2_loadu_dq:
9714     // Turn PPC lvx     -> load if the pointer is known aligned.
9715     // Turn X86 loadups -> load if the pointer is known aligned.
9716     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9717       Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9718                                          PointerType::getUnqual(II->getType()));
9719       return new LoadInst(Ptr);
9720     }
9721     break;
9722   case Intrinsic::ppc_altivec_stvx:
9723   case Intrinsic::ppc_altivec_stvxl:
9724     // Turn stvx -> store if the pointer is known aligned.
9725     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9726       const Type *OpPtrTy = 
9727         PointerType::getUnqual(II->getOperand(1)->getType());
9728       Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
9729       return new StoreInst(II->getOperand(1), Ptr);
9730     }
9731     break;
9732   case Intrinsic::x86_sse_storeu_ps:
9733   case Intrinsic::x86_sse2_storeu_pd:
9734   case Intrinsic::x86_sse2_storeu_dq:
9735     // Turn X86 storeu -> store if the pointer is known aligned.
9736     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9737       const Type *OpPtrTy = 
9738         PointerType::getUnqual(II->getOperand(2)->getType());
9739       Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
9740       return new StoreInst(II->getOperand(2), Ptr);
9741     }
9742     break;
9743     
9744   case Intrinsic::x86_sse_cvttss2si: {
9745     // These intrinsics only demands the 0th element of its input vector.  If
9746     // we can simplify the input based on that, do so now.
9747     unsigned VWidth =
9748       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9749     APInt DemandedElts(VWidth, 1);
9750     APInt UndefElts(VWidth, 0);
9751     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9752                                               UndefElts)) {
9753       II->setOperand(1, V);
9754       return II;
9755     }
9756     break;
9757   }
9758     
9759   case Intrinsic::ppc_altivec_vperm:
9760     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9761     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9762       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9763       
9764       // Check that all of the elements are integer constants or undefs.
9765       bool AllEltsOk = true;
9766       for (unsigned i = 0; i != 16; ++i) {
9767         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9768             !isa<UndefValue>(Mask->getOperand(i))) {
9769           AllEltsOk = false;
9770           break;
9771         }
9772       }
9773       
9774       if (AllEltsOk) {
9775         // Cast the input vectors to byte vectors.
9776         Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9777         Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
9778         Value *Result = UndefValue::get(Op0->getType());
9779         
9780         // Only extract each element once.
9781         Value *ExtractedElts[32];
9782         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9783         
9784         for (unsigned i = 0; i != 16; ++i) {
9785           if (isa<UndefValue>(Mask->getOperand(i)))
9786             continue;
9787           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9788           Idx &= 31;  // Match the hardware behavior.
9789           
9790           if (ExtractedElts[Idx] == 0) {
9791             ExtractedElts[Idx] = 
9792               Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1, 
9793                   ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9794                                             "tmp");
9795           }
9796         
9797           // Insert this value into the result vector.
9798           Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9799                          ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9800                                                 "tmp");
9801         }
9802         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9803       }
9804     }
9805     break;
9806
9807   case Intrinsic::stackrestore: {
9808     // If the save is right next to the restore, remove the restore.  This can
9809     // happen when variable allocas are DCE'd.
9810     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9811       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9812         BasicBlock::iterator BI = SS;
9813         if (&*++BI == II)
9814           return EraseInstFromFunction(CI);
9815       }
9816     }
9817     
9818     // Scan down this block to see if there is another stack restore in the
9819     // same block without an intervening call/alloca.
9820     BasicBlock::iterator BI = II;
9821     TerminatorInst *TI = II->getParent()->getTerminator();
9822     bool CannotRemove = false;
9823     for (++BI; &*BI != TI; ++BI) {
9824       if (isa<AllocaInst>(BI)) {
9825         CannotRemove = true;
9826         break;
9827       }
9828       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9829         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9830           // If there is a stackrestore below this one, remove this one.
9831           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9832             return EraseInstFromFunction(CI);
9833           // Otherwise, ignore the intrinsic.
9834         } else {
9835           // If we found a non-intrinsic call, we can't remove the stack
9836           // restore.
9837           CannotRemove = true;
9838           break;
9839         }
9840       }
9841     }
9842     
9843     // If the stack restore is in a return/unwind block and if there are no
9844     // allocas or calls between the restore and the return, nuke the restore.
9845     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9846       return EraseInstFromFunction(CI);
9847     break;
9848   }
9849   }
9850
9851   return visitCallSite(II);
9852 }
9853
9854 // InvokeInst simplification
9855 //
9856 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9857   return visitCallSite(&II);
9858 }
9859
9860 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9861 /// passed through the varargs area, we can eliminate the use of the cast.
9862 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9863                                          const CastInst * const CI,
9864                                          const TargetData * const TD,
9865                                          const int ix) {
9866   if (!CI->isLosslessCast())
9867     return false;
9868
9869   // The size of ByVal arguments is derived from the type, so we
9870   // can't change to a type with a different size.  If the size were
9871   // passed explicitly we could avoid this check.
9872   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9873     return true;
9874
9875   const Type* SrcTy = 
9876             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9877   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9878   if (!SrcTy->isSized() || !DstTy->isSized())
9879     return false;
9880   if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
9881     return false;
9882   return true;
9883 }
9884
9885 // visitCallSite - Improvements for call and invoke instructions.
9886 //
9887 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9888   bool Changed = false;
9889
9890   // If the callee is a constexpr cast of a function, attempt to move the cast
9891   // to the arguments of the call/invoke.
9892   if (transformConstExprCastCall(CS)) return 0;
9893
9894   Value *Callee = CS.getCalledValue();
9895
9896   if (Function *CalleeF = dyn_cast<Function>(Callee))
9897     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9898       Instruction *OldCall = CS.getInstruction();
9899       // If the call and callee calling conventions don't match, this call must
9900       // be unreachable, as the call is undefined.
9901       new StoreInst(ConstantInt::getTrue(*Context),
9902                 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), 
9903                                   OldCall);
9904       if (!OldCall->use_empty())
9905         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9906       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
9907         return EraseInstFromFunction(*OldCall);
9908       return 0;
9909     }
9910
9911   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9912     // This instruction is not reachable, just remove it.  We insert a store to
9913     // undef so that we know that this code is not reachable, despite the fact
9914     // that we can't modify the CFG here.
9915     new StoreInst(ConstantInt::getTrue(*Context),
9916                UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
9917                   CS.getInstruction());
9918
9919     if (!CS.getInstruction()->use_empty())
9920       CS.getInstruction()->
9921         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9922
9923     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9924       // Don't break the CFG, insert a dummy cond branch.
9925       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9926                          ConstantInt::getTrue(*Context), II);
9927     }
9928     return EraseInstFromFunction(*CS.getInstruction());
9929   }
9930
9931   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9932     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9933       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9934         return transformCallThroughTrampoline(CS);
9935
9936   const PointerType *PTy = cast<PointerType>(Callee->getType());
9937   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9938   if (FTy->isVarArg()) {
9939     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9940     // See if we can optimize any arguments passed through the varargs area of
9941     // the call.
9942     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9943            E = CS.arg_end(); I != E; ++I, ++ix) {
9944       CastInst *CI = dyn_cast<CastInst>(*I);
9945       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9946         *I = CI->getOperand(0);
9947         Changed = true;
9948       }
9949     }
9950   }
9951
9952   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9953     // Inline asm calls cannot throw - mark them 'nounwind'.
9954     CS.setDoesNotThrow();
9955     Changed = true;
9956   }
9957
9958   return Changed ? CS.getInstruction() : 0;
9959 }
9960
9961 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9962 // attempt to move the cast to the arguments of the call/invoke.
9963 //
9964 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9965   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9966   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9967   if (CE->getOpcode() != Instruction::BitCast || 
9968       !isa<Function>(CE->getOperand(0)))
9969     return false;
9970   Function *Callee = cast<Function>(CE->getOperand(0));
9971   Instruction *Caller = CS.getInstruction();
9972   const AttrListPtr &CallerPAL = CS.getAttributes();
9973
9974   // Okay, this is a cast from a function to a different type.  Unless doing so
9975   // would cause a type conversion of one of our arguments, change this call to
9976   // be a direct call with arguments casted to the appropriate types.
9977   //
9978   const FunctionType *FT = Callee->getFunctionType();
9979   const Type *OldRetTy = Caller->getType();
9980   const Type *NewRetTy = FT->getReturnType();
9981
9982   if (isa<StructType>(NewRetTy))
9983     return false; // TODO: Handle multiple return values.
9984
9985   // Check to see if we are changing the return type...
9986   if (OldRetTy != NewRetTy) {
9987     if (Callee->isDeclaration() &&
9988         // Conversion is ok if changing from one pointer type to another or from
9989         // a pointer to an integer of the same size.
9990         !((isa<PointerType>(OldRetTy) || !TD ||
9991            OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
9992           (isa<PointerType>(NewRetTy) || !TD ||
9993            NewRetTy == TD->getIntPtrType(Caller->getContext()))))
9994       return false;   // Cannot transform this return value.
9995
9996     if (!Caller->use_empty() &&
9997         // void -> non-void is handled specially
9998         NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
9999       return false;   // Cannot transform this return value.
10000
10001     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10002       Attributes RAttrs = CallerPAL.getRetAttributes();
10003       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10004         return false;   // Attribute not compatible with transformed value.
10005     }
10006
10007     // If the callsite is an invoke instruction, and the return value is used by
10008     // a PHI node in a successor, we cannot change the return type of the call
10009     // because there is no place to put the cast instruction (without breaking
10010     // the critical edge).  Bail out in this case.
10011     if (!Caller->use_empty())
10012       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10013         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10014              UI != E; ++UI)
10015           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10016             if (PN->getParent() == II->getNormalDest() ||
10017                 PN->getParent() == II->getUnwindDest())
10018               return false;
10019   }
10020
10021   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10022   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10023
10024   CallSite::arg_iterator AI = CS.arg_begin();
10025   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10026     const Type *ParamTy = FT->getParamType(i);
10027     const Type *ActTy = (*AI)->getType();
10028
10029     if (!CastInst::isCastable(ActTy, ParamTy))
10030       return false;   // Cannot transform this parameter value.
10031
10032     if (CallerPAL.getParamAttributes(i + 1) 
10033         & Attribute::typeIncompatible(ParamTy))
10034       return false;   // Attribute not compatible with transformed value.
10035
10036     // Converting from one pointer type to another or between a pointer and an
10037     // integer of the same size is safe even if we do not have a body.
10038     bool isConvertible = ActTy == ParamTy ||
10039       (TD && ((isa<PointerType>(ParamTy) ||
10040       ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10041               (isa<PointerType>(ActTy) ||
10042               ActTy == TD->getIntPtrType(Caller->getContext()))));
10043     if (Callee->isDeclaration() && !isConvertible) return false;
10044   }
10045
10046   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10047       Callee->isDeclaration())
10048     return false;   // Do not delete arguments unless we have a function body.
10049
10050   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10051       !CallerPAL.isEmpty())
10052     // In this case we have more arguments than the new function type, but we
10053     // won't be dropping them.  Check that these extra arguments have attributes
10054     // that are compatible with being a vararg call argument.
10055     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10056       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10057         break;
10058       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10059       if (PAttrs & Attribute::VarArgsIncompatible)
10060         return false;
10061     }
10062
10063   // Okay, we decided that this is a safe thing to do: go ahead and start
10064   // inserting cast instructions as necessary...
10065   std::vector<Value*> Args;
10066   Args.reserve(NumActualArgs);
10067   SmallVector<AttributeWithIndex, 8> attrVec;
10068   attrVec.reserve(NumCommonArgs);
10069
10070   // Get any return attributes.
10071   Attributes RAttrs = CallerPAL.getRetAttributes();
10072
10073   // If the return value is not being used, the type may not be compatible
10074   // with the existing attributes.  Wipe out any problematic attributes.
10075   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10076
10077   // Add the new return attributes.
10078   if (RAttrs)
10079     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10080
10081   AI = CS.arg_begin();
10082   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10083     const Type *ParamTy = FT->getParamType(i);
10084     if ((*AI)->getType() == ParamTy) {
10085       Args.push_back(*AI);
10086     } else {
10087       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10088           false, ParamTy, false);
10089       Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
10090     }
10091
10092     // Add any parameter attributes.
10093     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10094       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10095   }
10096
10097   // If the function takes more arguments than the call was taking, add them
10098   // now.
10099   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10100     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10101
10102   // If we are removing arguments to the function, emit an obnoxious warning.
10103   if (FT->getNumParams() < NumActualArgs) {
10104     if (!FT->isVarArg()) {
10105       errs() << "WARNING: While resolving call to function '"
10106              << Callee->getName() << "' arguments were dropped!\n";
10107     } else {
10108       // Add all of the arguments in their promoted form to the arg list.
10109       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10110         const Type *PTy = getPromotedType((*AI)->getType());
10111         if (PTy != (*AI)->getType()) {
10112           // Must promote to pass through va_arg area!
10113           Instruction::CastOps opcode =
10114             CastInst::getCastOpcode(*AI, false, PTy, false);
10115           Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
10116         } else {
10117           Args.push_back(*AI);
10118         }
10119
10120         // Add any parameter attributes.
10121         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10122           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10123       }
10124     }
10125   }
10126
10127   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10128     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10129
10130   if (NewRetTy == Type::getVoidTy(*Context))
10131     Caller->setName("");   // Void type should not have a name.
10132
10133   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10134                                                      attrVec.end());
10135
10136   Instruction *NC;
10137   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10138     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10139                             Args.begin(), Args.end(),
10140                             Caller->getName(), Caller);
10141     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10142     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10143   } else {
10144     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10145                           Caller->getName(), Caller);
10146     CallInst *CI = cast<CallInst>(Caller);
10147     if (CI->isTailCall())
10148       cast<CallInst>(NC)->setTailCall();
10149     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10150     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10151   }
10152
10153   // Insert a cast of the return type as necessary.
10154   Value *NV = NC;
10155   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10156     if (NV->getType() != Type::getVoidTy(*Context)) {
10157       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10158                                                             OldRetTy, false);
10159       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10160
10161       // If this is an invoke instruction, we should insert it after the first
10162       // non-phi, instruction in the normal successor block.
10163       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10164         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10165         InsertNewInstBefore(NC, *I);
10166       } else {
10167         // Otherwise, it's a call, just insert cast right after the call instr
10168         InsertNewInstBefore(NC, *Caller);
10169       }
10170       Worklist.AddUsersToWorkList(*Caller);
10171     } else {
10172       NV = UndefValue::get(Caller->getType());
10173     }
10174   }
10175
10176   if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
10177     Caller->replaceAllUsesWith(NV);
10178   Caller->eraseFromParent();
10179   Worklist.Remove(Caller);
10180   return true;
10181 }
10182
10183 // transformCallThroughTrampoline - Turn a call to a function created by the
10184 // init_trampoline intrinsic into a direct call to the underlying function.
10185 //
10186 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10187   Value *Callee = CS.getCalledValue();
10188   const PointerType *PTy = cast<PointerType>(Callee->getType());
10189   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10190   const AttrListPtr &Attrs = CS.getAttributes();
10191
10192   // If the call already has the 'nest' attribute somewhere then give up -
10193   // otherwise 'nest' would occur twice after splicing in the chain.
10194   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10195     return 0;
10196
10197   IntrinsicInst *Tramp =
10198     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10199
10200   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10201   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10202   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10203
10204   const AttrListPtr &NestAttrs = NestF->getAttributes();
10205   if (!NestAttrs.isEmpty()) {
10206     unsigned NestIdx = 1;
10207     const Type *NestTy = 0;
10208     Attributes NestAttr = Attribute::None;
10209
10210     // Look for a parameter marked with the 'nest' attribute.
10211     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10212          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10213       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10214         // Record the parameter type and any other attributes.
10215         NestTy = *I;
10216         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10217         break;
10218       }
10219
10220     if (NestTy) {
10221       Instruction *Caller = CS.getInstruction();
10222       std::vector<Value*> NewArgs;
10223       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10224
10225       SmallVector<AttributeWithIndex, 8> NewAttrs;
10226       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10227
10228       // Insert the nest argument into the call argument list, which may
10229       // mean appending it.  Likewise for attributes.
10230
10231       // Add any result attributes.
10232       if (Attributes Attr = Attrs.getRetAttributes())
10233         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10234
10235       {
10236         unsigned Idx = 1;
10237         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10238         do {
10239           if (Idx == NestIdx) {
10240             // Add the chain argument and attributes.
10241             Value *NestVal = Tramp->getOperand(3);
10242             if (NestVal->getType() != NestTy)
10243               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10244             NewArgs.push_back(NestVal);
10245             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10246           }
10247
10248           if (I == E)
10249             break;
10250
10251           // Add the original argument and attributes.
10252           NewArgs.push_back(*I);
10253           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10254             NewAttrs.push_back
10255               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10256
10257           ++Idx, ++I;
10258         } while (1);
10259       }
10260
10261       // Add any function attributes.
10262       if (Attributes Attr = Attrs.getFnAttributes())
10263         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10264
10265       // The trampoline may have been bitcast to a bogus type (FTy).
10266       // Handle this by synthesizing a new function type, equal to FTy
10267       // with the chain parameter inserted.
10268
10269       std::vector<const Type*> NewTypes;
10270       NewTypes.reserve(FTy->getNumParams()+1);
10271
10272       // Insert the chain's type into the list of parameter types, which may
10273       // mean appending it.
10274       {
10275         unsigned Idx = 1;
10276         FunctionType::param_iterator I = FTy->param_begin(),
10277           E = FTy->param_end();
10278
10279         do {
10280           if (Idx == NestIdx)
10281             // Add the chain's type.
10282             NewTypes.push_back(NestTy);
10283
10284           if (I == E)
10285             break;
10286
10287           // Add the original type.
10288           NewTypes.push_back(*I);
10289
10290           ++Idx, ++I;
10291         } while (1);
10292       }
10293
10294       // Replace the trampoline call with a direct call.  Let the generic
10295       // code sort out any function type mismatches.
10296       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 
10297                                                 FTy->isVarArg());
10298       Constant *NewCallee =
10299         NestF->getType() == PointerType::getUnqual(NewFTy) ?
10300         NestF : ConstantExpr::getBitCast(NestF, 
10301                                          PointerType::getUnqual(NewFTy));
10302       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10303                                                    NewAttrs.end());
10304
10305       Instruction *NewCaller;
10306       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10307         NewCaller = InvokeInst::Create(NewCallee,
10308                                        II->getNormalDest(), II->getUnwindDest(),
10309                                        NewArgs.begin(), NewArgs.end(),
10310                                        Caller->getName(), Caller);
10311         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10312         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10313       } else {
10314         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10315                                      Caller->getName(), Caller);
10316         if (cast<CallInst>(Caller)->isTailCall())
10317           cast<CallInst>(NewCaller)->setTailCall();
10318         cast<CallInst>(NewCaller)->
10319           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10320         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10321       }
10322       if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
10323         Caller->replaceAllUsesWith(NewCaller);
10324       Caller->eraseFromParent();
10325       Worklist.Remove(Caller);
10326       return 0;
10327     }
10328   }
10329
10330   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10331   // parameter, there is no need to adjust the argument list.  Let the generic
10332   // code sort out any function type mismatches.
10333   Constant *NewCallee =
10334     NestF->getType() == PTy ? NestF : 
10335                               ConstantExpr::getBitCast(NestF, PTy);
10336   CS.setCalledFunction(NewCallee);
10337   return CS.getInstruction();
10338 }
10339
10340 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10341 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10342 /// and a single binop.
10343 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10344   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10345   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10346   unsigned Opc = FirstInst->getOpcode();
10347   Value *LHSVal = FirstInst->getOperand(0);
10348   Value *RHSVal = FirstInst->getOperand(1);
10349     
10350   const Type *LHSType = LHSVal->getType();
10351   const Type *RHSType = RHSVal->getType();
10352   
10353   // Scan to see if all operands are the same opcode, all have one use, and all
10354   // kill their operands (i.e. the operands have one use).
10355   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10356     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10357     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10358         // Verify type of the LHS matches so we don't fold cmp's of different
10359         // types or GEP's with different index types.
10360         I->getOperand(0)->getType() != LHSType ||
10361         I->getOperand(1)->getType() != RHSType)
10362       return 0;
10363
10364     // If they are CmpInst instructions, check their predicates
10365     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10366       if (cast<CmpInst>(I)->getPredicate() !=
10367           cast<CmpInst>(FirstInst)->getPredicate())
10368         return 0;
10369     
10370     // Keep track of which operand needs a phi node.
10371     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10372     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10373   }
10374   
10375   // Otherwise, this is safe to transform!
10376   
10377   Value *InLHS = FirstInst->getOperand(0);
10378   Value *InRHS = FirstInst->getOperand(1);
10379   PHINode *NewLHS = 0, *NewRHS = 0;
10380   if (LHSVal == 0) {
10381     NewLHS = PHINode::Create(LHSType,
10382                              FirstInst->getOperand(0)->getName() + ".pn");
10383     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10384     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10385     InsertNewInstBefore(NewLHS, PN);
10386     LHSVal = NewLHS;
10387   }
10388   
10389   if (RHSVal == 0) {
10390     NewRHS = PHINode::Create(RHSType,
10391                              FirstInst->getOperand(1)->getName() + ".pn");
10392     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10393     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10394     InsertNewInstBefore(NewRHS, PN);
10395     RHSVal = NewRHS;
10396   }
10397   
10398   // Add all operands to the new PHIs.
10399   if (NewLHS || NewRHS) {
10400     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10401       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10402       if (NewLHS) {
10403         Value *NewInLHS = InInst->getOperand(0);
10404         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10405       }
10406       if (NewRHS) {
10407         Value *NewInRHS = InInst->getOperand(1);
10408         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10409       }
10410     }
10411   }
10412     
10413   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10414     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10415   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10416   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10417                          LHSVal, RHSVal);
10418 }
10419
10420 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10421   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10422   
10423   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10424                                         FirstInst->op_end());
10425   // This is true if all GEP bases are allocas and if all indices into them are
10426   // constants.
10427   bool AllBasePointersAreAllocas = true;
10428   
10429   // Scan to see if all operands are the same opcode, all have one use, and all
10430   // kill their operands (i.e. the operands have one use).
10431   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10432     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10433     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10434       GEP->getNumOperands() != FirstInst->getNumOperands())
10435       return 0;
10436
10437     // Keep track of whether or not all GEPs are of alloca pointers.
10438     if (AllBasePointersAreAllocas &&
10439         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10440          !GEP->hasAllConstantIndices()))
10441       AllBasePointersAreAllocas = false;
10442     
10443     // Compare the operand lists.
10444     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10445       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10446         continue;
10447       
10448       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10449       // if one of the PHIs has a constant for the index.  The index may be
10450       // substantially cheaper to compute for the constants, so making it a
10451       // variable index could pessimize the path.  This also handles the case
10452       // for struct indices, which must always be constant.
10453       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10454           isa<ConstantInt>(GEP->getOperand(op)))
10455         return 0;
10456       
10457       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10458         return 0;
10459       FixedOperands[op] = 0;  // Needs a PHI.
10460     }
10461   }
10462   
10463   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10464   // bother doing this transformation.  At best, this will just save a bit of
10465   // offset calculation, but all the predecessors will have to materialize the
10466   // stack address into a register anyway.  We'd actually rather *clone* the
10467   // load up into the predecessors so that we have a load of a gep of an alloca,
10468   // which can usually all be folded into the load.
10469   if (AllBasePointersAreAllocas)
10470     return 0;
10471   
10472   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10473   // that is variable.
10474   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10475   
10476   bool HasAnyPHIs = false;
10477   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10478     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10479     Value *FirstOp = FirstInst->getOperand(i);
10480     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10481                                      FirstOp->getName()+".pn");
10482     InsertNewInstBefore(NewPN, PN);
10483     
10484     NewPN->reserveOperandSpace(e);
10485     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10486     OperandPhis[i] = NewPN;
10487     FixedOperands[i] = NewPN;
10488     HasAnyPHIs = true;
10489   }
10490
10491   
10492   // Add all operands to the new PHIs.
10493   if (HasAnyPHIs) {
10494     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10495       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10496       BasicBlock *InBB = PN.getIncomingBlock(i);
10497       
10498       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10499         if (PHINode *OpPhi = OperandPhis[op])
10500           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10501     }
10502   }
10503   
10504   Value *Base = FixedOperands[0];
10505   GetElementPtrInst *GEP =
10506     GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10507                               FixedOperands.end());
10508   if (cast<GEPOperator>(FirstInst)->isInBounds())
10509     cast<GEPOperator>(GEP)->setIsInBounds(true);
10510   return GEP;
10511 }
10512
10513
10514 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10515 /// sink the load out of the block that defines it.  This means that it must be
10516 /// obvious the value of the load is not changed from the point of the load to
10517 /// the end of the block it is in.
10518 ///
10519 /// Finally, it is safe, but not profitable, to sink a load targetting a
10520 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10521 /// to a register.
10522 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10523   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10524   
10525   for (++BBI; BBI != E; ++BBI)
10526     if (BBI->mayWriteToMemory())
10527       return false;
10528   
10529   // Check for non-address taken alloca.  If not address-taken already, it isn't
10530   // profitable to do this xform.
10531   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10532     bool isAddressTaken = false;
10533     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10534          UI != E; ++UI) {
10535       if (isa<LoadInst>(UI)) continue;
10536       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10537         // If storing TO the alloca, then the address isn't taken.
10538         if (SI->getOperand(1) == AI) continue;
10539       }
10540       isAddressTaken = true;
10541       break;
10542     }
10543     
10544     if (!isAddressTaken && AI->isStaticAlloca())
10545       return false;
10546   }
10547   
10548   // If this load is a load from a GEP with a constant offset from an alloca,
10549   // then we don't want to sink it.  In its present form, it will be
10550   // load [constant stack offset].  Sinking it will cause us to have to
10551   // materialize the stack addresses in each predecessor in a register only to
10552   // do a shared load from register in the successor.
10553   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10554     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10555       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10556         return false;
10557   
10558   return true;
10559 }
10560
10561
10562 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10563 // operator and they all are only used by the PHI, PHI together their
10564 // inputs, and do the operation once, to the result of the PHI.
10565 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10566   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10567
10568   // Scan the instruction, looking for input operations that can be folded away.
10569   // If all input operands to the phi are the same instruction (e.g. a cast from
10570   // the same type or "+42") we can pull the operation through the PHI, reducing
10571   // code size and simplifying code.
10572   Constant *ConstantOp = 0;
10573   const Type *CastSrcTy = 0;
10574   bool isVolatile = false;
10575   if (isa<CastInst>(FirstInst)) {
10576     CastSrcTy = FirstInst->getOperand(0)->getType();
10577   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10578     // Can fold binop, compare or shift here if the RHS is a constant, 
10579     // otherwise call FoldPHIArgBinOpIntoPHI.
10580     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10581     if (ConstantOp == 0)
10582       return FoldPHIArgBinOpIntoPHI(PN);
10583   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10584     isVolatile = LI->isVolatile();
10585     // We can't sink the load if the loaded value could be modified between the
10586     // load and the PHI.
10587     if (LI->getParent() != PN.getIncomingBlock(0) ||
10588         !isSafeAndProfitableToSinkLoad(LI))
10589       return 0;
10590     
10591     // If the PHI is of volatile loads and the load block has multiple
10592     // successors, sinking it would remove a load of the volatile value from
10593     // the path through the other successor.
10594     if (isVolatile &&
10595         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10596       return 0;
10597     
10598   } else if (isa<GetElementPtrInst>(FirstInst)) {
10599     return FoldPHIArgGEPIntoPHI(PN);
10600   } else {
10601     return 0;  // Cannot fold this operation.
10602   }
10603
10604   // Check to see if all arguments are the same operation.
10605   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10606     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10607     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10608     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10609       return 0;
10610     if (CastSrcTy) {
10611       if (I->getOperand(0)->getType() != CastSrcTy)
10612         return 0;  // Cast operation must match.
10613     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10614       // We can't sink the load if the loaded value could be modified between 
10615       // the load and the PHI.
10616       if (LI->isVolatile() != isVolatile ||
10617           LI->getParent() != PN.getIncomingBlock(i) ||
10618           !isSafeAndProfitableToSinkLoad(LI))
10619         return 0;
10620       
10621       // If the PHI is of volatile loads and the load block has multiple
10622       // successors, sinking it would remove a load of the volatile value from
10623       // the path through the other successor.
10624       if (isVolatile &&
10625           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10626         return 0;
10627       
10628     } else if (I->getOperand(1) != ConstantOp) {
10629       return 0;
10630     }
10631   }
10632
10633   // Okay, they are all the same operation.  Create a new PHI node of the
10634   // correct type, and PHI together all of the LHS's of the instructions.
10635   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10636                                    PN.getName()+".in");
10637   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10638
10639   Value *InVal = FirstInst->getOperand(0);
10640   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10641
10642   // Add all operands to the new PHI.
10643   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10644     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10645     if (NewInVal != InVal)
10646       InVal = 0;
10647     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10648   }
10649
10650   Value *PhiVal;
10651   if (InVal) {
10652     // The new PHI unions all of the same values together.  This is really
10653     // common, so we handle it intelligently here for compile-time speed.
10654     PhiVal = InVal;
10655     delete NewPN;
10656   } else {
10657     InsertNewInstBefore(NewPN, PN);
10658     PhiVal = NewPN;
10659   }
10660
10661   // Insert and return the new operation.
10662   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10663     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10664   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10665     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10666   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10667     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10668                            PhiVal, ConstantOp);
10669   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10670   
10671   // If this was a volatile load that we are merging, make sure to loop through
10672   // and mark all the input loads as non-volatile.  If we don't do this, we will
10673   // insert a new volatile load and the old ones will not be deletable.
10674   if (isVolatile)
10675     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10676       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10677   
10678   return new LoadInst(PhiVal, "", isVolatile);
10679 }
10680
10681 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10682 /// that is dead.
10683 static bool DeadPHICycle(PHINode *PN,
10684                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10685   if (PN->use_empty()) return true;
10686   if (!PN->hasOneUse()) return false;
10687
10688   // Remember this node, and if we find the cycle, return.
10689   if (!PotentiallyDeadPHIs.insert(PN))
10690     return true;
10691   
10692   // Don't scan crazily complex things.
10693   if (PotentiallyDeadPHIs.size() == 16)
10694     return false;
10695
10696   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10697     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10698
10699   return false;
10700 }
10701
10702 /// PHIsEqualValue - Return true if this phi node is always equal to
10703 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10704 ///   z = some value; x = phi (y, z); y = phi (x, z)
10705 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10706                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10707   // See if we already saw this PHI node.
10708   if (!ValueEqualPHIs.insert(PN))
10709     return true;
10710   
10711   // Don't scan crazily complex things.
10712   if (ValueEqualPHIs.size() == 16)
10713     return false;
10714  
10715   // Scan the operands to see if they are either phi nodes or are equal to
10716   // the value.
10717   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10718     Value *Op = PN->getIncomingValue(i);
10719     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10720       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10721         return false;
10722     } else if (Op != NonPhiInVal)
10723       return false;
10724   }
10725   
10726   return true;
10727 }
10728
10729
10730 // PHINode simplification
10731 //
10732 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10733   // If LCSSA is around, don't mess with Phi nodes
10734   if (MustPreserveLCSSA) return 0;
10735   
10736   if (Value *V = PN.hasConstantValue())
10737     return ReplaceInstUsesWith(PN, V);
10738
10739   // If all PHI operands are the same operation, pull them through the PHI,
10740   // reducing code size.
10741   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10742       isa<Instruction>(PN.getIncomingValue(1)) &&
10743       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10744       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10745       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10746       // than themselves more than once.
10747       PN.getIncomingValue(0)->hasOneUse())
10748     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10749       return Result;
10750
10751   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10752   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10753   // PHI)... break the cycle.
10754   if (PN.hasOneUse()) {
10755     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10756     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10757       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10758       PotentiallyDeadPHIs.insert(&PN);
10759       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10760         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10761     }
10762    
10763     // If this phi has a single use, and if that use just computes a value for
10764     // the next iteration of a loop, delete the phi.  This occurs with unused
10765     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10766     // common case here is good because the only other things that catch this
10767     // are induction variable analysis (sometimes) and ADCE, which is only run
10768     // late.
10769     if (PHIUser->hasOneUse() &&
10770         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10771         PHIUser->use_back() == &PN) {
10772       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10773     }
10774   }
10775
10776   // We sometimes end up with phi cycles that non-obviously end up being the
10777   // same value, for example:
10778   //   z = some value; x = phi (y, z); y = phi (x, z)
10779   // where the phi nodes don't necessarily need to be in the same block.  Do a
10780   // quick check to see if the PHI node only contains a single non-phi value, if
10781   // so, scan to see if the phi cycle is actually equal to that value.
10782   {
10783     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10784     // Scan for the first non-phi operand.
10785     while (InValNo != NumOperandVals && 
10786            isa<PHINode>(PN.getIncomingValue(InValNo)))
10787       ++InValNo;
10788
10789     if (InValNo != NumOperandVals) {
10790       Value *NonPhiInVal = PN.getOperand(InValNo);
10791       
10792       // Scan the rest of the operands to see if there are any conflicts, if so
10793       // there is no need to recursively scan other phis.
10794       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10795         Value *OpVal = PN.getIncomingValue(InValNo);
10796         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10797           break;
10798       }
10799       
10800       // If we scanned over all operands, then we have one unique value plus
10801       // phi values.  Scan PHI nodes to see if they all merge in each other or
10802       // the value.
10803       if (InValNo == NumOperandVals) {
10804         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10805         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10806           return ReplaceInstUsesWith(PN, NonPhiInVal);
10807       }
10808     }
10809   }
10810   return 0;
10811 }
10812
10813 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10814   Value *PtrOp = GEP.getOperand(0);
10815   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10816   // If so, eliminate the noop.
10817   if (GEP.getNumOperands() == 1)
10818     return ReplaceInstUsesWith(GEP, PtrOp);
10819
10820   if (isa<UndefValue>(GEP.getOperand(0)))
10821     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10822
10823   bool HasZeroPointerIndex = false;
10824   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10825     HasZeroPointerIndex = C->isNullValue();
10826
10827   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10828     return ReplaceInstUsesWith(GEP, PtrOp);
10829
10830   // Eliminate unneeded casts for indices.
10831   if (TD) {
10832     bool MadeChange = false;
10833     unsigned PtrSize = TD->getPointerSizeInBits();
10834     
10835     gep_type_iterator GTI = gep_type_begin(GEP);
10836     for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10837          I != E; ++I, ++GTI) {
10838       if (!isa<SequentialType>(*GTI)) continue;
10839       
10840       // If we are using a wider index than needed for this platform, shrink it
10841       // to what we need.  If narrower, sign-extend it to what we need.  This
10842       // explicit cast can make subsequent optimizations more obvious.
10843       unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
10844       
10845       if (OpBits == PtrSize)
10846         continue;
10847       
10848       Instruction::CastOps Opc =
10849         OpBits > PtrSize ? Instruction::Trunc : Instruction::SExt;
10850       *I = InsertCastBefore(Opc, *I, TD->getIntPtrType(GEP.getContext()), GEP);
10851       MadeChange = true;
10852     }
10853     if (MadeChange) return &GEP;
10854   }
10855
10856   // Combine Indices - If the source pointer to this getelementptr instruction
10857   // is a getelementptr instruction, combine the indices of the two
10858   // getelementptr instructions into a single instruction.
10859   //
10860   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
10861     // Note that if our source is a gep chain itself that we wait for that
10862     // chain to be resolved before we perform this transformation.  This
10863     // avoids us creating a TON of code in some cases.
10864     //
10865     if (GetElementPtrInst *SrcGEP =
10866           dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10867       if (SrcGEP->getNumOperands() == 2)
10868         return 0;   // Wait until our source is folded to completion.
10869
10870     SmallVector<Value*, 8> Indices;
10871
10872     // Find out whether the last index in the source GEP is a sequential idx.
10873     bool EndsWithSequential = false;
10874     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10875          I != E; ++I)
10876       EndsWithSequential = !isa<StructType>(*I);
10877
10878     // Can we combine the two pointer arithmetics offsets?
10879     if (EndsWithSequential) {
10880       // Replace: gep (gep %P, long B), long A, ...
10881       // With:    T = long A+B; gep %P, T, ...
10882       //
10883       Value *Sum;
10884       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10885       Value *GO1 = GEP.getOperand(1);
10886       if (SO1 == Constant::getNullValue(SO1->getType())) {
10887         Sum = GO1;
10888       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10889         Sum = SO1;
10890       } else {
10891         // If they aren't the same type, then the input hasn't been processed
10892         // by the loop above yet (which canonicalizes sequential index types to
10893         // intptr_t).  Just avoid transforming this until the input has been
10894         // normalized.
10895         if (SO1->getType() != GO1->getType())
10896           return 0;
10897         Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10898       }
10899
10900       // Update the GEP in place if possible.
10901       if (Src->getNumOperands() == 2) {
10902         GEP.setOperand(0, Src->getOperand(0));
10903         GEP.setOperand(1, Sum);
10904         return &GEP;
10905       }
10906       Indices.append(Src->op_begin()+1, Src->op_end()-1);
10907       Indices.push_back(Sum);
10908       Indices.append(GEP.op_begin()+2, GEP.op_end());
10909     } else if (isa<Constant>(*GEP.idx_begin()) &&
10910                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10911                Src->getNumOperands() != 1) {
10912       // Otherwise we can do the fold if the first index of the GEP is a zero
10913       Indices.append(Src->op_begin()+1, Src->op_end());
10914       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
10915     }
10916
10917     if (!Indices.empty()) {
10918       GetElementPtrInst *NewGEP =
10919         GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
10920                                   Indices.end(), GEP.getName());
10921       if (cast<GEPOperator>(&GEP)->isInBounds() && Src->isInBounds())
10922         cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10923       return NewGEP;
10924     }
10925   }
10926   
10927   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
10928   if (Value *X = getBitCastOperand(PtrOp)) {
10929     assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
10930            
10931     if (HasZeroPointerIndex) {
10932       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10933       // into     : GEP [10 x i8]* X, i32 0, ...
10934       //
10935       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
10936       //           into     : GEP i8* X, ...
10937       // 
10938       // This occurs when the program declares an array extern like "int X[];"
10939       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10940       const PointerType *XTy = cast<PointerType>(X->getType());
10941       if (const ArrayType *CATy =
10942           dyn_cast<ArrayType>(CPTy->getElementType())) {
10943         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
10944         if (CATy->getElementType() == XTy->getElementType()) {
10945           // -> GEP i8* X, ...
10946           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
10947           GetElementPtrInst *NewGEP =
10948             GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
10949                                       GEP.getName());
10950           if (cast<GEPOperator>(&GEP)->isInBounds())
10951             cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10952           return NewGEP;
10953         } else if (const ArrayType *XATy =
10954                  dyn_cast<ArrayType>(XTy->getElementType())) {
10955           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
10956           if (CATy->getElementType() == XATy->getElementType()) {
10957             // -> GEP [10 x i8]* X, i32 0, ...
10958             // At this point, we know that the cast source type is a pointer
10959             // to an array of the same type as the destination pointer
10960             // array.  Because the array type is never stepped over (there
10961             // is a leading zero) we can fold the cast into this GEP.
10962             GEP.setOperand(0, X);
10963             return &GEP;
10964           }
10965         }
10966       }
10967     } else if (GEP.getNumOperands() == 2) {
10968       // Transform things like:
10969       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10970       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10971       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10972       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10973       if (TD && isa<ArrayType>(SrcElTy) &&
10974           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10975           TD->getTypeAllocSize(ResElTy)) {
10976         Value *Idx[2];
10977         Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
10978         Idx[1] = GEP.getOperand(1);
10979         Value *NewGEP =
10980           Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
10981         if (cast<GEPOperator>(&GEP)->isInBounds())
10982           cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10983         // V and GEP are both pointer types --> BitCast
10984         return new BitCastInst(NewGEP, GEP.getType());
10985       }
10986       
10987       // Transform things like:
10988       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10989       //   (where tmp = 8*tmp2) into:
10990       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10991       
10992       if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
10993         uint64_t ArrayEltSize =
10994             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
10995         
10996         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
10997         // allow either a mul, shift, or constant here.
10998         Value *NewIdx = 0;
10999         ConstantInt *Scale = 0;
11000         if (ArrayEltSize == 1) {
11001           NewIdx = GEP.getOperand(1);
11002           Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11003         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11004           NewIdx = ConstantInt::get(CI->getType(), 1);
11005           Scale = CI;
11006         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11007           if (Inst->getOpcode() == Instruction::Shl &&
11008               isa<ConstantInt>(Inst->getOperand(1))) {
11009             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11010             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11011             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11012                                      1ULL << ShAmtVal);
11013             NewIdx = Inst->getOperand(0);
11014           } else if (Inst->getOpcode() == Instruction::Mul &&
11015                      isa<ConstantInt>(Inst->getOperand(1))) {
11016             Scale = cast<ConstantInt>(Inst->getOperand(1));
11017             NewIdx = Inst->getOperand(0);
11018           }
11019         }
11020         
11021         // If the index will be to exactly the right offset with the scale taken
11022         // out, perform the transformation. Note, we don't know whether Scale is
11023         // signed or not. We'll use unsigned version of division/modulo
11024         // operation after making sure Scale doesn't have the sign bit set.
11025         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11026             Scale->getZExtValue() % ArrayEltSize == 0) {
11027           Scale = ConstantInt::get(Scale->getType(),
11028                                    Scale->getZExtValue() / ArrayEltSize);
11029           if (Scale->getZExtValue() != 1) {
11030             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11031                                                        false /*ZExt*/);
11032             NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
11033           }
11034
11035           // Insert the new GEP instruction.
11036           Value *Idx[2];
11037           Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11038           Idx[1] = NewIdx;
11039           Value *NewGEP = Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11040           if (cast<GEPOperator>(&GEP)->isInBounds())
11041             cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11042           // The NewGEP must be pointer typed, so must the old one -> BitCast
11043           return new BitCastInst(NewGEP, GEP.getType());
11044         }
11045       }
11046     }
11047   }
11048   
11049   /// See if we can simplify:
11050   ///   X = bitcast A* to B*
11051   ///   Y = gep X, <...constant indices...>
11052   /// into a gep of the original struct.  This is important for SROA and alias
11053   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11054   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11055     if (TD &&
11056         !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11057       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11058       // a constant back from EmitGEPOffset.
11059       ConstantInt *OffsetV =
11060                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11061       int64_t Offset = OffsetV->getSExtValue();
11062       
11063       // If this GEP instruction doesn't move the pointer, just replace the GEP
11064       // with a bitcast of the real input to the dest type.
11065       if (Offset == 0) {
11066         // If the bitcast is of an allocation, and the allocation will be
11067         // converted to match the type of the cast, don't touch this.
11068         if (isa<AllocationInst>(BCI->getOperand(0))) {
11069           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11070           if (Instruction *I = visitBitCast(*BCI)) {
11071             if (I != BCI) {
11072               I->takeName(BCI);
11073               BCI->getParent()->getInstList().insert(BCI, I);
11074               ReplaceInstUsesWith(*BCI, I);
11075             }
11076             return &GEP;
11077           }
11078         }
11079         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11080       }
11081       
11082       // Otherwise, if the offset is non-zero, we need to find out if there is a
11083       // field at Offset in 'A's type.  If so, we can pull the cast through the
11084       // GEP.
11085       SmallVector<Value*, 8> NewIndices;
11086       const Type *InTy =
11087         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11088       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11089         Value *NGEP = Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11090                                          NewIndices.end());
11091         if (cast<GEPOperator>(&GEP)->isInBounds())
11092           cast<GEPOperator>(NGEP)->setIsInBounds(true);
11093         
11094         if (NGEP->getType() == GEP.getType())
11095           return ReplaceInstUsesWith(GEP, NGEP);
11096         NGEP->takeName(&GEP);
11097         return new BitCastInst(NGEP, GEP.getType());
11098       }
11099     }
11100   }    
11101     
11102   return 0;
11103 }
11104
11105 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11106   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11107   if (AI.isArrayAllocation()) {  // Check C != 1
11108     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11109       const Type *NewTy = 
11110         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11111       AllocationInst *New = 0;
11112
11113       // Create and insert the replacement instruction...
11114       if (isa<MallocInst>(AI))
11115         New = Builder->CreateMalloc(NewTy, 0, AI.getName());
11116       else {
11117         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11118         New = Builder->CreateAlloca(NewTy, 0, AI.getName());
11119       }
11120       New->setAlignment(AI.getAlignment());
11121
11122       // Scan to the end of the allocation instructions, to skip over a block of
11123       // allocas if possible...also skip interleaved debug info
11124       //
11125       BasicBlock::iterator It = New;
11126       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11127
11128       // Now that I is pointing to the first non-allocation-inst in the block,
11129       // insert our getelementptr instruction...
11130       //
11131       Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
11132       Value *Idx[2];
11133       Idx[0] = NullIdx;
11134       Idx[1] = NullIdx;
11135       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11136                                            New->getName()+".sub", It);
11137       cast<GEPOperator>(V)->setIsInBounds(true);
11138
11139       // Now make everything use the getelementptr instead of the original
11140       // allocation.
11141       return ReplaceInstUsesWith(AI, V);
11142     } else if (isa<UndefValue>(AI.getArraySize())) {
11143       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11144     }
11145   }
11146
11147   if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11148     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11149     // Note that we only do this for alloca's, because malloc should allocate
11150     // and return a unique pointer, even for a zero byte allocation.
11151     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11152       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11153
11154     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11155     if (AI.getAlignment() == 0)
11156       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11157   }
11158
11159   return 0;
11160 }
11161
11162 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11163   Value *Op = FI.getOperand(0);
11164
11165   // free undef -> unreachable.
11166   if (isa<UndefValue>(Op)) {
11167     // Insert a new store to null because we cannot modify the CFG here.
11168     new StoreInst(ConstantInt::getTrue(*Context),
11169            UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
11170     return EraseInstFromFunction(FI);
11171   }
11172   
11173   // If we have 'free null' delete the instruction.  This can happen in stl code
11174   // when lots of inlining happens.
11175   if (isa<ConstantPointerNull>(Op))
11176     return EraseInstFromFunction(FI);
11177   
11178   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11179   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11180     FI.setOperand(0, CI->getOperand(0));
11181     return &FI;
11182   }
11183   
11184   // Change free (gep X, 0,0,0,0) into free(X)
11185   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11186     if (GEPI->hasAllZeroIndices()) {
11187       Worklist.Add(GEPI);
11188       FI.setOperand(0, GEPI->getOperand(0));
11189       return &FI;
11190     }
11191   }
11192   
11193   // Change free(malloc) into nothing, if the malloc has a single use.
11194   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11195     if (MI->hasOneUse()) {
11196       EraseInstFromFunction(FI);
11197       return EraseInstFromFunction(*MI);
11198     }
11199
11200   return 0;
11201 }
11202
11203
11204 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11205 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11206                                         const TargetData *TD) {
11207   User *CI = cast<User>(LI.getOperand(0));
11208   Value *CastOp = CI->getOperand(0);
11209   LLVMContext *Context = IC.getContext();
11210
11211   if (TD) {
11212     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11213       // Instead of loading constant c string, use corresponding integer value
11214       // directly if string length is small enough.
11215       std::string Str;
11216       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11217         unsigned len = Str.length();
11218         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11219         unsigned numBits = Ty->getPrimitiveSizeInBits();
11220         // Replace LI with immediate integer store.
11221         if ((numBits >> 3) == len + 1) {
11222           APInt StrVal(numBits, 0);
11223           APInt SingleChar(numBits, 0);
11224           if (TD->isLittleEndian()) {
11225             for (signed i = len-1; i >= 0; i--) {
11226               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11227               StrVal = (StrVal << 8) | SingleChar;
11228             }
11229           } else {
11230             for (unsigned i = 0; i < len; i++) {
11231               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11232               StrVal = (StrVal << 8) | SingleChar;
11233             }
11234             // Append NULL at the end.
11235             SingleChar = 0;
11236             StrVal = (StrVal << 8) | SingleChar;
11237           }
11238           Value *NL = ConstantInt::get(*Context, StrVal);
11239           return IC.ReplaceInstUsesWith(LI, NL);
11240         }
11241       }
11242     }
11243   }
11244
11245   const PointerType *DestTy = cast<PointerType>(CI->getType());
11246   const Type *DestPTy = DestTy->getElementType();
11247   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11248
11249     // If the address spaces don't match, don't eliminate the cast.
11250     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11251       return 0;
11252
11253     const Type *SrcPTy = SrcTy->getElementType();
11254
11255     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11256          isa<VectorType>(DestPTy)) {
11257       // If the source is an array, the code below will not succeed.  Check to
11258       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11259       // constants.
11260       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11261         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11262           if (ASrcTy->getNumElements() != 0) {
11263             Value *Idxs[2];
11264             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
11265             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11266             SrcTy = cast<PointerType>(CastOp->getType());
11267             SrcPTy = SrcTy->getElementType();
11268           }
11269
11270       if (IC.getTargetData() &&
11271           (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11272             isa<VectorType>(SrcPTy)) &&
11273           // Do not allow turning this into a load of an integer, which is then
11274           // casted to a pointer, this pessimizes pointer analysis a lot.
11275           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11276           IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11277                IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11278
11279         // Okay, we are casting from one integer or pointer type to another of
11280         // the same size.  Instead of casting the pointer before the load, cast
11281         // the result of the loaded value.
11282         Value *NewLoad = 
11283           IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
11284         // Now cast the result of the load.
11285         return new BitCastInst(NewLoad, LI.getType());
11286       }
11287     }
11288   }
11289   return 0;
11290 }
11291
11292 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11293   Value *Op = LI.getOperand(0);
11294
11295   // Attempt to improve the alignment.
11296   if (TD) {
11297     unsigned KnownAlign =
11298       GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11299     if (KnownAlign >
11300         (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11301                                   LI.getAlignment()))
11302       LI.setAlignment(KnownAlign);
11303   }
11304
11305   // load (cast X) --> cast (load X) iff safe
11306   if (isa<CastInst>(Op))
11307     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11308       return Res;
11309
11310   // None of the following transforms are legal for volatile loads.
11311   if (LI.isVolatile()) return 0;
11312   
11313   // Do really simple store-to-load forwarding and load CSE, to catch cases
11314   // where there are several consequtive memory accesses to the same location,
11315   // separated by a few arithmetic operations.
11316   BasicBlock::iterator BBI = &LI;
11317   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11318     return ReplaceInstUsesWith(LI, AvailableVal);
11319
11320   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11321     const Value *GEPI0 = GEPI->getOperand(0);
11322     // TODO: Consider a target hook for valid address spaces for this xform.
11323     if (isa<ConstantPointerNull>(GEPI0) &&
11324         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11325       // Insert a new store to null instruction before the load to indicate
11326       // that this code is not reachable.  We do this instead of inserting
11327       // an unreachable instruction directly because we cannot modify the
11328       // CFG.
11329       new StoreInst(UndefValue::get(LI.getType()),
11330                     Constant::getNullValue(Op->getType()), &LI);
11331       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11332     }
11333   } 
11334
11335   if (Constant *C = dyn_cast<Constant>(Op)) {
11336     // load null/undef -> undef
11337     // TODO: Consider a target hook for valid address spaces for this xform.
11338     if (isa<UndefValue>(C) || (C->isNullValue() && 
11339         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11340       // Insert a new store to null instruction before the load to indicate that
11341       // this code is not reachable.  We do this instead of inserting an
11342       // unreachable instruction directly because we cannot modify the CFG.
11343       new StoreInst(UndefValue::get(LI.getType()),
11344                     Constant::getNullValue(Op->getType()), &LI);
11345       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11346     }
11347
11348     // Instcombine load (constant global) into the value loaded.
11349     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11350       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11351         return ReplaceInstUsesWith(LI, GV->getInitializer());
11352
11353     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11354     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11355       if (CE->getOpcode() == Instruction::GetElementPtr) {
11356         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11357           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11358             if (Constant *V = 
11359                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE, 
11360                                                       *Context))
11361               return ReplaceInstUsesWith(LI, V);
11362         if (CE->getOperand(0)->isNullValue()) {
11363           // Insert a new store to null instruction before the load to indicate
11364           // that this code is not reachable.  We do this instead of inserting
11365           // an unreachable instruction directly because we cannot modify the
11366           // CFG.
11367           new StoreInst(UndefValue::get(LI.getType()),
11368                         Constant::getNullValue(Op->getType()), &LI);
11369           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11370         }
11371
11372       } else if (CE->isCast()) {
11373         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11374           return Res;
11375       }
11376     }
11377   }
11378     
11379   // If this load comes from anywhere in a constant global, and if the global
11380   // is all undef or zero, we know what it loads.
11381   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11382     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11383       if (GV->getInitializer()->isNullValue())
11384         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11385       else if (isa<UndefValue>(GV->getInitializer()))
11386         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11387     }
11388   }
11389
11390   if (Op->hasOneUse()) {
11391     // Change select and PHI nodes to select values instead of addresses: this
11392     // helps alias analysis out a lot, allows many others simplifications, and
11393     // exposes redundancy in the code.
11394     //
11395     // Note that we cannot do the transformation unless we know that the
11396     // introduced loads cannot trap!  Something like this is valid as long as
11397     // the condition is always false: load (select bool %C, int* null, int* %G),
11398     // but it would not be valid if we transformed it to load from null
11399     // unconditionally.
11400     //
11401     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11402       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11403       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11404           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11405         Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11406                                         SI->getOperand(1)->getName()+".val");
11407         Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11408                                         SI->getOperand(2)->getName()+".val");
11409         return SelectInst::Create(SI->getCondition(), V1, V2);
11410       }
11411
11412       // load (select (cond, null, P)) -> load P
11413       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11414         if (C->isNullValue()) {
11415           LI.setOperand(0, SI->getOperand(2));
11416           return &LI;
11417         }
11418
11419       // load (select (cond, P, null)) -> load P
11420       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11421         if (C->isNullValue()) {
11422           LI.setOperand(0, SI->getOperand(1));
11423           return &LI;
11424         }
11425     }
11426   }
11427   return 0;
11428 }
11429
11430 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11431 /// when possible.  This makes it generally easy to do alias analysis and/or
11432 /// SROA/mem2reg of the memory object.
11433 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11434   User *CI = cast<User>(SI.getOperand(1));
11435   Value *CastOp = CI->getOperand(0);
11436
11437   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11438   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11439   if (SrcTy == 0) return 0;
11440   
11441   const Type *SrcPTy = SrcTy->getElementType();
11442
11443   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11444     return 0;
11445   
11446   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11447   /// to its first element.  This allows us to handle things like:
11448   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11449   /// on 32-bit hosts.
11450   SmallVector<Value*, 4> NewGEPIndices;
11451   
11452   // If the source is an array, the code below will not succeed.  Check to
11453   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11454   // constants.
11455   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11456     // Index through pointer.
11457     Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
11458     NewGEPIndices.push_back(Zero);
11459     
11460     while (1) {
11461       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11462         if (!STy->getNumElements()) /* Struct can be empty {} */
11463           break;
11464         NewGEPIndices.push_back(Zero);
11465         SrcPTy = STy->getElementType(0);
11466       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11467         NewGEPIndices.push_back(Zero);
11468         SrcPTy = ATy->getElementType();
11469       } else {
11470         break;
11471       }
11472     }
11473     
11474     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11475   }
11476
11477   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11478     return 0;
11479   
11480   // If the pointers point into different address spaces or if they point to
11481   // values with different sizes, we can't do the transformation.
11482   if (!IC.getTargetData() ||
11483       SrcTy->getAddressSpace() != 
11484         cast<PointerType>(CI->getType())->getAddressSpace() ||
11485       IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11486       IC.getTargetData()->getTypeSizeInBits(DestPTy))
11487     return 0;
11488
11489   // Okay, we are casting from one integer or pointer type to another of
11490   // the same size.  Instead of casting the pointer before 
11491   // the store, cast the value to be stored.
11492   Value *NewCast;
11493   Value *SIOp0 = SI.getOperand(0);
11494   Instruction::CastOps opcode = Instruction::BitCast;
11495   const Type* CastSrcTy = SIOp0->getType();
11496   const Type* CastDstTy = SrcPTy;
11497   if (isa<PointerType>(CastDstTy)) {
11498     if (CastSrcTy->isInteger())
11499       opcode = Instruction::IntToPtr;
11500   } else if (isa<IntegerType>(CastDstTy)) {
11501     if (isa<PointerType>(SIOp0->getType()))
11502       opcode = Instruction::PtrToInt;
11503   }
11504   
11505   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11506   // emit a GEP to index into its first field.
11507   if (!NewGEPIndices.empty()) {
11508     CastOp = IC.Builder->CreateGEP(CastOp, NewGEPIndices.begin(),
11509                                    NewGEPIndices.end());
11510     cast<GEPOperator>(CastOp)->setIsInBounds(true);
11511   }
11512   
11513   NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11514                                    SIOp0->getName()+".c");
11515   return new StoreInst(NewCast, CastOp);
11516 }
11517
11518 /// equivalentAddressValues - Test if A and B will obviously have the same
11519 /// value. This includes recognizing that %t0 and %t1 will have the same
11520 /// value in code like this:
11521 ///   %t0 = getelementptr \@a, 0, 3
11522 ///   store i32 0, i32* %t0
11523 ///   %t1 = getelementptr \@a, 0, 3
11524 ///   %t2 = load i32* %t1
11525 ///
11526 static bool equivalentAddressValues(Value *A, Value *B) {
11527   // Test if the values are trivially equivalent.
11528   if (A == B) return true;
11529   
11530   // Test if the values come form identical arithmetic instructions.
11531   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11532   // its only used to compare two uses within the same basic block, which
11533   // means that they'll always either have the same value or one of them
11534   // will have an undefined value.
11535   if (isa<BinaryOperator>(A) ||
11536       isa<CastInst>(A) ||
11537       isa<PHINode>(A) ||
11538       isa<GetElementPtrInst>(A))
11539     if (Instruction *BI = dyn_cast<Instruction>(B))
11540       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
11541         return true;
11542   
11543   // Otherwise they may not be equivalent.
11544   return false;
11545 }
11546
11547 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11548 // return the llvm.dbg.declare.
11549 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11550   if (!V->hasNUses(2))
11551     return 0;
11552   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11553        UI != E; ++UI) {
11554     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11555       return DI;
11556     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11557       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11558         return DI;
11559       }
11560   }
11561   return 0;
11562 }
11563
11564 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11565   Value *Val = SI.getOperand(0);
11566   Value *Ptr = SI.getOperand(1);
11567
11568   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11569     EraseInstFromFunction(SI);
11570     ++NumCombined;
11571     return 0;
11572   }
11573   
11574   // If the RHS is an alloca with a single use, zapify the store, making the
11575   // alloca dead.
11576   // If the RHS is an alloca with a two uses, the other one being a 
11577   // llvm.dbg.declare, zapify the store and the declare, making the
11578   // alloca dead.  We must do this to prevent declare's from affecting
11579   // codegen.
11580   if (!SI.isVolatile()) {
11581     if (Ptr->hasOneUse()) {
11582       if (isa<AllocaInst>(Ptr)) {
11583         EraseInstFromFunction(SI);
11584         ++NumCombined;
11585         return 0;
11586       }
11587       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11588         if (isa<AllocaInst>(GEP->getOperand(0))) {
11589           if (GEP->getOperand(0)->hasOneUse()) {
11590             EraseInstFromFunction(SI);
11591             ++NumCombined;
11592             return 0;
11593           }
11594           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11595             EraseInstFromFunction(*DI);
11596             EraseInstFromFunction(SI);
11597             ++NumCombined;
11598             return 0;
11599           }
11600         }
11601       }
11602     }
11603     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11604       EraseInstFromFunction(*DI);
11605       EraseInstFromFunction(SI);
11606       ++NumCombined;
11607       return 0;
11608     }
11609   }
11610
11611   // Attempt to improve the alignment.
11612   if (TD) {
11613     unsigned KnownAlign =
11614       GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11615     if (KnownAlign >
11616         (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11617                                   SI.getAlignment()))
11618       SI.setAlignment(KnownAlign);
11619   }
11620
11621   // Do really simple DSE, to catch cases where there are several consecutive
11622   // stores to the same location, separated by a few arithmetic operations. This
11623   // situation often occurs with bitfield accesses.
11624   BasicBlock::iterator BBI = &SI;
11625   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11626        --ScanInsts) {
11627     --BBI;
11628     // Don't count debug info directives, lest they affect codegen,
11629     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11630     // It is necessary for correctness to skip those that feed into a
11631     // llvm.dbg.declare, as these are not present when debugging is off.
11632     if (isa<DbgInfoIntrinsic>(BBI) ||
11633         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11634       ScanInsts++;
11635       continue;
11636     }    
11637     
11638     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11639       // Prev store isn't volatile, and stores to the same location?
11640       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11641                                                           SI.getOperand(1))) {
11642         ++NumDeadStore;
11643         ++BBI;
11644         EraseInstFromFunction(*PrevSI);
11645         continue;
11646       }
11647       break;
11648     }
11649     
11650     // If this is a load, we have to stop.  However, if the loaded value is from
11651     // the pointer we're loading and is producing the pointer we're storing,
11652     // then *this* store is dead (X = load P; store X -> P).
11653     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11654       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11655           !SI.isVolatile()) {
11656         EraseInstFromFunction(SI);
11657         ++NumCombined;
11658         return 0;
11659       }
11660       // Otherwise, this is a load from some other location.  Stores before it
11661       // may not be dead.
11662       break;
11663     }
11664     
11665     // Don't skip over loads or things that can modify memory.
11666     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11667       break;
11668   }
11669   
11670   
11671   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11672
11673   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11674   if (isa<ConstantPointerNull>(Ptr) &&
11675       cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11676     if (!isa<UndefValue>(Val)) {
11677       SI.setOperand(0, UndefValue::get(Val->getType()));
11678       if (Instruction *U = dyn_cast<Instruction>(Val))
11679         Worklist.Add(U);  // Dropped a use.
11680       ++NumCombined;
11681     }
11682     return 0;  // Do not modify these!
11683   }
11684
11685   // store undef, Ptr -> noop
11686   if (isa<UndefValue>(Val)) {
11687     EraseInstFromFunction(SI);
11688     ++NumCombined;
11689     return 0;
11690   }
11691
11692   // If the pointer destination is a cast, see if we can fold the cast into the
11693   // source instead.
11694   if (isa<CastInst>(Ptr))
11695     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11696       return Res;
11697   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11698     if (CE->isCast())
11699       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11700         return Res;
11701
11702   
11703   // If this store is the last instruction in the basic block (possibly
11704   // excepting debug info instructions and the pointer bitcasts that feed
11705   // into them), and if the block ends with an unconditional branch, try
11706   // to move it to the successor block.
11707   BBI = &SI; 
11708   do {
11709     ++BBI;
11710   } while (isa<DbgInfoIntrinsic>(BBI) ||
11711            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11712   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11713     if (BI->isUnconditional())
11714       if (SimplifyStoreAtEndOfBlock(SI))
11715         return 0;  // xform done!
11716   
11717   return 0;
11718 }
11719
11720 /// SimplifyStoreAtEndOfBlock - Turn things like:
11721 ///   if () { *P = v1; } else { *P = v2 }
11722 /// into a phi node with a store in the successor.
11723 ///
11724 /// Simplify things like:
11725 ///   *P = v1; if () { *P = v2; }
11726 /// into a phi node with a store in the successor.
11727 ///
11728 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11729   BasicBlock *StoreBB = SI.getParent();
11730   
11731   // Check to see if the successor block has exactly two incoming edges.  If
11732   // so, see if the other predecessor contains a store to the same location.
11733   // if so, insert a PHI node (if needed) and move the stores down.
11734   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11735   
11736   // Determine whether Dest has exactly two predecessors and, if so, compute
11737   // the other predecessor.
11738   pred_iterator PI = pred_begin(DestBB);
11739   BasicBlock *OtherBB = 0;
11740   if (*PI != StoreBB)
11741     OtherBB = *PI;
11742   ++PI;
11743   if (PI == pred_end(DestBB))
11744     return false;
11745   
11746   if (*PI != StoreBB) {
11747     if (OtherBB)
11748       return false;
11749     OtherBB = *PI;
11750   }
11751   if (++PI != pred_end(DestBB))
11752     return false;
11753
11754   // Bail out if all the relevant blocks aren't distinct (this can happen,
11755   // for example, if SI is in an infinite loop)
11756   if (StoreBB == DestBB || OtherBB == DestBB)
11757     return false;
11758
11759   // Verify that the other block ends in a branch and is not otherwise empty.
11760   BasicBlock::iterator BBI = OtherBB->getTerminator();
11761   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11762   if (!OtherBr || BBI == OtherBB->begin())
11763     return false;
11764   
11765   // If the other block ends in an unconditional branch, check for the 'if then
11766   // else' case.  there is an instruction before the branch.
11767   StoreInst *OtherStore = 0;
11768   if (OtherBr->isUnconditional()) {
11769     --BBI;
11770     // Skip over debugging info.
11771     while (isa<DbgInfoIntrinsic>(BBI) ||
11772            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11773       if (BBI==OtherBB->begin())
11774         return false;
11775       --BBI;
11776     }
11777     // If this isn't a store, or isn't a store to the same location, bail out.
11778     OtherStore = dyn_cast<StoreInst>(BBI);
11779     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11780       return false;
11781   } else {
11782     // Otherwise, the other block ended with a conditional branch. If one of the
11783     // destinations is StoreBB, then we have the if/then case.
11784     if (OtherBr->getSuccessor(0) != StoreBB && 
11785         OtherBr->getSuccessor(1) != StoreBB)
11786       return false;
11787     
11788     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11789     // if/then triangle.  See if there is a store to the same ptr as SI that
11790     // lives in OtherBB.
11791     for (;; --BBI) {
11792       // Check to see if we find the matching store.
11793       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11794         if (OtherStore->getOperand(1) != SI.getOperand(1))
11795           return false;
11796         break;
11797       }
11798       // If we find something that may be using or overwriting the stored
11799       // value, or if we run out of instructions, we can't do the xform.
11800       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11801           BBI == OtherBB->begin())
11802         return false;
11803     }
11804     
11805     // In order to eliminate the store in OtherBr, we have to
11806     // make sure nothing reads or overwrites the stored value in
11807     // StoreBB.
11808     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11809       // FIXME: This should really be AA driven.
11810       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11811         return false;
11812     }
11813   }
11814   
11815   // Insert a PHI node now if we need it.
11816   Value *MergedVal = OtherStore->getOperand(0);
11817   if (MergedVal != SI.getOperand(0)) {
11818     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11819     PN->reserveOperandSpace(2);
11820     PN->addIncoming(SI.getOperand(0), SI.getParent());
11821     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11822     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11823   }
11824   
11825   // Advance to a place where it is safe to insert the new store and
11826   // insert it.
11827   BBI = DestBB->getFirstNonPHI();
11828   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11829                                     OtherStore->isVolatile()), *BBI);
11830   
11831   // Nuke the old stores.
11832   EraseInstFromFunction(SI);
11833   EraseInstFromFunction(*OtherStore);
11834   ++NumCombined;
11835   return true;
11836 }
11837
11838
11839 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11840   // Change br (not X), label True, label False to: br X, label False, True
11841   Value *X = 0;
11842   BasicBlock *TrueDest;
11843   BasicBlock *FalseDest;
11844   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11845       !isa<Constant>(X)) {
11846     // Swap Destinations and condition...
11847     BI.setCondition(X);
11848     BI.setSuccessor(0, FalseDest);
11849     BI.setSuccessor(1, TrueDest);
11850     return &BI;
11851   }
11852
11853   // Cannonicalize fcmp_one -> fcmp_oeq
11854   FCmpInst::Predicate FPred; Value *Y;
11855   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11856                              TrueDest, FalseDest)) &&
11857       BI.getCondition()->hasOneUse())
11858     if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11859         FPred == FCmpInst::FCMP_OGE) {
11860       FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11861       Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11862       
11863       // Swap Destinations and condition.
11864       BI.setSuccessor(0, FalseDest);
11865       BI.setSuccessor(1, TrueDest);
11866       Worklist.Add(Cond);
11867       return &BI;
11868     }
11869
11870   // Cannonicalize icmp_ne -> icmp_eq
11871   ICmpInst::Predicate IPred;
11872   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11873                       TrueDest, FalseDest)) &&
11874       BI.getCondition()->hasOneUse())
11875     if (IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
11876         IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11877         IPred == ICmpInst::ICMP_SGE) {
11878       ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11879       Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11880       // Swap Destinations and condition.
11881       BI.setSuccessor(0, FalseDest);
11882       BI.setSuccessor(1, TrueDest);
11883       Worklist.Add(Cond);
11884       return &BI;
11885     }
11886
11887   return 0;
11888 }
11889
11890 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11891   Value *Cond = SI.getCondition();
11892   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11893     if (I->getOpcode() == Instruction::Add)
11894       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11895         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11896         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11897           SI.setOperand(i,
11898                    ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11899                                                 AddRHS));
11900         SI.setOperand(0, I->getOperand(0));
11901         Worklist.Add(I);
11902         return &SI;
11903       }
11904   }
11905   return 0;
11906 }
11907
11908 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
11909   Value *Agg = EV.getAggregateOperand();
11910
11911   if (!EV.hasIndices())
11912     return ReplaceInstUsesWith(EV, Agg);
11913
11914   if (Constant *C = dyn_cast<Constant>(Agg)) {
11915     if (isa<UndefValue>(C))
11916       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11917       
11918     if (isa<ConstantAggregateZero>(C))
11919       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11920
11921     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11922       // Extract the element indexed by the first index out of the constant
11923       Value *V = C->getOperand(*EV.idx_begin());
11924       if (EV.getNumIndices() > 1)
11925         // Extract the remaining indices out of the constant indexed by the
11926         // first index
11927         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11928       else
11929         return ReplaceInstUsesWith(EV, V);
11930     }
11931     return 0; // Can't handle other constants
11932   } 
11933   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11934     // We're extracting from an insertvalue instruction, compare the indices
11935     const unsigned *exti, *exte, *insi, *inse;
11936     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11937          exte = EV.idx_end(), inse = IV->idx_end();
11938          exti != exte && insi != inse;
11939          ++exti, ++insi) {
11940       if (*insi != *exti)
11941         // The insert and extract both reference distinctly different elements.
11942         // This means the extract is not influenced by the insert, and we can
11943         // replace the aggregate operand of the extract with the aggregate
11944         // operand of the insert. i.e., replace
11945         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11946         // %E = extractvalue { i32, { i32 } } %I, 0
11947         // with
11948         // %E = extractvalue { i32, { i32 } } %A, 0
11949         return ExtractValueInst::Create(IV->getAggregateOperand(),
11950                                         EV.idx_begin(), EV.idx_end());
11951     }
11952     if (exti == exte && insi == inse)
11953       // Both iterators are at the end: Index lists are identical. Replace
11954       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11955       // %C = extractvalue { i32, { i32 } } %B, 1, 0
11956       // with "i32 42"
11957       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11958     if (exti == exte) {
11959       // The extract list is a prefix of the insert list. i.e. replace
11960       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11961       // %E = extractvalue { i32, { i32 } } %I, 1
11962       // with
11963       // %X = extractvalue { i32, { i32 } } %A, 1
11964       // %E = insertvalue { i32 } %X, i32 42, 0
11965       // by switching the order of the insert and extract (though the
11966       // insertvalue should be left in, since it may have other uses).
11967       Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
11968                                                  EV.idx_begin(), EV.idx_end());
11969       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11970                                      insi, inse);
11971     }
11972     if (insi == inse)
11973       // The insert list is a prefix of the extract list
11974       // We can simply remove the common indices from the extract and make it
11975       // operate on the inserted value instead of the insertvalue result.
11976       // i.e., replace
11977       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11978       // %E = extractvalue { i32, { i32 } } %I, 1, 0
11979       // with
11980       // %E extractvalue { i32 } { i32 42 }, 0
11981       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
11982                                       exti, exte);
11983   }
11984   // Can't simplify extracts from other values. Note that nested extracts are
11985   // already simplified implicitely by the above (extract ( extract (insert) )
11986   // will be translated into extract ( insert ( extract ) ) first and then just
11987   // the value inserted, if appropriate).
11988   return 0;
11989 }
11990
11991 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11992 /// is to leave as a vector operation.
11993 static bool CheapToScalarize(Value *V, bool isConstant) {
11994   if (isa<ConstantAggregateZero>(V)) 
11995     return true;
11996   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11997     if (isConstant) return true;
11998     // If all elts are the same, we can extract.
11999     Constant *Op0 = C->getOperand(0);
12000     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12001       if (C->getOperand(i) != Op0)
12002         return false;
12003     return true;
12004   }
12005   Instruction *I = dyn_cast<Instruction>(V);
12006   if (!I) return false;
12007   
12008   // Insert element gets simplified to the inserted element or is deleted if
12009   // this is constant idx extract element and its a constant idx insertelt.
12010   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12011       isa<ConstantInt>(I->getOperand(2)))
12012     return true;
12013   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12014     return true;
12015   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12016     if (BO->hasOneUse() &&
12017         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12018          CheapToScalarize(BO->getOperand(1), isConstant)))
12019       return true;
12020   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12021     if (CI->hasOneUse() &&
12022         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12023          CheapToScalarize(CI->getOperand(1), isConstant)))
12024       return true;
12025   
12026   return false;
12027 }
12028
12029 /// Read and decode a shufflevector mask.
12030 ///
12031 /// It turns undef elements into values that are larger than the number of
12032 /// elements in the input.
12033 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12034   unsigned NElts = SVI->getType()->getNumElements();
12035   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12036     return std::vector<unsigned>(NElts, 0);
12037   if (isa<UndefValue>(SVI->getOperand(2)))
12038     return std::vector<unsigned>(NElts, 2*NElts);
12039
12040   std::vector<unsigned> Result;
12041   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12042   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12043     if (isa<UndefValue>(*i))
12044       Result.push_back(NElts*2);  // undef -> 8
12045     else
12046       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12047   return Result;
12048 }
12049
12050 /// FindScalarElement - Given a vector and an element number, see if the scalar
12051 /// value is already around as a register, for example if it were inserted then
12052 /// extracted from the vector.
12053 static Value *FindScalarElement(Value *V, unsigned EltNo,
12054                                 LLVMContext *Context) {
12055   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12056   const VectorType *PTy = cast<VectorType>(V->getType());
12057   unsigned Width = PTy->getNumElements();
12058   if (EltNo >= Width)  // Out of range access.
12059     return UndefValue::get(PTy->getElementType());
12060   
12061   if (isa<UndefValue>(V))
12062     return UndefValue::get(PTy->getElementType());
12063   else if (isa<ConstantAggregateZero>(V))
12064     return Constant::getNullValue(PTy->getElementType());
12065   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12066     return CP->getOperand(EltNo);
12067   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12068     // If this is an insert to a variable element, we don't know what it is.
12069     if (!isa<ConstantInt>(III->getOperand(2))) 
12070       return 0;
12071     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12072     
12073     // If this is an insert to the element we are looking for, return the
12074     // inserted value.
12075     if (EltNo == IIElt) 
12076       return III->getOperand(1);
12077     
12078     // Otherwise, the insertelement doesn't modify the value, recurse on its
12079     // vector input.
12080     return FindScalarElement(III->getOperand(0), EltNo, Context);
12081   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12082     unsigned LHSWidth =
12083       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12084     unsigned InEl = getShuffleMask(SVI)[EltNo];
12085     if (InEl < LHSWidth)
12086       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12087     else if (InEl < LHSWidth*2)
12088       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12089     else
12090       return UndefValue::get(PTy->getElementType());
12091   }
12092   
12093   // Otherwise, we don't know.
12094   return 0;
12095 }
12096
12097 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12098   // If vector val is undef, replace extract with scalar undef.
12099   if (isa<UndefValue>(EI.getOperand(0)))
12100     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12101
12102   // If vector val is constant 0, replace extract with scalar 0.
12103   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12104     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12105   
12106   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12107     // If vector val is constant with all elements the same, replace EI with
12108     // that element. When the elements are not identical, we cannot replace yet
12109     // (we do that below, but only when the index is constant).
12110     Constant *op0 = C->getOperand(0);
12111     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12112       if (C->getOperand(i) != op0) {
12113         op0 = 0; 
12114         break;
12115       }
12116     if (op0)
12117       return ReplaceInstUsesWith(EI, op0);
12118   }
12119   
12120   // If extracting a specified index from the vector, see if we can recursively
12121   // find a previously computed scalar that was inserted into the vector.
12122   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12123     unsigned IndexVal = IdxC->getZExtValue();
12124     unsigned VectorWidth = 
12125       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12126       
12127     // If this is extracting an invalid index, turn this into undef, to avoid
12128     // crashing the code below.
12129     if (IndexVal >= VectorWidth)
12130       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12131     
12132     // This instruction only demands the single element from the input vector.
12133     // If the input vector has a single use, simplify it based on this use
12134     // property.
12135     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12136       APInt UndefElts(VectorWidth, 0);
12137       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12138       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12139                                                 DemandedMask, UndefElts)) {
12140         EI.setOperand(0, V);
12141         return &EI;
12142       }
12143     }
12144     
12145     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12146       return ReplaceInstUsesWith(EI, Elt);
12147     
12148     // If the this extractelement is directly using a bitcast from a vector of
12149     // the same number of elements, see if we can find the source element from
12150     // it.  In this case, we will end up needing to bitcast the scalars.
12151     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12152       if (const VectorType *VT = 
12153               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12154         if (VT->getNumElements() == VectorWidth)
12155           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12156                                              IndexVal, Context))
12157             return new BitCastInst(Elt, EI.getType());
12158     }
12159   }
12160   
12161   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12162     if (I->hasOneUse()) {
12163       // Push extractelement into predecessor operation if legal and
12164       // profitable to do so
12165       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12166         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12167         if (CheapToScalarize(BO, isConstantElt)) {
12168           Value *newEI0 =
12169             Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12170                                           EI.getName()+".lhs");
12171           Value *newEI1 =
12172             Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12173                                           EI.getName()+".rhs");
12174           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12175         }
12176       } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
12177         unsigned AS = LI->getPointerAddressSpace();
12178         Value *Ptr = Builder->CreateBitCast(I->getOperand(0),
12179                                             PointerType::get(EI.getType(), AS),
12180                                             I->getOperand(0)->getName());
12181         Value *GEP =
12182           Builder->CreateGEP(Ptr, EI.getOperand(1), I->getName()+".gep");
12183         cast<GEPOperator>(GEP)->setIsInBounds(true);
12184         
12185         LoadInst *Load = Builder->CreateLoad(GEP, "tmp");
12186
12187         // Make sure the Load goes before the load instruction in the source,
12188         // not wherever the extract happens to be.
12189         if (Instruction *P = dyn_cast<Instruction>(Ptr))
12190           P->moveBefore(I);
12191         if (Instruction *G = dyn_cast<Instruction>(GEP))
12192           G->moveBefore(I);
12193         Load->moveBefore(I);
12194         
12195         return ReplaceInstUsesWith(EI, Load);
12196       }
12197     }
12198     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12199       // Extracting the inserted element?
12200       if (IE->getOperand(2) == EI.getOperand(1))
12201         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12202       // If the inserted and extracted elements are constants, they must not
12203       // be the same value, extract from the pre-inserted value instead.
12204       if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
12205         Worklist.AddValue(EI.getOperand(0));
12206         EI.setOperand(0, IE->getOperand(0));
12207         return &EI;
12208       }
12209     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12210       // If this is extracting an element from a shufflevector, figure out where
12211       // it came from and extract from the appropriate input element instead.
12212       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12213         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12214         Value *Src;
12215         unsigned LHSWidth =
12216           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12217
12218         if (SrcIdx < LHSWidth)
12219           Src = SVI->getOperand(0);
12220         else if (SrcIdx < LHSWidth*2) {
12221           SrcIdx -= LHSWidth;
12222           Src = SVI->getOperand(1);
12223         } else {
12224           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12225         }
12226         return ExtractElementInst::Create(Src,
12227                          ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12228                                           false));
12229       }
12230     }
12231     // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12232   }
12233   return 0;
12234 }
12235
12236 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12237 /// elements from either LHS or RHS, return the shuffle mask and true. 
12238 /// Otherwise, return false.
12239 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12240                                          std::vector<Constant*> &Mask,
12241                                          LLVMContext *Context) {
12242   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12243          "Invalid CollectSingleShuffleElements");
12244   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12245
12246   if (isa<UndefValue>(V)) {
12247     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12248     return true;
12249   } else if (V == LHS) {
12250     for (unsigned i = 0; i != NumElts; ++i)
12251       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12252     return true;
12253   } else if (V == RHS) {
12254     for (unsigned i = 0; i != NumElts; ++i)
12255       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
12256     return true;
12257   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12258     // If this is an insert of an extract from some other vector, include it.
12259     Value *VecOp    = IEI->getOperand(0);
12260     Value *ScalarOp = IEI->getOperand(1);
12261     Value *IdxOp    = IEI->getOperand(2);
12262     
12263     if (!isa<ConstantInt>(IdxOp))
12264       return false;
12265     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12266     
12267     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12268       // Okay, we can handle this if the vector we are insertinting into is
12269       // transitively ok.
12270       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12271         // If so, update the mask to reflect the inserted undef.
12272         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
12273         return true;
12274       }      
12275     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12276       if (isa<ConstantInt>(EI->getOperand(1)) &&
12277           EI->getOperand(0)->getType() == V->getType()) {
12278         unsigned ExtractedIdx =
12279           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12280         
12281         // This must be extracting from either LHS or RHS.
12282         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12283           // Okay, we can handle this if the vector we are insertinting into is
12284           // transitively ok.
12285           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12286             // If so, update the mask to reflect the inserted value.
12287             if (EI->getOperand(0) == LHS) {
12288               Mask[InsertedIdx % NumElts] = 
12289                  ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12290             } else {
12291               assert(EI->getOperand(0) == RHS);
12292               Mask[InsertedIdx % NumElts] = 
12293                 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
12294               
12295             }
12296             return true;
12297           }
12298         }
12299       }
12300     }
12301   }
12302   // TODO: Handle shufflevector here!
12303   
12304   return false;
12305 }
12306
12307 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12308 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12309 /// that computes V and the LHS value of the shuffle.
12310 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12311                                      Value *&RHS, LLVMContext *Context) {
12312   assert(isa<VectorType>(V->getType()) && 
12313          (RHS == 0 || V->getType() == RHS->getType()) &&
12314          "Invalid shuffle!");
12315   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12316
12317   if (isa<UndefValue>(V)) {
12318     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12319     return V;
12320   } else if (isa<ConstantAggregateZero>(V)) {
12321     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
12322     return V;
12323   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12324     // If this is an insert of an extract from some other vector, include it.
12325     Value *VecOp    = IEI->getOperand(0);
12326     Value *ScalarOp = IEI->getOperand(1);
12327     Value *IdxOp    = IEI->getOperand(2);
12328     
12329     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12330       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12331           EI->getOperand(0)->getType() == V->getType()) {
12332         unsigned ExtractedIdx =
12333           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12334         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12335         
12336         // Either the extracted from or inserted into vector must be RHSVec,
12337         // otherwise we'd end up with a shuffle of three inputs.
12338         if (EI->getOperand(0) == RHS || RHS == 0) {
12339           RHS = EI->getOperand(0);
12340           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12341           Mask[InsertedIdx % NumElts] = 
12342             ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
12343           return V;
12344         }
12345         
12346         if (VecOp == RHS) {
12347           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12348                                             RHS, Context);
12349           // Everything but the extracted element is replaced with the RHS.
12350           for (unsigned i = 0; i != NumElts; ++i) {
12351             if (i != InsertedIdx)
12352               Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
12353           }
12354           return V;
12355         }
12356         
12357         // If this insertelement is a chain that comes from exactly these two
12358         // vectors, return the vector and the effective shuffle.
12359         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12360                                          Context))
12361           return EI->getOperand(0);
12362         
12363       }
12364     }
12365   }
12366   // TODO: Handle shufflevector here!
12367   
12368   // Otherwise, can't do anything fancy.  Return an identity vector.
12369   for (unsigned i = 0; i != NumElts; ++i)
12370     Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12371   return V;
12372 }
12373
12374 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12375   Value *VecOp    = IE.getOperand(0);
12376   Value *ScalarOp = IE.getOperand(1);
12377   Value *IdxOp    = IE.getOperand(2);
12378   
12379   // Inserting an undef or into an undefined place, remove this.
12380   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12381     ReplaceInstUsesWith(IE, VecOp);
12382   
12383   // If the inserted element was extracted from some other vector, and if the 
12384   // indexes are constant, try to turn this into a shufflevector operation.
12385   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12386     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12387         EI->getOperand(0)->getType() == IE.getType()) {
12388       unsigned NumVectorElts = IE.getType()->getNumElements();
12389       unsigned ExtractedIdx =
12390         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12391       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12392       
12393       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12394         return ReplaceInstUsesWith(IE, VecOp);
12395       
12396       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12397         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12398       
12399       // If we are extracting a value from a vector, then inserting it right
12400       // back into the same place, just use the input vector.
12401       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12402         return ReplaceInstUsesWith(IE, VecOp);      
12403       
12404       // We could theoretically do this for ANY input.  However, doing so could
12405       // turn chains of insertelement instructions into a chain of shufflevector
12406       // instructions, and right now we do not merge shufflevectors.  As such,
12407       // only do this in a situation where it is clear that there is benefit.
12408       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12409         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12410         // the values of VecOp, except then one read from EIOp0.
12411         // Build a new shuffle mask.
12412         std::vector<Constant*> Mask;
12413         if (isa<UndefValue>(VecOp))
12414           Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
12415         else {
12416           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12417           Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
12418                                                        NumVectorElts));
12419         } 
12420         Mask[InsertedIdx] = 
12421                            ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12422         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12423                                      ConstantVector::get(Mask));
12424       }
12425       
12426       // If this insertelement isn't used by some other insertelement, turn it
12427       // (and any insertelements it points to), into one big shuffle.
12428       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12429         std::vector<Constant*> Mask;
12430         Value *RHS = 0;
12431         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12432         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12433         // We now have a shuffle of LHS, RHS, Mask.
12434         return new ShuffleVectorInst(LHS, RHS,
12435                                      ConstantVector::get(Mask));
12436       }
12437     }
12438   }
12439
12440   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12441   APInt UndefElts(VWidth, 0);
12442   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12443   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12444     return &IE;
12445
12446   return 0;
12447 }
12448
12449
12450 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12451   Value *LHS = SVI.getOperand(0);
12452   Value *RHS = SVI.getOperand(1);
12453   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12454
12455   bool MadeChange = false;
12456
12457   // Undefined shuffle mask -> undefined value.
12458   if (isa<UndefValue>(SVI.getOperand(2)))
12459     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12460
12461   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12462
12463   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12464     return 0;
12465
12466   APInt UndefElts(VWidth, 0);
12467   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12468   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12469     LHS = SVI.getOperand(0);
12470     RHS = SVI.getOperand(1);
12471     MadeChange = true;
12472   }
12473   
12474   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12475   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12476   if (LHS == RHS || isa<UndefValue>(LHS)) {
12477     if (isa<UndefValue>(LHS) && LHS == RHS) {
12478       // shuffle(undef,undef,mask) -> undef.
12479       return ReplaceInstUsesWith(SVI, LHS);
12480     }
12481     
12482     // Remap any references to RHS to use LHS.
12483     std::vector<Constant*> Elts;
12484     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12485       if (Mask[i] >= 2*e)
12486         Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12487       else {
12488         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12489             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12490           Mask[i] = 2*e;     // Turn into undef.
12491           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12492         } else {
12493           Mask[i] = Mask[i] % e;  // Force to LHS.
12494           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
12495         }
12496       }
12497     }
12498     SVI.setOperand(0, SVI.getOperand(1));
12499     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12500     SVI.setOperand(2, ConstantVector::get(Elts));
12501     LHS = SVI.getOperand(0);
12502     RHS = SVI.getOperand(1);
12503     MadeChange = true;
12504   }
12505   
12506   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12507   bool isLHSID = true, isRHSID = true;
12508     
12509   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12510     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12511     // Is this an identity shuffle of the LHS value?
12512     isLHSID &= (Mask[i] == i);
12513       
12514     // Is this an identity shuffle of the RHS value?
12515     isRHSID &= (Mask[i]-e == i);
12516   }
12517
12518   // Eliminate identity shuffles.
12519   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12520   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12521   
12522   // If the LHS is a shufflevector itself, see if we can combine it with this
12523   // one without producing an unusual shuffle.  Here we are really conservative:
12524   // we are absolutely afraid of producing a shuffle mask not in the input
12525   // program, because the code gen may not be smart enough to turn a merged
12526   // shuffle into two specific shuffles: it may produce worse code.  As such,
12527   // we only merge two shuffles if the result is one of the two input shuffle
12528   // masks.  In this case, merging the shuffles just removes one instruction,
12529   // which we know is safe.  This is good for things like turning:
12530   // (splat(splat)) -> splat.
12531   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12532     if (isa<UndefValue>(RHS)) {
12533       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12534
12535       std::vector<unsigned> NewMask;
12536       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12537         if (Mask[i] >= 2*e)
12538           NewMask.push_back(2*e);
12539         else
12540           NewMask.push_back(LHSMask[Mask[i]]);
12541       
12542       // If the result mask is equal to the src shuffle or this shuffle mask, do
12543       // the replacement.
12544       if (NewMask == LHSMask || NewMask == Mask) {
12545         unsigned LHSInNElts =
12546           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12547         std::vector<Constant*> Elts;
12548         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12549           if (NewMask[i] >= LHSInNElts*2) {
12550             Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12551           } else {
12552             Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
12553           }
12554         }
12555         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12556                                      LHSSVI->getOperand(1),
12557                                      ConstantVector::get(Elts));
12558       }
12559     }
12560   }
12561
12562   return MadeChange ? &SVI : 0;
12563 }
12564
12565
12566
12567
12568 /// TryToSinkInstruction - Try to move the specified instruction from its
12569 /// current block into the beginning of DestBlock, which can only happen if it's
12570 /// safe to move the instruction past all of the instructions between it and the
12571 /// end of its block.
12572 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12573   assert(I->hasOneUse() && "Invariants didn't hold!");
12574
12575   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12576   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12577     return false;
12578
12579   // Do not sink alloca instructions out of the entry block.
12580   if (isa<AllocaInst>(I) && I->getParent() ==
12581         &DestBlock->getParent()->getEntryBlock())
12582     return false;
12583
12584   // We can only sink load instructions if there is nothing between the load and
12585   // the end of block that could change the value.
12586   if (I->mayReadFromMemory()) {
12587     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12588          Scan != E; ++Scan)
12589       if (Scan->mayWriteToMemory())
12590         return false;
12591   }
12592
12593   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12594
12595   CopyPrecedingStopPoint(I, InsertPos);
12596   I->moveBefore(InsertPos);
12597   ++NumSunkInst;
12598   return true;
12599 }
12600
12601
12602 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12603 /// all reachable code to the worklist.
12604 ///
12605 /// This has a couple of tricks to make the code faster and more powerful.  In
12606 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12607 /// them to the worklist (this significantly speeds up instcombine on code where
12608 /// many instructions are dead or constant).  Additionally, if we find a branch
12609 /// whose condition is a known constant, we only visit the reachable successors.
12610 ///
12611 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12612                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12613                                        InstCombiner &IC,
12614                                        const TargetData *TD) {
12615   SmallVector<BasicBlock*, 256> Worklist;
12616   Worklist.push_back(BB);
12617
12618   while (!Worklist.empty()) {
12619     BB = Worklist.back();
12620     Worklist.pop_back();
12621     
12622     // We have now visited this block!  If we've already been here, ignore it.
12623     if (!Visited.insert(BB)) continue;
12624
12625     DbgInfoIntrinsic *DBI_Prev = NULL;
12626     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12627       Instruction *Inst = BBI++;
12628       
12629       // DCE instruction if trivially dead.
12630       if (isInstructionTriviallyDead(Inst)) {
12631         ++NumDeadInst;
12632         DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
12633         Inst->eraseFromParent();
12634         continue;
12635       }
12636       
12637       // ConstantProp instruction if trivially constant.
12638       if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12639         DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12640                      << *Inst << '\n');
12641         Inst->replaceAllUsesWith(C);
12642         ++NumConstProp;
12643         Inst->eraseFromParent();
12644         continue;
12645       }
12646      
12647       // If there are two consecutive llvm.dbg.stoppoint calls then
12648       // it is likely that the optimizer deleted code in between these
12649       // two intrinsics. 
12650       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12651       if (DBI_Next) {
12652         if (DBI_Prev
12653             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12654             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12655           IC.Worklist.Remove(DBI_Prev);
12656           DBI_Prev->eraseFromParent();
12657         }
12658         DBI_Prev = DBI_Next;
12659       } else {
12660         DBI_Prev = 0;
12661       }
12662
12663       IC.Worklist.Add(Inst);
12664     }
12665
12666     // Recursively visit successors.  If this is a branch or switch on a
12667     // constant, only visit the reachable successor.
12668     TerminatorInst *TI = BB->getTerminator();
12669     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12670       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12671         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12672         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12673         Worklist.push_back(ReachableBB);
12674         continue;
12675       }
12676     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12677       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12678         // See if this is an explicit destination.
12679         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12680           if (SI->getCaseValue(i) == Cond) {
12681             BasicBlock *ReachableBB = SI->getSuccessor(i);
12682             Worklist.push_back(ReachableBB);
12683             continue;
12684           }
12685         
12686         // Otherwise it is the default destination.
12687         Worklist.push_back(SI->getSuccessor(0));
12688         continue;
12689       }
12690     }
12691     
12692     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12693       Worklist.push_back(TI->getSuccessor(i));
12694   }
12695 }
12696
12697 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12698   bool Changed = false;
12699   TD = getAnalysisIfAvailable<TargetData>();
12700   
12701   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12702         << F.getNameStr() << "\n");
12703
12704   {
12705     // Do a depth-first traversal of the function, populate the worklist with
12706     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12707     // track of which blocks we visit.
12708     SmallPtrSet<BasicBlock*, 64> Visited;
12709     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12710
12711     // Do a quick scan over the function.  If we find any blocks that are
12712     // unreachable, remove any instructions inside of them.  This prevents
12713     // the instcombine code from having to deal with some bad special cases.
12714     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12715       if (!Visited.count(BB)) {
12716         Instruction *Term = BB->getTerminator();
12717         while (Term != BB->begin()) {   // Remove instrs bottom-up
12718           BasicBlock::iterator I = Term; --I;
12719
12720           DEBUG(errs() << "IC: DCE: " << *I << '\n');
12721           // A debug intrinsic shouldn't force another iteration if we weren't
12722           // going to do one without it.
12723           if (!isa<DbgInfoIntrinsic>(I)) {
12724             ++NumDeadInst;
12725             Changed = true;
12726           }
12727           if (!I->use_empty())
12728             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12729           I->eraseFromParent();
12730         }
12731       }
12732   }
12733
12734   while (!Worklist.isEmpty()) {
12735     Instruction *I = Worklist.RemoveOne();
12736     if (I == 0) continue;  // skip null values.
12737
12738     // Check to see if we can DCE the instruction.
12739     if (isInstructionTriviallyDead(I)) {
12740       DEBUG(errs() << "IC: DCE: " << *I << '\n');
12741       EraseInstFromFunction(*I);
12742       ++NumDeadInst;
12743       Changed = true;
12744       continue;
12745     }
12746
12747     // Instruction isn't dead, see if we can constant propagate it.
12748     if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12749       DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
12750
12751       // Add operands to the worklist.
12752       ReplaceInstUsesWith(*I, C);
12753       ++NumConstProp;
12754       EraseInstFromFunction(*I);
12755       Changed = true;
12756       continue;
12757     }
12758
12759     if (TD) {
12760       // See if we can constant fold its operands.
12761       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12762         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12763           if (Constant *NewC = ConstantFoldConstantExpression(CE,   
12764                                   F.getContext(), TD))
12765             if (NewC != CE) {
12766               i->set(NewC);
12767               Changed = true;
12768             }
12769     }
12770
12771     // See if we can trivially sink this instruction to a successor basic block.
12772     if (I->hasOneUse()) {
12773       BasicBlock *BB = I->getParent();
12774       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12775       if (UserParent != BB) {
12776         bool UserIsSuccessor = false;
12777         // See if the user is one of our successors.
12778         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12779           if (*SI == UserParent) {
12780             UserIsSuccessor = true;
12781             break;
12782           }
12783
12784         // If the user is one of our immediate successors, and if that successor
12785         // only has us as a predecessors (we'd have to split the critical edge
12786         // otherwise), we can keep going.
12787         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12788             next(pred_begin(UserParent)) == pred_end(UserParent))
12789           // Okay, the CFG is simple enough, try to sink this instruction.
12790           Changed |= TryToSinkInstruction(I, UserParent);
12791       }
12792     }
12793
12794     // Now that we have an instruction, try combining it to simplify it.
12795     Builder->SetInsertPoint(I->getParent(), I);
12796     
12797 #ifndef NDEBUG
12798     std::string OrigI;
12799 #endif
12800     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
12801     
12802     if (Instruction *Result = visit(*I)) {
12803       ++NumCombined;
12804       // Should we replace the old instruction with a new one?
12805       if (Result != I) {
12806         DEBUG(errs() << "IC: Old = " << *I << '\n'
12807                      << "    New = " << *Result << '\n');
12808
12809         // Everything uses the new instruction now.
12810         I->replaceAllUsesWith(Result);
12811
12812         // Push the new instruction and any users onto the worklist.
12813         Worklist.Add(Result);
12814         Worklist.AddUsersToWorkList(*Result);
12815
12816         // Move the name to the new instruction first.
12817         Result->takeName(I);
12818
12819         // Insert the new instruction into the basic block...
12820         BasicBlock *InstParent = I->getParent();
12821         BasicBlock::iterator InsertPos = I;
12822
12823         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12824           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12825             ++InsertPos;
12826
12827         InstParent->getInstList().insert(InsertPos, Result);
12828
12829         EraseInstFromFunction(*I);
12830       } else {
12831 #ifndef NDEBUG
12832         DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12833                      << "    New = " << *I << '\n');
12834 #endif
12835
12836         // If the instruction was modified, it's possible that it is now dead.
12837         // if so, remove it.
12838         if (isInstructionTriviallyDead(I)) {
12839           EraseInstFromFunction(*I);
12840         } else {
12841           Worklist.Add(I);
12842           Worklist.AddUsersToWorkList(*I);
12843         }
12844       }
12845       Changed = true;
12846     }
12847   }
12848
12849   Worklist.Zap();
12850   return Changed;
12851 }
12852
12853
12854 bool InstCombiner::runOnFunction(Function &F) {
12855   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12856   Context = &F.getContext();
12857   
12858   
12859   /// Builder - This is an IRBuilder that automatically inserts new
12860   /// instructions into the worklist when they are created.
12861   IRBuilder<true, ConstantFolder, InstCombineIRInserter> 
12862     TheBuilder(F.getContext(), ConstantFolder(F.getContext()),
12863                InstCombineIRInserter(Worklist));
12864   Builder = &TheBuilder;
12865   
12866   bool EverMadeChange = false;
12867
12868   // Iterate while there is work to do.
12869   unsigned Iteration = 0;
12870   while (DoOneIteration(F, Iteration++))
12871     EverMadeChange = true;
12872   
12873   Builder = 0;
12874   return EverMadeChange;
12875 }
12876
12877 FunctionPass *llvm::createInstructionCombiningPass() {
12878   return new InstCombiner();
12879 }